'use client';
import { FunctionComponent, MouseEvent, useState } from 'react';
import { useLocale } from 'next-intl';
import Popover from '@mui/material/Popover';
import TextField, { TextFieldProps } from '@mui/material/TextField';
import Box from '@mui/material/Box';
import { formatShamsiDate } from '@/utils';
import AppIcon from '../AppIcon';
import JalaliDatePicker from '../JalaliDatePicker';

export interface JalaliDateFieldProps
  extends Omit<TextFieldProps, 'value' | 'onChange' | 'select' | 'type' | 'InputProps'> {
  /** The selected date as a wire ISO (Gregorian) `YYYY-MM-DD` string, or `null` for no selection. */
  value: string | null;
  /** Fired with the wire ISO (Gregorian) date of the day the user picked. */
  onChange: (iso: string) => void;
  min?: string;
  max?: string;
  /** Already-translated accessible labels forwarded to the picker's month-navigation buttons. */
  prevMonthLabel?: string;
  nextMonthLabel?: string;
}

/**
 * A read-only text field that opens `JalaliDatePicker` (grid variant) in a popover — the replacement for
 * every native `<input type="date">` in the app (which only ever rendered the Gregorian calendar). Display
 * is Shamsi on `fa` / Gregorian on `en` via the same `utils/date.ts` formatter used everywhere else in the
 * app; the emitted value is always ISO Gregorian.
 * @component JalaliDateField
 */
const JalaliDateField: FunctionComponent<JalaliDateFieldProps> = ({
  value,
  onChange,
  min,
  max,
  prevMonthLabel,
  nextMonthLabel,
  ...textFieldProps
}) => {
  const locale = useLocale();
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  // MUI Popover's anchor/transform origins are physical (left/right), not logical — resolve the reading
  // "start" edge from the locale ourselves so the popover opens on the correct side under RTL.
  const startEdge = locale === 'fa' ? 'right' : 'left';

  const open = (event: MouseEvent<HTMLDivElement>) => setAnchorEl(event.currentTarget);
  const close = () => setAnchorEl(null);

  const displayValue = value ? formatShamsiDate(value, locale) : '';

  return (
    <>
      <TextField
        {...textFieldProps}
        value={displayValue}
        onClick={open}
        slotProps={{
          input: {
            readOnly: true,
            endAdornment: <AppIcon icon="calendar" size={20} color="var(--bal-text-secondary)" />,
            sx: { cursor: 'pointer' },
          },
          htmlInput: { readOnly: true, style: { cursor: 'pointer' } },
        }}
      />
      <Popover
        open={Boolean(anchorEl)}
        anchorEl={anchorEl}
        onClose={close}
        anchorOrigin={{ vertical: 'bottom', horizontal: startEdge }}
        transformOrigin={{ vertical: 'top', horizontal: startEdge }}
      >
        <Box sx={{ p: 2, width: 320 }}>
          <JalaliDatePicker
            value={value}
            min={min}
            max={max}
            prevMonthLabel={prevMonthLabel}
            nextMonthLabel={nextMonthLabel}
            onChange={(iso) => {
              onChange(iso);
              close();
            }}
          />
        </Box>
      </Popover>
    </>
  );
};

export default JalaliDateField;
