'use client';
import { FunctionComponent, useState } from 'react';
import Box from '@mui/material/Box';
import Popover from '@mui/material/Popover';
import Stack from '@mui/material/Stack';
import AppIconButton from '../AppIconButton';
import JalaliDatePicker from '../JalaliDatePicker';

export interface JalaliDateIntentPickerProps {
  /** The selected date as a wire ISO (Gregorian) `YYYY-MM-DD` string, or `''` for no selection. */
  value: string;
  /** Fired with the wire ISO (Gregorian) date of the day the user picked. */
  onChange: (iso: string) => void;
  /** Inclusive ISO lower bound (typically `todayIso()`). */
  min?: string;
  /** Number of day-chips in the near strip (default 7). */
  chipDayCount?: number;
  /** Already-translated relative labels for the first two chips when they land on today/tomorrow. */
  todayLabel: string;
  tomorrowLabel: string;
  /** Already-translated accessible label for the "pick another date" calendar-icon entry. */
  pickOtherLabel: string;
}

/**
 * A horizontal near-date chip strip (`JalaliDatePicker` `chips` variant) plus a calendar-icon entry into
 * the full Jalali grid (a `Popover`) for dates beyond the strip — the shape both C1 search (date-intent,
 * never hard-filters) and C4 booking-request (a real required field) need. Presentational, caller-owned
 * copy, per the `components/common` convention.
 * @component JalaliDateIntentPicker
 */
const JalaliDateIntentPicker: FunctionComponent<JalaliDateIntentPickerProps> = ({
  value,
  onChange,
  min,
  chipDayCount = 7,
  todayLabel,
  tomorrowLabel,
  pickOtherLabel,
}) => {
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);

  return (
    <Stack direction="row" sx={{ gap: 1, alignItems: 'center' }}>
      <Box sx={{ flexGrow: 1, minWidth: 0 }}>
        <JalaliDatePicker
          variant="chips"
          chipDayCount={chipDayCount}
          value={value || null}
          onChange={onChange}
          min={min}
          todayLabel={todayLabel}
          tomorrowLabel={tomorrowLabel}
        />
      </Box>
      <AppIconButton
        icon="calendar"
        title={pickOtherLabel}
        onClick={(event) => setAnchorEl(event.currentTarget)}
      />
      <Popover
        open={Boolean(anchorEl)}
        anchorEl={anchorEl}
        onClose={() => setAnchorEl(null)}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
        transformOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Box sx={{ p: 2, width: 320 }}>
          <JalaliDatePicker
            value={value || null}
            min={min}
            onChange={(iso) => {
              onChange(iso);
              setAnchorEl(null);
            }}
          />
        </Box>
      </Popover>
    </Stack>
  );
};

export default JalaliDateIntentPicker;
