import { Loader, Select, SimpleGrid, TextInput } from '@mantine/core';
import type { FieldErrors, UseFormRegister, UseFormSetValue, UseFormWatch, UseFormTrigger } from 'react-hook-form';
import { z } from 'zod';
import type { TFunction } from 'i18next';
import { useTranslation } from 'react-i18next';
import { AmharicDatePicker } from '@ema-platform/ui';

// dob comes in as a plain yyyy-MM-dd string; skip on empty/malformed so
// dobRequired's own message takes precedence.
function isAtLeast18(dob: string): boolean {
  const birth = new Date(dob);
  if (Number.isNaN(birth.getTime())) return true;
  const today = new Date();
  const cutoff = new Date(today.getFullYear() - 18, today.getMonth(), today.getDate());
  return birth <= cutoff;
}

export const profileSchema = (t: TFunction) =>
  z.object({
    professionId: z.string().min(1, t('profileForm.validation.professionRequired')),
    firstName: z.string().min(3, t('profileForm.validation.firstNameMin')),
    middleName: z.string().min(3, t('profileForm.validation.middleNameMin')),
    lastName: z.string().min(3, t('profileForm.validation.lastNameMin')),
    gender: z.string().min(1, t('profileForm.validation.genderRequired')),
    dob: z
      .string()
      .min(1, t('profileForm.validation.dobRequired'))
      .refine((value) => isAtLeast18(value), {
        message: t('profileForm.validation.dobMinAge'),
      }),
    pob: z.string().optional(),
    maritalStatus: z.string().min(1, t('profileForm.validation.maritalStatusRequired')),
  });

export type ProfileValues = z.infer<ReturnType<typeof profileSchema>>;

export const GENDERS = ['MALE', 'FEMALE'] as const;
export const MARITAL_STATUSES = ['SINGLE', 'MARRIED', 'DIVORCED', 'WIDOWED'] as const;
export const ID_TYPES = ['NID', 'VITAL', 'PASSPORT', 'DRIVERS_LICENSE'] as const;

interface ProfileFormContentProps {
  register: UseFormRegister<ProfileValues>;
  errors: FieldErrors<ProfileValues>;
  setValue: UseFormSetValue<ProfileValues>;
  watch: UseFormWatch<ProfileValues>;
  trigger: UseFormTrigger<ProfileValues>;
  professionsLoading: boolean;
  professionOptions: Array<{ value: string; label: string }>;
}

export function ProfileFormContent({
  register,
  errors,
  setValue,
  watch,
  trigger,
  professionsLoading,
  professionOptions,
}: ProfileFormContentProps) {
  const { t } = useTranslation();

  return (
    <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md">
      <Select
        label={t('profileFields.professionId')}
        placeholder={professionsLoading ? t('common.loading') : t('common.select')}
        required
        data={professionOptions}
        error={errors.professionId?.message}
        value={watch('professionId')}
        onChange={(val) => setValue('professionId', val || '', { shouldValidate: true })}
        onBlur={() => trigger('professionId')}
        name="professionId"
        searchable
        disabled={professionsLoading}
        rightSection={professionsLoading ? <Loader size="xs" type="oval" /> : undefined}
      />
      <TextInput
        label={t('profileFields.firstName')}
        placeholder={t('profileForm.placeholders.firstName')}
        required
        {...register('firstName')}
        error={errors.firstName?.message}
      />
      <TextInput
        label={t('profileFields.middleName')}
        placeholder={t('profileForm.placeholders.middleName')}
        required
        {...register('middleName')}
        error={errors.middleName?.message}
      />
      <TextInput
        label={t('profileFields.lastName')}
        placeholder={t('profileForm.placeholders.lastName')}
        required
        {...register('lastName')}
        error={errors.lastName?.message}
      />
      <Select
        label={t('profileFields.gender')}
        placeholder={t('common.select')}
        required
        data={GENDERS.map((g) => ({ value: g, label: t(`profileForm.genders.${g}`) }))}
        error={errors.gender?.message}
        value={watch('gender')}
        onChange={(val) => setValue('gender', val || '', { shouldValidate: true })}
        onBlur={() => trigger('gender')}
        name="gender"
      />
      <AmharicDatePicker
        label={t('profileFields.dob')}
        required
        value={watch('dob')}
        onChange={(val) => setValue('dob', val, { shouldValidate: true })}
        onBlur={() => trigger('dob')}
        name="dob"
        error={errors.dob?.message}
      />
      <TextInput
        label={t('profileFields.pob')}
        placeholder={t('profileForm.placeholders.pob')}
        {...register('pob')}
        error={errors.pob?.message}
      />
      <Select
        label={t('profileFields.maritalStatus')}
        placeholder={t('common.select')}
        required
        data={MARITAL_STATUSES.map((m) => ({ value: m, label: t(`profileForm.maritalStatuses.${m}`) }))}
        error={errors.maritalStatus?.message}
        value={watch('maritalStatus')}
        onChange={(val) => setValue('maritalStatus', val || '', { shouldValidate: true })}
        onBlur={() => trigger('maritalStatus')}
        name="maritalStatus"
      />
    </SimpleGrid>
  );
}
