'use client';

import { forwardRef } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { ChevronIcon, ClearSmallIcon } from './icons';

/**
 * Below this, one month at a time. Two months side by side need ~600px, which a
 * phone does not have — and stacking them into a column makes the second one
 * something you have to scroll a popup to reach.
 */
const TWO_MONTH_MIN_WIDTH = '(min-width: 768px)';

interface FsDateInputProps {
  label: string;
  placeholder: string;
  /** Extra class for the placeholder span only — never for a chosen date. */
  placeholderClassName?: string;
  value?: string;
  onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
  onClear?: () => void;
  clearLabel?: string;
}

const FsDateInput = forwardRef<HTMLDivElement, FsDateInputProps>(function FsDateInput(
  { label, placeholder, placeholderClassName, value, onClick, onClear, clearLabel },
  ref,
) {
  return (
    <div className="exact-dates fs-date-box" ref={ref} onClick={onClick}>
      <div className="fs-head">
        <span className="fs-label">{label}</span>
        {/*
          The cross takes the chevron's place rather than sitting beside it.
          Two 14px glyphs in the corner of a cell whose label is 10px in the
          sticky bar read as one smudge, and the chevron is the more expendable
          of the two: the whole box already opens the calendar, so it is
          decoration, while the cross is the only way to reach this action.
        */}
        {onClear ? (
          <button
            type="button"
            className="fs-date-clear"
            aria-label={clearLabel ?? `Clear ${label.toLowerCase()}`}
            // The box around this button opens the calendar. Both handlers are
            // needed: react-datepicker opens on mousedown-then-click through
            // the custom input, so stopping only the click still flashes the
            // calendar open as the field is cleared.
            onMouseDown={(e) => e.stopPropagation()}
            onClick={(e) => {
              e.stopPropagation();
              e.preventDefault();
              onClear();
            }}
          >
            <ClearSmallIcon />
          </button>
        ) : (
          <ChevronIcon />
        )}
      </div>
      <div className="fs-value fs-date-display">
        {value || (
          <span className={`fs-placeholder${placeholderClassName ? ` ${placeholderClassName}` : ''}`}>
            {placeholder}
          </span>
        )}
      </div>
    </div>
  );
});

interface FlightDateFieldV3Props {
  dd: string;
  label: string;
  placeholder: string;
  /**
   * Extra class for the placeholder only. Exists for the one-way return
   * field, whose prompt is a full sentence of sell copy rather than a field
   * name and needs to be sized as such — while the date that replaces it, and
   * every other field's placeholder, keep the shared typography.
   */
  placeholderClassName?: string;
  selected: Date | null;
  onChange: (date: Date | null) => void;
  minDate?: Date;
  startDate?: Date | null;
  endDate?: Date | null;
  selectsStart?: boolean;
  selectsEnd?: boolean;
  /** Controlled open, so the form can hand focus from one field to the next. */
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /**
   * Fires on every day click, including re-picking the day already selected —
   * which `onChange` skips. Closing and advancing therefore has to hang off
   * this, or re-clicking the current date leaves the calendar stuck open.
   */
  onSelect?: (date: Date | null) => void;
  /**
   * Renders a cross in the field's top-right corner. Absent means no cross at
   * all — a field whose value is not optional has nothing to offer here.
   */
  onClear?: () => void;
  /** Spoken label for that cross, when "Clear return" is not what it does. */
  clearLabel?: string;
}

/**
 * Flight date field: react-datepicker wearing the design's `fs-date-box`.
 *
 * `key` on the picker is deliberately the caller's business — a return field
 * whose minDate moves with the departure needs remounting for the calendar to
 * reopen on the right month.
 */
export default function FlightDateFieldV3({
  dd,
  label,
  placeholder,
  placeholderClassName,
  selected,
  onChange,
  minDate,
  startDate,
  endDate,
  selectsStart,
  selectsEnd,
  open,
  onOpenChange,
  onSelect,
  onClear,
  clearLabel,
}: FlightDateFieldV3Props) {
  // Defaults to one month: `false` is what both the server and the first client
  // render see, and one month is the layout that always fits.
  const showTwoMonths = useMediaQuery(TWO_MONTH_MIN_WIDTH);

  return (
    <div className="fs-field fs-date-field" data-dd={dd}>
      <DatePicker
        selected={selected}
        onChange={onChange}
        onSelect={onSelect}
        minDate={minDate}
        startDate={startDate ?? undefined}
        endDate={endDate ?? undefined}
        selectsStart={selectsStart}
        selectsEnd={selectsEnd}
        monthsShown={showTwoMonths ? 2 : 1}
        dateFormat="EEE, MMM d yyyy"
        popperPlacement="bottom-start"
        portalId="v3-datepicker-portal"
        popperClassName="v3-dp-popper"
        open={open}
        onInputClick={() => {
          // Toggles, so tapping the field again dismisses the calendar. The
          // picker's `open` is controlled here, so without this it can only be
          // closed by picking a date or tapping somewhere else entirely.
          onOpenChange(!open);
        }}
        onClickOutside={() => onOpenChange(false)}
        onCalendarClose={() => onOpenChange(false)}
        shouldCloseOnSelect
        showPopperArrow={false}
        /*
         * The placeholder has to be given to the picker, not just to the input.
         *
         * react-datepicker clones `customInput` and assigns
         * `placeholder = this.props.placeholderText` onto the clone — so the
         * value set on the element below was overwritten with `undefined` on
         * every render, and `<span className="fs-placeholder">` came out empty.
         * That is why an unset Depart or Return field showed a blank line
         * rather than its prompt.
         *
         * Passed in both places deliberately: this one is what survives the
         * clone, and the element keeps its own so the component is still
         * correct if it is ever rendered outside a DatePicker.
         */
        placeholderText={placeholder}
        customInput={
          <FsDateInput
            label={label}
            placeholder={placeholder}
            placeholderClassName={placeholderClassName}
            onClear={onClear}
            clearLabel={clearLabel}
          />
        }
      />
    </div>
  );
}
