"use client";

import { useState } from "react";
import DatePicker from "react-multi-date-picker";
import persian from "react-date-object/calendars/jalali";
import persian_fa from "react-date-object/locales/persian_fa";

import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { CalendarIcon } from "lucide-react";
import { cn } from "@/lib/utils";

type Props = {
  value: Date | null | undefined;
  onChange?: (date: Date | undefined) => void;
  placeholder?: string;
  className?: string;
};

export function PersianDatePicker({
  value,
  onChange,
  placeholder = "انتخاب تاریخ",
  className,
}: Props) {
  const [open, setOpen] = useState(false);

  const displayedValue = value
    ? new Date(value).toLocaleDateString("fa-IR")
    : placeholder;
 return (
    <Popover>
      <PopoverTrigger asChild>
        <Button
          type="button"
          onMouseDown={(e) => {
            e.preventDefault();
          }}
          variant="outline"
          className={cn(
            `w-full h-12 rounded-xl bg-white dark:bg-input 
            border border-input px-4 text-[15px]
            text-right justify-between hover:border-secondary
            focus:border-secondary focus:ring-2 focus:ring-secondary/20`,
            !value && "text-muted-foreground",
            className
          )}
        >
          <span className="flex-1 text-right">{displayedValue}</span>
          <CalendarIcon className="w-5 h-5 text-muted-foreground ml-2" />
        </Button>
      </PopoverTrigger>

      <PopoverContent className="p-2" align="end">
        <DatePicker
          calendar={persian}
          locale={persian_fa}
          value={value ? new Date(value) : null}
          onChange={(val) => {
            const g = val?.toDate?.();
            onChange?.(g);
          }}
          calendarPosition="bottom-center"
          style={{
            width: "100%",
            padding: 10,
            borderRadius: "12px",
          }}
        />
      </PopoverContent>
    </Popover>
  );
}
