/**
 * Date Field Component
 *
 * Renders a text input with variable picker support and a calendar dropdown
 * for selecting dates. Format: YYYY-MM-DD.
 *
 * Uses a plain positioned div instead of Radix Popover to avoid
 * pointer-event conflicts between Radix's dismiss layer and
 * react-day-picker's click handling in portaled content.
 */

import { memo, useState, useRef, useEffect } from 'react';
import { CalendarIcon } from 'lucide-react';
import { format, parse, isValid } from 'date-fns';
import { Label } from '../ui/label';
import { Button } from '../ui/button';
import { Calendar } from '../ui/calendar';
import { VariableInput } from '../VariableInput';
import { ActionField } from '../../types/action';
import { AvailableContext } from '../../hooks/useAvailableContext';

interface DateFieldProps {
  fieldName: string;
  field: ActionField;
  value: string;
  onChange: (value: string) => void;
  availableContext: AvailableContext;
  error?: string;
}

export const DateField = memo(function DateField({
  fieldName,
  field,
  value,
  onChange,
  availableContext,
  error,
}: DateFieldProps) {
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  // Disable calendar when value contains a variable placeholder
  const hasVariable = value.includes('{{');

  // Parse current value to highlight in calendar
  const parsedDate = value ? parse(value, 'yyyy-MM-dd', new Date()) : undefined;
  const selectedDate = parsedDate && isValid(parsedDate) ? parsedDate : undefined;

  // Close on outside click
  useEffect(() => {
    if (!open) return;
    function handlePointerDown(e: PointerEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener('pointerdown', handlePointerDown);
    return () => document.removeEventListener('pointerdown', handlePointerDown);
  }, [open]);

  // Close on Escape
  useEffect(() => {
    if (!open) return;
    function handleKeyDown(e: KeyboardEvent) {
      if (e.key === 'Escape') setOpen(false);
    }
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [open]);

  return (
    <div className="space-y-2">
      <Label htmlFor={fieldName} className="text-slate-900">
        {field.label}
        {field.required && <span className="text-red-600 ml-1">*</span>}
      </Label>

      <div className="flex gap-2">
        <div className="flex-1">
          <VariableInput
            value={value}
            onChange={onChange}
            availableContext={availableContext}
            placeholder={field.placeholder || 'YYYY-MM-DD'}
          />
        </div>

        <div ref={containerRef} className="relative">
          <Button
            variant="outline"
            size="icon"
            disabled={hasVariable}
            aria-label="Pick date"
            type="button"
            aria-expanded={open}
            onClick={() => setOpen((prev) => !prev)}
          >
            <CalendarIcon className="h-4 w-4" />
          </Button>

          {open && (
            <div
              className="absolute right-0 top-full mt-1 z-50 rounded-md border bg-popover p-0 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95"
              role="dialog"
            >
              <Calendar
                mode="single"
                selected={selectedDate}
                onSelect={(date) => {
                  if (date) {
                    onChange(format(date, 'yyyy-MM-dd'));
                  }
                  setOpen(false);
                }}
                defaultMonth={selectedDate}
              />
            </div>
          )}
        </div>
      </div>

      {field.description && <p className="text-xs text-slate-500">{field.description}</p>}
      {error && <p className="text-xs text-red-600">{error}</p>}
    </div>
  );
});
