import { useState } from 'react';
import { ActionIcon, Button, Popover, TextInput } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { DayPicker as EthiopicDayPicker } from '@daypicker/ethiopic';
import { DayPicker as GregorianDayPicker } from '@daypicker/react';
import { IconCalendarEvent } from '@tabler/icons-react';
import { EthDateTime } from 'ethiopian-calendar-date-converter';
import '@daypicker/react/dist/style.css';

const EC_MONTHS_AM = [
  'መስከረም', 'ጥቅምት', 'ኅዳር', 'ታህሳስ', 'ጥር', 'የካቲት',
  'መጋቢት', 'ሚያዝያ', 'ግንቦት', 'ሰኔ', 'ሐምሌ', 'ነሐሴ', 'ጳጉሜ',
];

function toAmharicDisplay(date: Date): string {
  try {
    const eth = EthDateTime.fromEuropeanDate(date);
    return `${EC_MONTHS_AM[eth.month - 1]} ${eth.date}/${eth.year}`;
  } catch {
    return date.toLocaleDateString('en-US');
  }
}

export function toEthiopicDateLabel(date: Date): string {
  try {
    const eth = EthDateTime.fromEuropeanDate(date);
    return `EC ${eth.year}-${String(eth.month).padStart(2, '0')}-${String(eth.date).padStart(2, '0')}`;
  } catch {
    return date.toLocaleDateString('en-US');
  }
}

export interface AmharicDatePickerProps {
  label?: string;
  value?: Date | null;
  onChange?: (date: Date | null) => void;
  required?: boolean;
  placeholder?: string;
}

export function AmharicDatePicker({
  label,
  value,
  onChange,
  required,
  placeholder,
}: AmharicDatePickerProps) {
  const [calendarType, setCalendarType] = useState<'EN' | 'AMH'>('AMH');
  const [opened, { close, toggle }] = useDisclosure(false);

  const displayValue = value
    ? calendarType === 'EN'
      ? value.toLocaleDateString('en-US', {
          year: 'numeric',
          month: 'long',
          day: 'numeric',
        })
      : toAmharicDisplay(value)
    : '';

  return (
    <Popover
      opened={opened}
      onChange={close}
      position="bottom"
      width="auto"
      trapFocus
      withArrow
    >
      <Popover.Target>
        <TextInput
          label={label}
          required={required}
          value={displayValue}
          readOnly
          placeholder={placeholder}
          onClick={toggle}
          leftSection={
            <Button
              variant="light"
              size="compact-xs"
              onClick={(e) => {
                e.stopPropagation();
                setCalendarType((prev) => (prev === 'EN' ? 'AMH' : 'EN'));
              }}
              aria-label="Switch calendar type"
            >
              {calendarType}
            </Button>
          }
          leftSectionWidth="calc(4.375rem * var(--mantine-scale))"
          rightSection={
            <ActionIcon size="md" variant="transparent" onClick={toggle}>
              <IconCalendarEvent size={20} />
            </ActionIcon>
          }
        />
      </Popover.Target>

      <Popover.Dropdown p="md">
        {calendarType === 'AMH' ? (
          <EthiopicDayPicker
            mode="single"
            selected={value ?? undefined}
            numerals="latn"
            onSelect={(date: Date | undefined) => {
              onChange?.(date ?? null);
              close();
            }}
          />
        ) : (
          <GregorianDayPicker
            mode="single"
            selected={value ?? undefined}
            onSelect={(date: Date | undefined) => {
              onChange?.(date ?? null);
              close();
            }}
          />
        )}
      </Popover.Dropdown>
    </Popover>
  );
}
