"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useI18n } from "@/lib/i18n";

function pad(n: number) {
  return String(n).padStart(2, "0");
}

function toISO(d: Date) {
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}

function parseISO(value?: string) {
  if (!value) return null;
  const [y, m, d] = value.split("-").map(Number);
  if (!y || !m || !d) return null;
  return new Date(y, m - 1, d);
}

function formatDisplay(value: string, lang: string) {
  const date = parseISO(value);
  if (!date) return "";
  return new Intl.DateTimeFormat(lang === "en" ? "en" : "ar", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  }).format(date);
}

function sameDay(a: Date, b: Date) {
  return a.getFullYear() === b.getFullYear()
    && a.getMonth() === b.getMonth()
    && a.getDate() === b.getDate();
}

function startOfDay(date: Date) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

interface DatePickerProps {
  value: string;
  onChange: (value: string) => void;
  error?: boolean;
  placeholder?: string;
  minDate?: string;
}

export default function DatePicker({
  value,
  onChange,
  error,
  placeholder = "-/-/-",
  minDate,
}: DatePickerProps) {
  const { t, lang } = useI18n();
  const rootRef = useRef<HTMLDivElement>(null);
  const selected = parseISO(value);
  const [open, setOpen] = useState(false);
  const [view, setView] = useState(() => {
    const base = selected ?? new Date();
    return { year: base.getFullYear(), month: base.getMonth() };
  });
  const locale = lang === "en" ? "en" : "ar";

  useEffect(() => {
    if (!open) return;
    const onDoc = (e: MouseEvent) => {
      if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const earliest = parseISO(minDate);
    const base = selected && !(earliest && startOfDay(selected) < startOfDay(earliest))
      ? selected
      : earliest ?? new Date();
    setView({ year: base.getFullYear(), month: base.getMonth() });
  }, [open, value, minDate]);

  const days = useMemo(() => {
    const first = new Date(view.year, view.month, 1);
    const startPad = first.getDay();
    const daysInMonth = new Date(view.year, view.month + 1, 0).getDate();
    const cells: { date: Date; inMonth: boolean }[] = [];
    for (let i = 0; i < startPad; i += 1) {
      cells.push({ date: new Date(view.year, view.month, -startPad + i + 1), inMonth: false });
    }
    for (let day = 1; day <= daysInMonth; day += 1) {
      cells.push({ date: new Date(view.year, view.month, day), inMonth: true });
    }
    while (cells.length % 7 !== 0) {
      cells.push({ date: new Date(view.year, view.month + 1, cells.length - startPad - daysInMonth + 1), inMonth: false });
    }
    return cells;
  }, [view]);

  const weekdays = useMemo(() => {
    const sunday = new Date(2024, 0, 7);
    return Array.from({ length: 7 }, (_, index) => {
      const day = new Date(sunday);
      day.setDate(sunday.getDate() + index);
      return new Intl.DateTimeFormat(locale, { weekday: "narrow" }).format(day);
    });
  }, [locale]);

  const monthLabel = new Intl.DateTimeFormat(locale, { month: "long" }).format(new Date(view.year, view.month, 1));
  const today = new Date();
  const earliest = parseISO(minDate);
  const blocked = (date: Date) => Boolean(earliest && startOfDay(date) < startOfDay(earliest));
  const todayAllowed = !blocked(today);

  const shiftMonth = (delta: number) => {
    setView((prev) => {
      const next = new Date(prev.year, prev.month + delta, 1);
      return { year: next.getFullYear(), month: next.getMonth() };
    });
  };

  return (
    <div ref={rootRef} className="relative">
      <button
        type="button"
        onClick={() => setOpen((current) => !current)}
        className={`flex h-12 w-full items-center gap-3 rounded-xl border-2 bg-[#FAFAF8] px-[18px] text-sm outline-none transition-colors ${
          error ? "border-red-300" : open ? "border-[#C9A84C]" : "border-[#E8E4D9]"
        } ${open ? "shadow-[0_0_0_3px_rgba(201,168,76,0.18)]" : ""}`}
      >
        <img src="/icons/reg-date.svg" alt="" width={16} height={15} className="h-[15px] w-4 shrink-0" />
        <span className={`flex-1 text-start ${value ? "font-semibold text-[#1A1A2E]" : "text-[#9A9488]"}`}>
          {value ? formatDisplay(value, lang) : placeholder}
        </span>
      </button>

      {open && (
        <div className="absolute start-0 z-50 mt-2 w-[320px] max-w-[calc(100vw-2rem)] overflow-hidden rounded-2xl border border-[#E8E4D9] bg-white shadow-[0_24px_48px_-20px_rgba(26,26,46,0.28)]">
          <div className="h-1 bg-gradient-to-r from-[#C9A84C] via-[#E8C94A] to-[#A07830]" />
          <div className="p-4">
            <div className="mb-4 flex items-center justify-between gap-2">
              <button
                type="button"
                onClick={() => shiftMonth(-1)}
                className="flex size-9 items-center justify-center rounded-xl border border-[#E8E4D9] bg-[#FAFAF8] text-[#1A1A2E] transition-colors hover:border-[#C9A84C] hover:bg-[#C9A84C]/10"
                aria-label={t("previousMonth")}
              >
                <ChevronLeft className="size-4 rtl:rotate-180" />
              </button>
              <div className="text-center">
                <p className="text-sm font-bold text-[#1A1A2E]">{monthLabel} {view.year}</p>
                <p className="mt-0.5 text-[11px] text-[#4A4A6A]">{t("selectDate")}</p>
              </div>
              <button
                type="button"
                onClick={() => shiftMonth(1)}
                className="flex size-9 items-center justify-center rounded-xl border border-[#E8E4D9] bg-[#FAFAF8] text-[#1A1A2E] transition-colors hover:border-[#C9A84C] hover:bg-[#C9A84C]/10"
                aria-label={t("nextMonth")}
              >
                <ChevronRight className="size-4 rtl:rotate-180" />
              </button>
            </div>

            <div className="mb-1 grid grid-cols-7">
              {weekdays.map((day, index) => (
                <div key={`${day}-${index}`} className="py-1 text-center text-[11px] font-bold text-[#A08A5A]">
                  {day}
                </div>
              ))}
            </div>

            <div className="grid grid-cols-7 gap-1">
              {days.map((cell) => {
                const isSelected = selected ? sameDay(cell.date, selected) : false;
                const isToday = sameDay(cell.date, today);
                const disabled = blocked(cell.date);
                return (
                  <button
                    key={toISO(cell.date)}
                    type="button"
                    disabled={disabled}
                    onClick={() => {
                      if (disabled) return;
                      onChange(toISO(cell.date));
                      setOpen(false);
                    }}
                    className={`relative flex aspect-square items-center justify-center rounded-full text-sm transition-all ${
                      disabled
                        ? "cursor-not-allowed text-[#D5D0C6]"
                        : isSelected
                          ? "bg-gradient-to-br from-[#C9A84C] via-[#E8C94A] to-[#A07830] font-bold text-[#1A1A2E] shadow-md shadow-[#C9A84C]/30"
                          : cell.inMonth
                            ? "font-medium text-[#1A1A2E] hover:bg-[#C9A84C]/12"
                            : "text-[#C8C2B4] hover:bg-[#FAFAF8]"
                    } ${isToday && !isSelected && !disabled ? "ring-1 ring-[#C9A84C]" : ""}`}
                  >
                    {cell.date.getDate()}
                  </button>
                );
              })}
            </div>

            <div className="mt-4 flex items-center justify-between border-t border-[#E8E4D9] pt-3">
              <button
                type="button"
                onClick={() => {
                  onChange("");
                  setOpen(false);
                }}
                className="text-xs font-medium text-[#4A4A6A] hover:text-[#1A1A2E]"
              >
                {t("clear")}
              </button>
              {todayAllowed ? (
              <button
                type="button"
                onClick={() => {
                  const now = new Date();
                  onChange(toISO(now));
                  setView({ year: now.getFullYear(), month: now.getMonth() });
                  setOpen(false);
                }}
                className="rounded-lg px-3 py-1.5 text-xs font-bold text-[#A07830] transition-colors hover:bg-[#C9A84C]/15"
              >
                {t("today")}
              </button>
              ) : <span />}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
