import { useMemo, useState } from 'react';
import {
  DatePicker,
  PickersDay,
  type PickersDayProps,
} from '@mui/x-date-pickers';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { AdapterDateFnsJalali } from '@mui/x-date-pickers/AdapterDateFnsJalali';
import { enUS } from 'date-fns/locale';
import { faIR as faIRJalali } from 'date-fns-jalali/locale';
import { getDay } from 'date-fns-jalali';
import { format as formatJalali } from 'date-fns-jalali';
import { format } from 'date-fns';
import { useTranslation } from 'react-i18next';
import { type DateOfBirthProps } from '../../types/settingForm';
import { Icon } from '@rkheftan/harmony-ui';
import { Calendar } from 'iconsax-react';

export default function DateOfBirth({ value, onChange }: DateOfBirthProps) {
  const { t, i18n } = useTranslation('completionForm');
  const isFarsi = i18n.language === 'fa' || i18n.language === 'fa-IR';
  const [openView, setOpenView] = useState<'year' | 'month' | 'day'>('year');

  const { Adapter, locale, formatString, dayOfWeekFormatter } = useMemo(() => {
    if (isFarsi) {
      const persianDays = ['ی', 'د', 'س', 'چ', 'پ', 'ج', 'ش'];
      return {
        Adapter: AdapterDateFnsJalali,
        locale: faIRJalali,
        formatString: 'yyyy/MM/dd',
        dayOfWeekFormatter: (date: Date) => persianDays[getDay(date)],
      };
    }
    return {
      Adapter: AdapterDateFns,
      locale: enUS,
      formatString: 'MM/dd/yyyy',
      dayOfWeekFormatter: undefined,
    };
  }, [isFarsi]);

  const CustomDay = (props: PickersDayProps) => {
    const dayNumber = isFarsi
      ? formatJalali(props.day, 'dd')
      : format(props.day, 'dd');
    return <PickersDay {...props}>{dayNumber}</PickersDay>;
  };

  const CustomCalendarIcon = () => (
    <Icon Component={Calendar} color="primary.main" variant="Bold" />
  );

  return (
    <LocalizationProvider dateAdapter={Adapter} adapterLocale={locale}>
      <DatePicker
        label={t('completion.dateOfBirth')}
        value={value}
        onChange={onChange}
        format={formatString}
        dayOfWeekFormatter={dayOfWeekFormatter}
        slots={{ day: CustomDay, openPickerIcon: CustomCalendarIcon }}
        disableFuture
        openTo="year"
        views={['year', 'month', 'day']}
        view={openView}
        onViewChange={(newView) => setOpenView(newView)}
        onYearChange={() => setOpenView('month')}
        slotProps={{
          textField: { fullWidth: true },
          popper: {
            sx: {
              '& .MuiDateCalendar-root': { width: '309px' },
            },
          },
        }}
      />
    </LocalizationProvider>
  );
}
