'use client';

import { useEffect, useId, useRef, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react';
import { isRtlLocale } from '@/i18n/routing';
import { formatAppPickerDateLabel } from '@/lib/i18n/format';
import { CalendarDayPartsPanel } from '@/components/ui/shared/CalendarDayPartsPanel';
import { addCalendarDays, compareLocalDayStart, startOfLocalDay } from '@/components/appointments/appointmentTime';
import { Checkbox } from '@/components/ui/shared/Checkbox';
import { useAnchoredPanelPosition } from '@/lib/hooks/useAnchoredPanelPosition';

export type CalendarDaySelectProps = {
  value: Date;
  onChange: (day: Date) => void;
  label?: string;
  emptyLabel?: string;
  isEmpty?: boolean;
  showHeader?: boolean;
  showTodayToggle?: boolean;
  showNavArrows?: boolean;
  disabled?: boolean;
  className?: string;
  triggerClassName?: string;
  id?: string;
  onBlur?: () => void;
  closePanelOnDaySelect?: boolean;
};

export function CalendarDaySelect({
  value,
  onChange,
  label,
  emptyLabel,
  isEmpty = false,
  showHeader = false,
  showTodayToggle = false,
  showNavArrows = false,
  disabled = false,
  className,
  triggerClassName,
  id,
  onBlur,
  closePanelOnDaySelect = true,
}: CalendarDaySelectProps) {
  const locale = useLocale();
  const rtl = isRtlLocale(locale);
  const t = useTranslations('schedule');
  const PrevIcon = rtl ? ChevronRight : ChevronLeft;
  const NextIcon = rtl ? ChevronLeft : ChevronRight;
  const panelId = useId();
  const rootRef = useRef<HTMLDivElement>(null);
  const [panelOpen, setPanelOpen] = useState(false);
  const { panelRef, style: panelStyle } = useAnchoredPanelPosition({
    open: panelOpen && !disabled,
    anchorRef: rootRef,
    align: 'stretch',
  });

  const normalizedValue = startOfLocalDay(value);
  const today = startOfLocalDay(new Date());
  const isTodaySelected = !isEmpty && compareLocalDayStart(normalizedValue, today) === 0;
  const resolvedLabel = label ?? t('defaultLabel');
  const showLabelRow = showHeader && Boolean(resolvedLabel);
  const todayToggle = showTodayToggle ? (
    <Checkbox
      checked={isTodaySelected}
      onChange={(checked) => {
        if (checked) {
          onChange(today);
          setPanelOpen(false);
        }
      }}
      label={t('today')}
      className="shrink-0"
    />
  ) : null;
  const labelText = isEmpty
    ? (emptyLabel ?? t('chooseDate'))
    : formatAppPickerDateLabel(normalizedValue, locale);

  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);
      onBlur?.();
    }

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

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

  const triggerButton = (
    <button
      type="button"
      id={id}
      disabled={disabled}
      onClick={() => {
        if (disabled) return;
        setPanelOpen((open) => !open);
      }}
      aria-expanded={panelOpen}
      aria-controls={panelId}
      aria-haspopup="dialog"
      className={
        triggerClassName ??
        `flex flex-1 min-w-0 items-center justify-center gap-3 rounded-[var(--radius-sm)] px-2 py-1.5 text-sm font-medium text-text-primary tabular-nums hover:bg-background-card/80 focus:outline-none focus:ring-2 focus:ring-primary/35 disabled:cursor-not-allowed disabled:opacity-60 ${
          isEmpty ? 'text-text-muted' : ''
        }`
      }
    >
      <span className="truncate">{labelText}</span>
      <ChevronDown
        className={`h-3.5 w-3.5 shrink-0 text-text-muted icon-flat transition-transform ${panelOpen ? 'rotate-180' : ''}`}
        aria-hidden
      />
    </button>
  );

  return (
    <div ref={rootRef} className={`relative w-full ${className ?? 'max-w-md'}`}>
      {showLabelRow ? (
        <div className="mb-2 flex items-center justify-between gap-3">
          <p className="text-sm font-medium text-text-secondary">{resolvedLabel}</p>
          {todayToggle}
        </div>
      ) : null}

      <div
        className={`flex items-center gap-1 rounded-[var(--radius-md)] border border-border bg-background-secondary/90 px-1 py-1 shadow-[inset_0_1px_0_rgba(255,255,255,0.02)] ${
          showNavArrows ? '' : 'py-0.5'
        }`}
      >
        {showNavArrows ? (
          <button
            type="button"
            disabled={disabled}
            onClick={() => onChange(addCalendarDays(normalizedValue, -1))}
            className="shrink-0 rounded-[var(--radius-sm)] p-2 text-text-muted hover:text-text-primary hover:bg-background-card/80 focus:outline-none focus:ring-2 focus:ring-primary/35 disabled:opacity-60"
            aria-label={t('previousDay')}
          >
            <PrevIcon className="h-4 w-4 icon-flat" />
          </button>
        ) : null}

        {triggerButton}

        {showNavArrows ? (
          <button
            type="button"
            disabled={disabled}
            onClick={() => onChange(addCalendarDays(normalizedValue, 1))}
            className="shrink-0 rounded-[var(--radius-sm)] p-2 text-text-muted hover:text-text-primary hover:bg-background-card/80 focus:outline-none focus:ring-2 focus:ring-primary/35 disabled:opacity-60"
            aria-label={t('nextDay')}
          >
            <NextIcon className="h-4 w-4 icon-flat" />
          </button>
        ) : null}
        {!showLabelRow && todayToggle ? <div className="pe-1">{todayToggle}</div> : null}
      </div>

      {panelOpen && !disabled ? (
        <div
          ref={panelRef}
          id={panelId}
          role="dialog"
          aria-label={t('chooseDate')}
          style={
            panelStyle ?? {
              position: 'fixed',
              top: 0,
              left: 0,
              visibility: 'hidden',
              pointerEvents: 'none',
            }
          }
          className="rounded-[var(--radius-md)] border border-border bg-background-secondary p-3 shadow-lg"
        >
          <CalendarDayPartsPanel
            panelId={panelId}
            value={normalizedValue}
            onChange={onChange}
            closePanelOnDaySelect={closePanelOnDaySelect}
            onAfterSelect={() => {
              setPanelOpen(false);
              onBlur?.();
            }}
          />
        </div>
      ) : null}
    </div>
  );
}
