"use client";

import { useState, useRef, useEffect } from "react";
import { CalendarIcon, ChevronRightIcon, ChevronLeftIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import jalaali from "jalaali-js";
import { cn } from "@/lib/utils";

const MONTHS = ["فروردین","اردیبهشت","خرداد","تیر","مرداد","شهریور","مهر","آبان","آذر","دی","بهمن","اسفند"];
const DAYS = ["ش","ی","د","س","چ","پ","ج"];

interface JalaliDatePickerProps {
  value?: Date | null;
  onChange: (date: Date | null) => void;
  placeholder?: string;
  className?: string;
}

function toJalali(d: Date) {
  return jalaali.toJalaali(d.getFullYear(), d.getMonth() + 1, d.getDate());
}

function toGregorian(jy: number, jm: number, jd: number) {
  const g = jalaali.toGregorian(jy, jm, jd);
  return new Date(g.gy, g.gm - 1, g.gd);
}

function daysInJalaliMonth(jy: number, jm: number) {
  return jalaali.jalaaliMonthLength(jy, jm);
}

function firstWeekdayOfJalaliMonth(jy: number, jm: number) {
  const g = jalaali.toGregorian(jy, jm, 1);
  // 0=Sun,1=Mon,...,6=Sat → convert to Sat=0
  const day = new Date(g.gy, g.gm - 1, g.gd).getDay();
  // Sat=0, Sun=1, Mon=2, Tue=3, Wed=4, Thu=5, Fri=6
  return (day + 1) % 7;
}

export function JalaliDatePicker({ value, onChange, placeholder = "انتخاب تاریخ", className }: JalaliDatePickerProps) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  const today = new Date();
  const todayJ = toJalali(today);

  const [viewYear, setViewYear] = useState(() => value ? toJalali(value).jy : todayJ.jy);
  const [viewMonth, setViewMonth] = useState(() => value ? toJalali(value).jm : todayJ.jm);



  const prevMonth = () => {
    if (viewMonth === 1) { setViewMonth(12); setViewYear(y => y - 1); }
    else setViewMonth(m => m - 1);
  };
  const nextMonth = () => {
    if (viewMonth === 12) { setViewMonth(1); setViewYear(y => y + 1); }
    else setViewMonth(m => m + 1);
  };

  const numDays = daysInJalaliMonth(viewYear, viewMonth);
  const firstDay = firstWeekdayOfJalaliMonth(viewYear, viewMonth);
  const cells = Array(firstDay).fill(null).concat(Array.from({ length: numDays }, (_, i) => i + 1));
  while (cells.length % 7 !== 0) cells.push(null);

  const selectedJ = value ? toJalali(value) : null;

  const formatDisplay = () => {
    if (!value) return "";
    const j = toJalali(value);
    return `${j.jy}/${String(j.jm).padStart(2,"0")}/${String(j.jd).padStart(2,"0")}`;
  };

  const isSelected = (d: number) =>
    selectedJ && selectedJ.jy === viewYear && selectedJ.jm === viewMonth && selectedJ.jd === d;

  const isToday = (d: number) =>
    todayJ.jy === viewYear && todayJ.jm === viewMonth && todayJ.jd === d;

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <button
          type="button"
          className={cn(
            "flex items-center gap-2 h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 hover:bg-accent/50 transition-colors",
            className
          )}
        >
          <CalendarIcon className="w-4 h-4 text-muted-foreground shrink-0" />
          <span className={cn("flex-1 text-right font-sans", !value && "text-muted-foreground")}>
            {value ? formatDisplay() : placeholder}
          </span>
          {value && (
            <button
              type="button"
              onClick={(e) => { e.stopPropagation(); e.preventDefault(); onChange(null); }}
              className="text-muted-foreground hover:text-foreground transition-colors text-xs px-1"
            >✕</button>
          )}
        </button>
      </PopoverTrigger>

      <PopoverContent className="w-72 p-4" align="start" dir="rtl">
        {/* Header */}
        <div className="flex items-center justify-between mb-4">
          <button type="button" onClick={nextMonth} className="p-1.5 rounded-lg hover:bg-muted transition-colors">
            <ChevronRightIcon className="w-4 h-4" />
          </button>
          <div className="flex items-center gap-2">
            <span className="font-bold text-sm">{MONTHS[viewMonth - 1]}</span>
            <select
              value={viewYear}
              onChange={e => setViewYear(Number(e.target.value))}
              className="font-sans font-bold text-sm bg-muted rounded-lg px-2 py-0.5 border-none outline-none cursor-pointer"
            >
              {Array.from({ length: todayJ.jy - 1330 + 1 }, (_, i) => todayJ.jy - i).map(y => (
                <option key={y} value={y}>{y}</option>
              ))}
            </select>
          </div>
          <button type="button" onClick={prevMonth} className="p-1.5 rounded-lg hover:bg-muted transition-colors">
            <ChevronLeftIcon className="w-4 h-4" />
          </button>
        </div>

        {/* Day headers */}
        <div className="grid grid-cols-7 mb-2">
          {DAYS.map(d => (
            <div key={d} className="text-center text-[10px] font-bold text-muted-foreground py-1">{d}</div>
          ))}
        </div>

        {/* Calendar grid */}
        <div className="grid grid-cols-7 gap-0.5">
          {cells.map((day, idx) => (
            <button
              key={idx}
              type="button"
              disabled={!day}
              onClick={() => {
                if (!day) return;
                onChange(toGregorian(viewYear, viewMonth, day));
                setOpen(false);
              }}
              className={cn(
                "h-8 w-8 mx-auto flex items-center justify-center rounded-lg text-xs font-sans font-medium transition-all",
                !day && "invisible",
                day && !isSelected(day) && !isToday(day) && "hover:bg-muted text-foreground",
                isToday(day) && !isSelected(day) && "border border-primary text-primary font-bold",
                isSelected(day) && "bg-primary text-primary-foreground font-bold shadow-sm",
              )}
            >
              {day}
            </button>
          ))}
        </div>

        {/* Today button */}
        <div className="mt-3 pt-3 border-t flex justify-center">
          <button
            type="button"
            onClick={() => {
              onChange(today);
              setViewYear(todayJ.jy);
              setViewMonth(todayJ.jm);
              setOpen(false);
            }}
            className="text-xs text-primary font-bold hover:underline"
          >
            امروز
          </button>
        </div>
      </PopoverContent>
    </Popover>
  );
}
