import { useEffect, useMemo, useState } from "react";
import { format, isValid, parseISO } from "date-fns";
import { enUS, tr } from "date-fns/locale";
import { CalendarDays } from "lucide-react";
import { DayPicker, type Matcher } from "react-day-picker";
import "react-day-picker/dist/style.css";
import { cn } from "../utils/helpers";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";

type PopoverAlign = "start" | "center" | "end";

interface DatePickerInputProps {
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  className?: string;
  disabled?: boolean;
  fromDate?: Date;
  toDate?: Date;
  align?: PopoverAlign;
}

const DEFAULT_START_MONTH = new Date(1950, 0, 1);
const DEFAULT_END_MONTH = new Date(new Date().getFullYear() + 10, 11, 31);

export function DatePickerInput({
  value,
  onChange,
  placeholder = "Select date",
  className,
  disabled = false,
  fromDate,
  toDate,
  align = "start",
}: DatePickerInputProps) {
  const [open, setOpen] = useState(false);
  const selectedDate = useMemo(() => {
    if (!value) return undefined;
    const parsed = parseISO(value);
    return isValid(parsed) ? parsed : undefined;
  }, [value]);
  const [visibleMonth, setVisibleMonth] = useState<Date>(selectedDate ?? toDate ?? new Date());

  useEffect(() => {
    if (selectedDate) {
      setVisibleMonth(selectedDate);
    }
  }, [selectedDate]);

  const calendarLocale =
    typeof navigator !== "undefined" && navigator.language.toLowerCase().startsWith("tr")
      ? tr
      : enUS;

  const disabledDays = useMemo<Matcher | Matcher[] | undefined>(() => {
    const matchers: Matcher[] = [];
    if (fromDate) matchers.push({ before: fromDate });
    if (toDate) matchers.push({ after: toDate });
    return matchers.length > 0 ? matchers : undefined;
  }, [fromDate, toDate]);

  const displayValue = selectedDate ? format(selectedDate, "dd.MM.yyyy") : placeholder;

  const handleSelect = (date?: Date) => {
    if (!date) return;
    onChange(format(date, "yyyy-MM-dd"));
    setVisibleMonth(date);
    setOpen(false);
  };

  const handleToday = () => {
    const today = new Date();
    onChange(format(today, "yyyy-MM-dd"));
    setVisibleMonth(today);
    setOpen(false);
  };

  const handleClear = () => {
    onChange("");
    setOpen(false);
  };

  return (
    <Popover
      open={open}
      onOpenChange={(nextOpen) => {
        setOpen(nextOpen);
        if (nextOpen) {
          setVisibleMonth(selectedDate ?? toDate ?? new Date());
        }
      }}
    >
      <PopoverTrigger asChild>
        <button
          type="button"
          disabled={disabled}
          className={cn(
            "flex w-full items-center gap-2.5 rounded-xl border border-gray-200 bg-white px-3 py-2.5 text-left text-sm text-slate-700 transition-all",
            "shadow-sm hover:border-slate-300 hover:bg-slate-50",
            "disabled:cursor-not-allowed disabled:opacity-60",
            !selectedDate && "text-slate-400",
            className,
          )}
        >
          <CalendarDays className="h-4 w-4 shrink-0 text-slate-400" />
          <span className="min-w-0 flex-1 truncate">{displayValue}</span>
        </button>
      </PopoverTrigger>
      <PopoverContent align={align} className="z-[140] w-[320px] p-3">
        <DayPicker
          mode="single"
          selected={selectedDate}
          onSelect={handleSelect}
          month={visibleMonth}
          onMonthChange={setVisibleMonth}
          locale={calendarLocale}
          disabled={disabledDays}
          showOutsideDays
          captionLayout="dropdown"
          startMonth={fromDate ?? DEFAULT_START_MONTH}
          endMonth={toDate ?? DEFAULT_END_MONTH}
          navLayout="around"
          className="hp-day-picker hp-input-calendar"
        />
        <div className="mt-3 flex items-center justify-between border-t border-slate-100 pt-3">
          <button
            type="button"
            onClick={handleToday}
            className="rounded-full px-3 py-1.5 text-xs font-semibold text-blue-700 transition hover:bg-blue-50"
          >
            Today
          </button>
          <button
            type="button"
            onClick={handleClear}
            className="rounded-full px-3 py-1.5 text-xs font-semibold text-slate-500 transition hover:bg-slate-100 hover:text-slate-700"
          >
            Clear
          </button>
        </div>
      </PopoverContent>
    </Popover>
  );
}
