﻿import FormRendererUser from '@/components/common/form-renderer-user';
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 { handleApiError } from '@/lib/error-handler';
import { request } from '@/lib/fetcher';
import { SharedData } from '@/types';
import { COUNTRY_OPTIONS } from '@/utils/countries';
import { zodResolver } from '@hookform/resolvers/zod';
import { router, usePage } from '@inertiajs/react';
import { CaretRightIcon } from '@phosphor-icons/react';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { z } from 'zod';

const ProfileSchema = z.object({
  first_name: z.string().min(1, 'First name is required'),
  last_name: z.string().min(1, 'Last name is required'),
  phone: z.string().optional(),
  birth_date: z.string().optional(),
  country: z.string().optional(),
  city: z.string().optional(),
  zip_code: z.string().optional(),
  address: z.string().optional(),
  profile_photo: z.any().optional(),
});

type ProfileFormValues = z.infer<typeof ProfileSchema>;

export default function Profile() {
  const { t } = useTranslation();
  const { auth } = usePage<SharedData>().props;
  const user = auth.user;
  const profile = user.profile;
  const [loading, setLoading] = useState(false);

  const leftFields = [
    { name: 'profile_photo', label: t('Profile Picture'), type: 'file' },
    {
      name: 'first_name',
      label: t('First Name'),
      placeholder: t('Enter first name'),
      type: 'text',
    },
    {
      name: 'last_name',
      label: t('Last Name'),
      placeholder: t('Enter last name'),
      type: 'text',
    },
    {
      name: 'phone',
      label: t('Phone'),
      placeholder: t('Enter phone number'),
      type: 'tel',
    },
    {
      name: 'birth_date',
      label: t('Date of Birth'),
      placeholder: t('Select birth date'),
      type: 'date',
    },
  ];

  const rightFields = [
    {
      name: 'city',
      label: t('City'),
      placeholder: t('Enter city'),
      type: 'text',
    },
    {
      name: 'zip_code',
      label: t('Zip Code'),
      placeholder: t('Enter zip code'),
      type: 'text',
    },
    {
      name: 'address',
      label: t('Address'),
      placeholder: t('Enter address'),
      type: 'text',
    },
  ];

  const form = useForm<ProfileFormValues>({
    resolver: zodResolver(ProfileSchema),
    defaultValues: {
      first_name: user.first_name ?? '',
      last_name: user.last_name ?? '',
      phone: profile?.phone ?? '',
      birth_date: profile?.birth_date ?? '',
      country: profile?.country ?? '',
      city: profile?.city ?? '',
      zip_code: profile?.zip_code ?? '',
      address: profile?.address ?? '',
      profile_photo: profile?.profile_photo ?? undefined,
    },
  });

  const onSubmit = async (values: ProfileFormValues) => {
    setLoading(true);
    const formData = new FormData();

    Object.entries(values).forEach(([key, value]) => {
      if (value instanceof File) {
        formData.append(key, value);
      } else if (
        value !== undefined &&
        value !== null &&
        value !== '' &&
        key !== 'profile_photo'
      ) {
        formData.append(key, value as string);
      }
    });

    try {
      await request.post('/api/user/profile', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      toast.success(t('Profile updated successfully'));
      router.reload({ only: ['auth'] });
    } catch (error) {
      handleApiError(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)}>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-4">
            {leftFields.map((field) => (
              <FormRendererUser key={field.name} form={form} item={field} />
            ))}
          </div>
          <div className="space-y-4">
            <FormField
              control={form.control}
              name="country"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="px-4 font-lexend text-black/50 dark:text-white/50">
                    {t('Country')}
                  </FormLabel>
                  <Combobox
                    options={COUNTRY_OPTIONS}
                    value={field.value}
                    onChange={field.onChange}
                    placeholder={t('Select country')}
                    className="rounded-xl border border-black/5 bg-black/5 dark:border-white/5 dark:bg-secondary"
                    searchPlaceholder={t('Search country...')}
                    variant="default"
                  />
                </FormItem>
              )}
            />
            {rightFields.map((field) => (
              <FormRendererUser key={field.name} form={form} item={field} />
            ))}
          </div>
        </div>
        <Separator className="my-6 bg-black/5 dark:bg-white/5" />
        <div className="flex items-center justify-end">
          <Button type="submit" variant="primary" disabled={loading}>
            <span>{loading ? t('Saving...') : t('Save Changes')}</span>
            <CaretRightIcon weight="bold" />
          </Button>
        </div>
      </form>
    </Form>
  );
}
