"use client";

import * as React from "react";
import { format, parse, isValid } from "date-fns";
import { Calendar as CalendarIcon } from "lucide-react";
import { cn } from "./utils";
import { Button } from "./button";
import { Calendar } from "./calendar";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "./popover";

export interface CustomDatePickerProps {
  /**
   * Selected date value as string in YYYY-MM-DD format (for form compatibility)
   * or Date object
   */
  value?: string | Date | null;
  
  /**
   * Callback when date changes. Returns date string in YYYY-MM-DD format
   */
  onChange?: (date: string | null) => void;
  
  /**
   * Minimum selectable date as string (YYYY-MM-DD) or Date object
   */
  minDate?: string | Date | null;
  
  /**
   * Maximum selectable date as string (YYYY-MM-DD) or Date object
   */
  maxDate?: string | Date | null;
  
  /**
   * Placeholder text
   */
  placeholderText?: string;
  
  /**
   * Whether the date picker is disabled
   */
  disabled?: boolean;
  
  /**
   * Additional CSS classes
   */
  className?: string;

  /**
   * CSS classes for the wrapper div
   */
  wrapperClassName?: string;

  /**
   * Error state - shows red border
   */
  error?: boolean;
  
  /**
   * Display format (default: "dd/MM/yyyy")
   */
  displayFormat?: string;
  
  /**
   * ID for accessibility
   */
  id?: string;
}

/**
 * Reusable DatePicker component with consistent dd/MM/yyyy format and button trigger.
 * Uses native Calendar component wrapped in a Popover.
 */
export function CustomDatePicker({
  value,
  onChange,
  minDate,
  maxDate,
  placeholderText = "dd/mm/yyyy",
  disabled = false,
  className,
  wrapperClassName,
  error = false,
  displayFormat = "dd/MM/yyyy",
  id,
}: CustomDatePickerProps) {
  const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);

  // Convert input value to Date object for Calendar
  const selectedDate = React.useMemo(() => {
    if (!value) return undefined;
    if (value instanceof Date) {
      return isValid(value) ? value : undefined;
    }
    if (typeof value === "string") {
      try {
        const parsed = parse(value, "yyyy-MM-dd", new Date());
        return isValid(parsed) ? parsed : undefined;
      } catch (e) {
        return undefined;
      }
    }
    return undefined;
  }, [value]);

  // Convert minDate
  const minDateObj = React.useMemo(() => {
    if (!minDate) return undefined;
    if (minDate instanceof Date) return isValid(minDate) ? minDate : undefined;
    if (typeof minDate === "string") {
      const parsed = parse(minDate, "yyyy-MM-dd", new Date());
      return isValid(parsed) ? parsed : undefined;
    }
    return undefined;
  }, [minDate]);

  // Convert maxDate
  const maxDateObj = React.useMemo(() => {
    if (!maxDate) return undefined;
    if (maxDate instanceof Date) return isValid(maxDate) ? maxDate : undefined;
    if (typeof maxDate === "string") {
      const parsed = parse(maxDate, "yyyy-MM-dd", new Date());
      return isValid(parsed) ? parsed : undefined;
    }
    return undefined;
  }, [maxDate]);

  const handleSelect = (date: Date | undefined) => {
    setIsPopoverOpen(false);
    if (!onChange) return;
    
    if (!date) {
      onChange(null);
      return;
    }
    
    // Return YYYY-MM-DD string
    onChange(format(date, "yyyy-MM-dd"));
  };

  return (
    <div className={cn("relative", wrapperClassName)}>
      <Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen}>
        <PopoverTrigger asChild>
          <Button
            id={id}
            disabled={disabled}
            variant="outline"
            className={cn(
              "w-full justify-start text-left font-normal",
              !selectedDate && "text-muted-foreground",
              error && "border-destructive ring-destructive/20",
              className
            )}
          >
            <CalendarIcon className="mr-2 h-4 w-4" />
            {selectedDate ? (
              format(selectedDate, displayFormat)
            ) : (
              <span>{placeholderText}</span>
            )}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0" align="start">
          <Calendar
            mode="single"
            selected={selectedDate}
            onSelect={handleSelect}
            disabled={(date) => {
              if (minDateObj && date < minDateObj) return true;
              if (maxDateObj && date > maxDateObj) return true;
              return false;
            }}
            initialFocus
          />
        </PopoverContent>
      </Popover>
    </div>
  );
}

export default CustomDatePicker;

