import FormRenderer from '@/components/common/form-renderer';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
import { Form, FormField, FormItem, FormLabel } from '@/components/ui/form';
import { Separator } from '@/components/ui/separator';
import {
  getProfileLeftFields,
  getProfileRightFields,
} from '@/data/forms/profile-fields';
import { useInitials } from '@/hooks/use-initials';
import { handleApiError } from '@/lib/error-handler';
import { request } from '@/lib/fetcher';
import type { User } from '@/types';
import { COUNTRY_OPTIONS } from '@/utils/countries';
import { getImageUrl } from '@/utils/getImageUrl';
import { CameraIcon, CheckIcon, XIcon } from '@phosphor-icons/react';
import { useRef, useState, useTransition } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

function SectionHeading({ title }: { title: string }) {
  return (
    <>
      <h4 className="mb-1 text-xs font-semibold tracking-widest text-black/30 uppercase">
        {title}
      </h4>
      <Separator className="mb-4" />
    </>
  );
}

type ProfileFormData = {
  first_name: string;
  last_name: string;
  phone: string;
  birth_date: string;
  country: string;
  city: string;
  zip_code: string;
  address: string;
};

export default function ProfileEditForm({
  user,
  mutate,
  onSaved,
  onCancel,
}: {
  user: User;
  mutate: () => void;
  onSaved: () => void;
  onCancel: () => void;
}) {
  const { t } = useTranslation();
  const [isPending, startTransition] = useTransition();
  const [photoFile, setPhotoFile] = useState<File | null>(null);
  const [photoPreview, setPhotoPreview] = useState<string>(
    getImageUrl(user.profile?.profile_photo),
  );
  const fileInputRef = useRef<HTMLInputElement>(null);
  const getInitials = useInitials();

  const form = useForm<ProfileFormData>({
    defaultValues: {
      first_name: user.first_name ?? '',
      last_name: user.last_name ?? '',
      phone: user.profile?.phone ?? '',
      birth_date: user.profile?.birth_date ?? '',
      country: user.profile?.country ?? '',
      city: user.profile?.city ?? '',
      zip_code: user.profile?.zip_code ?? '',
      address: user.profile?.address ?? '',
    },
  });

  const handlePhotoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setPhotoFile(file);
    setPhotoPreview(URL.createObjectURL(file));
  };

  const onSubmit = (values: ProfileFormData) => {
    startTransition(async () => {
      try {
        const fd = new FormData();
        fd.append('first_name', values.first_name);
        fd.append('last_name', values.last_name);
        fd.append('phone', values.phone ?? '');
        fd.append('birth_date', values.birth_date ?? '');
        fd.append('country', values.country ?? '');
        fd.append('city', values.city ?? '');
        fd.append('zip_code', values.zip_code ?? '');
        fd.append('address', values.address ?? '');
        if (photoFile) fd.append('profile_photo', photoFile);

        await request.post('/api/admin/profile', fd, {
          headers: { 'Content-Type': 'multipart/form-data' },
        });
        toast.success(t('Profile updated successfully'));
        mutate();
        onSaved();
      } catch (error) {
        handleApiError(error);
      }
    });
  };

  const LEFT_FIELDS = getProfileLeftFields(t);
  const RIGHT_FIELDS = getProfileRightFields(t);

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        <div className="flex flex-wrap items-center gap-4 rounded-xl bg-white p-6 shadow-box">
          <div className="relative">
            <Avatar className="size-16 rounded-full">
              <AvatarImage src={photoPreview} alt={user.name} />
              <AvatarFallback className="text-lg">
                {getInitials(user.name ?? '')}
              </AvatarFallback>
            </Avatar>
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              className="absolute -right-1 -bottom-1 flex size-6 items-center justify-center rounded-full bg-primary text-white shadow"
            >
              <CameraIcon weight="bold" className="size-3" />
            </button>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handlePhotoChange}
            />
          </div>
          <div className="flex-1">
            <p className="font-medium">{user.name}</p>
            <p className="text-sm text-black/50">{user.email}</p>
            <p className="mt-0.5 text-xs text-black/40">
              {t('Click the camera icon to change photo')}
            </p>
          </div>
          <div className="flex gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={onCancel}
              disabled={isPending}
            >
              <XIcon weight="bold" className="size-4" />
              {t('Cancel')}
            </Button>
            <Button type="submit" loading={isPending} disabled={isPending}>
              <CheckIcon weight="bold" className="size-4" />
              {t('Save Changes')}
            </Button>
          </div>
        </div>

        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
          <div className="space-y-4 rounded-xl bg-white p-6 shadow-box">
            <SectionHeading title={t('Personal Information')} />
            {LEFT_FIELDS.map((item) => (
              <FormRenderer key={item.id} form={form} item={item} />
            ))}
          </div>

          <div className="space-y-4 rounded-xl bg-white p-6 shadow-box">
            <SectionHeading title={t('Location')} />
            <FormField
              control={form.control}
              name="country"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('Country')}</FormLabel>
                  <Combobox
                    options={COUNTRY_OPTIONS}
                    value={field.value}
                    onChange={field.onChange}
                    placeholder={t('Select country')}
                    searchPlaceholder={t('Search country...')}
                  />
                </FormItem>
              )}
            />
            {RIGHT_FIELDS.map((item) => (
              <FormRenderer key={item.id} form={form} item={item} />
            ))}
          </div>
        </div>
      </form>
    </Form>
  );
}
