import * as React from "react";
import { format, parse, isValid } from "date-fns";
import { cn } from "@/lib/utils";
import { DatePicker, DatePickerProps } from "./date-picker";

interface DateInputWithFeedbackProps extends DatePickerProps {
  showFeedback?: boolean;
}

export function DateInputWithFeedback({ 
  showFeedback = true,
  onSelect,
  ...props 
}: DateInputWithFeedbackProps) {
  const [parseStatus, setParseStatus] = React.useState<{
    isValid: boolean;
    message: string;
    parsed?: Date;
  }>({ isValid: true, message: "" });

  const parseDate = (input: string): Date | null => {
    if (!input) return null;
    
    // Try ISO format: 2005-06-15
    let parsed = parse(input, "yyyy-MM-dd", new Date());
    if (isValid(parsed)) return parsed;
    
    // Try US format: 06/15/2005
    parsed = parse(input, "MM/dd/yyyy", new Date());
    if (isValid(parsed)) return parsed;
    
    // Try European format: 15/06/2005
    parsed = parse(input, "dd/MM/yyyy", new Date());
    if (isValid(parsed)) return parsed;
    
    // Try short format: 6/15/05
    parsed = parse(input, "M/d/yy", new Date());
    if (isValid(parsed)) return parsed;
    
    // Try short year format: 2005-6-15
    parsed = parse(input, "yyyy-M-d", new Date());
    if (isValid(parsed)) return parsed;
    
    return null;
  };

  const handleSelect = (date: Date | undefined) => {
    if (date) {
      setParseStatus({
        isValid: true,
        message: `✓ ${format(date, "PPP")}`,
        parsed: date
      });
    } else {
      setParseStatus({ isValid: true, message: "" });
    }
    onSelect?.(date);
  };

  return (
    <div className="space-y-1">
      <DatePicker
        allowTextEntry
        onSelect={handleSelect}
        {...props}
      />
      {showFeedback && parseStatus.message && (
        <p className={cn(
          "text-xs",
          parseStatus.isValid 
            ? "text-green-600 dark:text-green-400" 
            : "text-amber-600 dark:text-amber-400"
        )}>
          {parseStatus.message}
        </p>
      )}
    </div>
  );
}
