import React, { useRef, useState, useEffect, useContext } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setFromDate, setToDate, setMobileFilterType, setMobileDatePickerMode, setMinDate, setMaxDate, setDateFlexibility } from '../../store/qsm-slice';
import { QSMRootState } from '../../store/qsm-store';
import { addYears, format, startOfDay } from 'date-fns';
import DateRangePicker from '../date-range-picker';
import useMediaQuery from '../../../shared/utils/use-media-query-util';
import QSMConfigurationContext from '../../qsm-configuration-context';

const DatePicker: React.FC = () => {
  const dispatch = useDispatch();
  const isSmallScreen = useMediaQuery('(max-width: 768px)');

  /* 🔑  STATE FIRST (no TDZ issues) */
  const [isOpen, setIsOpen] = useState(false); // range pop-over
  const [isSingleOpen, setIsSingleOpen] = useState(false); // single pop-over

  const { datesIcon, showReturnDate = true, minDate, maxDate, dateFlexibility = [] } = useContext(QSMConfigurationContext);

  const isSingleDate = !showReturnDate;

  const dateInputWrapperRef = useRef<HTMLDivElement>(null);
  const dateInputRef = useRef<HTMLDivElement>(null);

  const today = startOfDay(new Date());
  const effectiveMinDate = minDate ?? today;
  const effectiveMaxDate = maxDate ?? addYears(today, 1);

  const { fromDate, toDate } = useSelector((state: QSMRootState) => ({
    fromDate: state.qsm.fromDate,
    toDate: state.qsm.toDate
  }));

  /* ----------------------- outside click close ----------------------- */
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dateInputWrapperRef.current &&
        !dateInputWrapperRef.current.contains(event.target as Node) &&
        dateInputRef.current &&
        !dateInputRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
        setIsSingleOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  /* ----------------------- min/max & flexibility sync ---------------- */
  useEffect(() => {
    dispatch(setMinDate(effectiveMinDate.toISOString()));
    dispatch(setMaxDate(effectiveMaxDate.toISOString()));
  }, [dispatch, effectiveMinDate, effectiveMaxDate]);

  useEffect(() => {
    if (dateFlexibility.length) {
      dispatch(setDateFlexibility(dateFlexibility));
    }
  }, [dispatch, JSON.stringify(dateFlexibility)]);

  /* =================== SINGLE DATE (only departure) ================= */
  if (isSingleDate) {
    return (
      <div className="qsm__double-input" ref={dateInputWrapperRef}>
        <div
          className="qsm__input-wrapper"
          onClick={() => {
            if (isSmallScreen) {
              dispatch(setMobileDatePickerMode('single'));
              dispatch(setMobileFilterType('date'));
            } else {
              setIsSingleOpen(true);
            }
          }}>
          {datesIcon && <span className="qsm__input-icon">{datesIcon}</span>}
          <label className="qsm__label">Vertrek</label>
          <input type="text" className="qsm__input u-ps-2" placeholder="Datum" readOnly value={fromDate ? format(new Date(fromDate), 'dd/MM/yyyy') : ''} />
        </div>

        {!isSmallScreen && isSingleOpen && (
          <div className="qsm__datepicker-popover" ref={dateInputRef}>
            <DateRangePicker
              fromDate={fromDate ? new Date(fromDate) : undefined}
              onSelectionChange={(from) => {
                dispatch(setFromDate(from ? from.toISOString() : undefined));
                dispatch(setToDate(undefined));
              }}
              onRequestClose={() => setIsSingleOpen(false)}
              isSingleDate
            />
          </div>
        )}
      </div>
    );
  }

  /* ======================== RANGE PICKER ============================= */
  const handleFromDateClick = () => {
    if (isSmallScreen) {
      dispatch(setMobileDatePickerMode('range'));
      dispatch(setMobileFilterType('date'));
    } else {
      setIsOpen(true);
    }
  };

  return (
    <div className="qsm__double-input" ref={dateInputWrapperRef}>
      {/* Departure */}
      <label className="qsm__input-wrapper" onClick={handleFromDateClick}>
        {datesIcon && <span className="qsm__input-icon">{datesIcon}</span>}
        <span className="qsm__label">Vertrek</span>
        <input
          type="text"
          id="vertrek"
          className="qsm__input u-ps-2"
          placeholder="Datum"
          readOnly
          value={fromDate ? format(new Date(fromDate), 'dd/MM/yyyy') : ''}
        />
        <div className="qsm__input-line qsm__input-line--datepicker" />
      </label>

      {/* Return */}
      <label className="qsm__input-wrapper" onClick={handleFromDateClick}>
        {datesIcon && <span className="qsm__input-icon">{datesIcon}</span>}
        <span className="qsm__label qsm__label--second-input-label">Retour</span>
        <input type="text" id="retour" className="qsm__input" placeholder="Datum" readOnly value={toDate ? format(new Date(toDate), 'dd/MM/yyyy') : ''} />
      </label>

      {/* Desktop pop-over */}
      {isOpen && !isSmallScreen && (
        <div className="qsm__datepicker-popover" ref={dateInputRef}>
          <DateRangePicker
            fromDate={fromDate ? new Date(fromDate) : undefined}
            toDate={toDate ? new Date(toDate) : undefined}
            onSelectionChange={(from, to) => {
              dispatch(setFromDate(from ? from.toISOString() : undefined));
              dispatch(setToDate(to ? to.toISOString() : undefined));
            }}
            onRequestClose={() => setIsOpen(false)}
          />
        </div>
      )}
    </div>
  );
};

export default DatePicker;
