import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Camera } from 'lucide-react';
import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Separator } from '@/components/ui/separator';
import { AvatarCropDialog } from './AvatarCropDialog';

export function ProfileSection() {
  const { t } = useTranslation();
  const authStatusQuery = trpc.auth.status.useQuery(undefined, {
    staleTime: 5 * 60 * 1000,
  });
  const updateProfileMutation = trpc.auth.updateProfile.useMutation();
  const updateAvatarMutation = trpc.auth.updateAvatar.useMutation();
  const utils = trpc.useUtils();
  const { notify, notifyError } = useNotify();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [rawImageSrc, setRawImageSrc] = useState<string | null>(null);

  const profile = authStatusQuery.data?.profile;

  const [name, setName] = useState('');
  const [surname, setSurname] = useState('');

  useEffect(() => {
    if (profile?.name) setName(profile.name);
    if (profile?.surname) setSurname(profile.surname);
  }, [profile?.name, profile?.surname]);

  const displayName =
    [profile?.name, profile?.surname].filter(Boolean).join(' ') ||
    profile?.email?.split('@')[0] ||
    '';
  const initials =
    profile?.name && profile?.surname
      ? `${profile.name[0]}${profile.surname[0]}`.toUpperCase()
      : (profile?.email?.split('@')[0] ?? 'U').slice(0, 2).toUpperCase();

  function handleSave() {
    updateProfileMutation.mutate(
      { name: name || undefined, surname: surname || undefined },
      {
        onSuccess: () => {
          notify('success', 'toast.profile.updated');
          void utils.auth.status.invalidate();
        },
        onError: (err) => notifyError('toast.profile.updateError', err),
      },
    );
  }

  function handleAvatarClick() {
    fileInputRef.current?.click();
  }

  function handleAvatarChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = () => {
      setRawImageSrc(reader.result as string);
    };
    reader.readAsDataURL(file);
    // Reset input so the same file can be re-selected
    e.target.value = '';
  }

  function handleCropDone(croppedDataUrl: string) {
    setRawImageSrc(null);
    updateAvatarMutation.mutate(
      { avatarUrl: croppedDataUrl },
      {
        onSuccess: () => {
          notify('success', 'toast.profile.updated');
          void utils.auth.status.invalidate();
        },
        onError: (err) => notifyError('toast.profile.updateError', err),
      },
    );
  }

  return (
    <>
      {/* Avatar */}
      <div className="flex items-center gap-5">
        <div className="relative group">
          <Avatar className="size-20 rounded-full">
            {profile?.avatarUrl && (
              <AvatarImage src={profile.avatarUrl} alt={displayName} />
            )}
            <AvatarFallback className="rounded-full text-lg font-medium">
              {initials}
            </AvatarFallback>
          </Avatar>
          <button
            type="button"
            onClick={handleAvatarClick}
            className="absolute inset-0 flex items-center justify-center rounded-full bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
          >
            <Camera className="size-5 text-white" />
          </button>
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            className="hidden"
            onChange={handleAvatarChange}
          />
        </div>
        <div className="flex flex-col gap-0.5">
          <p className="font-medium">{displayName}</p>
          <p className="text-sm text-muted-foreground">{profile?.email}</p>
        </div>
      </div>

      <Separator />

      {/* Name fields */}
      <div className="flex flex-col gap-4">
        <div className="grid grid-cols-2 gap-4">
          <div className="flex flex-col gap-1.5">
            <Label htmlFor="profileName" className="text-xs">
              {t('settings.namePlaceholder')}
            </Label>
            <Input
              id="profileName"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={t('settings.namePlaceholder')}
              onKeyDown={(e) => e.key === 'Enter' && handleSave()}
            />
          </div>
          <div className="flex flex-col gap-1.5">
            <Label htmlFor="profileSurname" className="text-xs">
              {t('settings.surnamePlaceholder')}
            </Label>
            <Input
              id="profileSurname"
              value={surname}
              onChange={(e) => setSurname(e.target.value)}
              placeholder={t('settings.surnamePlaceholder')}
              onKeyDown={(e) => e.key === 'Enter' && handleSave()}
            />
          </div>
        </div>

        {/* Email — read only */}
        <div className="flex flex-col gap-1.5">
          <Label className="text-xs">{t('settings.email')}</Label>
          <Input value={profile?.email ?? ''} disabled className="bg-muted" />
        </div>

        <Button
          size="sm"
          className="w-fit"
          onClick={handleSave}
          disabled={updateProfileMutation.isPending}
        >
          {t('settings.updateProfile')}
        </Button>
      </div>

      <AvatarCropDialog
        imageSrc={rawImageSrc}
        onClose={() => setRawImageSrc(null)}
        onCropDone={handleCropDone}
      />
    </>
  );
}
