'use client';

import { useEffect, useId, useRef, useState } from 'react';
import { useLocale } from 'next-intl';
import { CalendarDays } from 'lucide-react';
import { parseDateInput, startOfLocalDay, toDateInputValue } from '@/components/appointments/appointmentTime';
import { FORM_DATE_INPUT_CLASS } from '@/components/shared/formSelectStyles';
import { CalendarDayPartsPanel } from '@/components/ui/shared/CalendarDayPartsPanel';
import { useAnchoredPanelPosition } from '@/lib/hooks/useAnchoredPanelPosition';
import {
  formatIsoAsGregorianDateInput,
  maskGregorianDateTyping,
  parseGregorianDateInputText,
} from '@/lib/i18n/dateInputFormat';
import { usesPersianCalendar } from '@/lib/i18n/format';
import {
  formatIsoAsPersianDateInput,
  maskJalaliDateTyping,
  parsePersianDateInputText,
} from '@/lib/i18n/persianCalendar';

export type AppDateInputProps = {
  id?: string;
  value: string;
  onChange: (value: string) => void;
  onBlur?: (value: string) => void;
  disabled?: boolean;
  className?: string;
};

/**
 * Locale-aware date field — wire value is always `YYYY-MM-DD` or empty.
 * Visual shell matches native `.form-select` (padding, text alignment, icon inset).
 */
export function AppDateInput({
  id,
  value,
  onChange,
  onBlur,
  disabled = false,
  className = '',
}: AppDateInputProps) {
  const locale = useLocale();
  const persian = usesPersianCalendar(locale);
  const panelId = useId();
  const rootRef = useRef<HTMLDivElement>(null);
  const [text, setText] = useState('');
  const [panelOpen, setPanelOpen] = useState(false);
  const { panelRef, style: panelStyle } = useAnchoredPanelPosition({
    open: panelOpen && !disabled,
    anchorRef: rootRef,
    align: 'start',
  });

  useEffect(() => {
    setText(
      persian ? formatIsoAsPersianDateInput(value) : formatIsoAsGregorianDateInput(value),
    );
  }, [persian, value]);

  useEffect(() => {
    if (!panelOpen) return;

    function onPointerDown(event: MouseEvent) {
      const target = event.target as Node;
      if (rootRef.current?.contains(target) || panelRef.current?.contains(target)) {
        return;
      }
      setPanelOpen(false);
    }

    function onKeyDown(event: KeyboardEvent) {
      if (event.key === 'Escape') {
        setPanelOpen(false);
      }
    }

    document.addEventListener('mousedown', onPointerDown);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('mousedown', onPointerDown);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [panelOpen, panelRef]);

  const panelAnchorDate = value ? parseDateInput(value) : startOfLocalDay(new Date());
  const placeholder = persian ? '۱۴۰۴/۰۴/۲۲' : '2026-07-13';
  const fieldClass = `${FORM_DATE_INPUT_CLASS} w-full ${className}`.trim();

  function formatDisplay(iso: string): string {
    return persian ? formatIsoAsPersianDateInput(iso) : formatIsoAsGregorianDateInput(iso);
  }

  function maskTyping(raw: string): string {
    return persian ? maskJalaliDateTyping(raw) : maskGregorianDateTyping(raw);
  }

  function parseTyping(raw: string): string | null {
    return persian ? parsePersianDateInputText(raw) : parseGregorianDateInputText(raw);
  }

  function commitText(nextText: string): string {
    const trimmed = nextText.trim();
    if (!trimmed) {
      onChange('');
      setText('');
      return '';
    }
    const iso = parseTyping(trimmed);
    if (iso) {
      onChange(iso);
      setText(formatDisplay(iso));
      return iso;
    }
    setText(value ? formatDisplay(value) : '');
    return value;
  }

  function handlePanelChange(day: Date) {
    const iso = toDateInputValue(day);
    onChange(iso);
    setText(formatDisplay(iso));
  }

  return (
    <div ref={rootRef} className="relative w-full">
      <input
        id={id}
        type="text"
        inputMode="numeric"
        autoComplete="off"
        value={text}
        disabled={disabled}
        placeholder={placeholder}
        onChange={(e) => setText(maskTyping(e.target.value))}
        onBlur={() => {
          const committed = commitText(text);
          onBlur?.(committed);
        }}
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            const committed = commitText(text);
            onBlur?.(committed);
            (e.target as HTMLInputElement).blur();
          }
        }}
        className={fieldClass}
      />
      <button
        type="button"
        disabled={disabled}
        aria-expanded={panelOpen}
        aria-controls={`${panelId}-parts`}
        aria-label={panelOpen ? undefined : 'Open calendar'}
        onClick={() => {
          if (!disabled) setPanelOpen((open) => !open);
        }}
        className="pointer-events-auto absolute top-1/2 end-3 flex h-4 w-4 -translate-y-1/2 items-center justify-center text-text-muted hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/35 disabled:opacity-60"
      >
        <CalendarDays className="h-4 w-4 icon-flat" aria-hidden />
      </button>

      {panelOpen && !disabled ? (
        <div
          ref={panelRef}
          id={`${panelId}-parts`}
          role="dialog"
          style={
            panelStyle ?? {
              position: 'fixed',
              top: 0,
              left: 0,
              visibility: 'hidden',
              pointerEvents: 'none',
            }
          }
          className="min-w-[17.5rem] rounded-[var(--radius-md)] border border-border bg-background-secondary p-3 shadow-lg"
        >
          <CalendarDayPartsPanel
            panelId={panelId}
            value={panelAnchorDate}
            onChange={handlePanelChange}
            closePanelOnDaySelect
            onAfterSelect={(day) => {
              setPanelOpen(false);
              onBlur?.(toDateInputValue(day));
            }}
          />
        </div>
      ) : null}
    </div>
  );
}
