"use client";

import { CalendarDate } from "@internationalized/date";
import { cn } from "@xtablo/shared";
import { format } from "date-fns";
import { Calendar as CalendarIcon } from "lucide-react";
import * as React from "react";
import { Button } from "./button";
import { Calendar } from "./calendar";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";

interface DateFieldProps {
  name?: string;
  value?: CalendarDate | Date;
  defaultValue?: CalendarDate | Date;
  onChange?: (date: CalendarDate | undefined) => void;
  minValue?: CalendarDate | Date;
  maxValue?: CalendarDate | Date;
  disabled?: boolean;
  className?: string;
  children?: React.ReactNode;
}

export function DateField({
  name,
  value,
  defaultValue,
  onChange,
  minValue,
  maxValue,
  disabled,
  className,
  children,
}: DateFieldProps) {
  // Convert CalendarDate to Date for display
  const convertToDate = (val?: CalendarDate | Date): Date | undefined => {
    if (!val) return undefined;
    if (val instanceof Date) return val;
    return new Date(val.year, val.month - 1, val.day);
  };

  // Convert Date to CalendarDate for onChange
  const convertToCalendarDate = (date?: Date): CalendarDate | undefined => {
    if (!date) return undefined;
    return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate());
  };

  const [internalDate, setInternalDate] = React.useState<Date | undefined>(
    convertToDate(value || defaultValue)
  );

  const currentDate = value ? convertToDate(value) : internalDate;

  const handleSelect = (date: Date | undefined) => {
    setInternalDate(date);
    if (onChange) {
      onChange(convertToCalendarDate(date));
    }
  };

  const minDate = convertToDate(minValue);
  const maxDate = convertToDate(maxValue);

  // Extract label from children
  const label = React.Children.toArray(children).find(
    (child) => React.isValidElement(child) && child.type === DateFieldLabel
  );

  return (
    <div className={cn("flex flex-col gap-1.5", className)}>
      {label}
      <Popover>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            data-empty={!currentDate}
            disabled={disabled}
            className={cn(
              "data-[empty=true]:text-muted-foreground w-full justify-start text-left font-normal"
            )}
          >
            <CalendarIcon className="mr-2 h-4 w-4" />
            {currentDate ? format(currentDate, "PPP") : <span>Pick a date</span>}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0">
          <Calendar
            mode="single"
            selected={currentDate}
            onSelect={handleSelect}
            disabled={(date) => {
              if (minDate && date < minDate) return true;
              if (maxDate && date > maxDate) return true;
              return false;
            }}
            initialFocus
          />
        </PopoverContent>
      </Popover>
      {/* Hidden input for form submission */}
      {name && currentDate && (
        <input type="hidden" name={name} value={format(currentDate, "yyyy-MM-dd")} />
      )}
    </div>
  );
}

export function DateFieldLabel({
  children,
  "aria-required": ariaRequired,
}: {
  children: React.ReactNode;
  "aria-required"?: boolean;
}) {
  return (
    // biome-ignore lint/a11y/noLabelWithoutControl: This label is for display only within a custom date picker component
    <label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
      {children}
      {ariaRequired && <span className="text-destructive ml-1">*</span>}
    </label>
  );
}

export function DateInput() {
  // This is a placeholder since the calendar picker is the actual input
  return null;
}
