import { useMemo, useState, type KeyboardEventHandler } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { ChevronDown } from "lucide-react";
import {
  generateNaturalLanguagePreview,
  parseNaturalLanguagePeriod,
  type NaturalLanguagePeriodResult,
} from "@/utils/naturalLanguagePeriod";

export type QuickPreset =
  | "last30days"
  | "thisMonth"
  | "lastMonth"
  | "thisQuarter"
  | "lastQuarter"
  | "thisYear";


interface PeriodSelectionPopoverProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  selectedLabel: string;
  referenceDate: Date;
  isLast30DaysActive: boolean;
  onQuickSelect: (preset: QuickPreset) => void;
  onApplyResult: (result: NaturalLanguagePeriodResult) => void;
}

const PeriodSelectionPopover = ({
  open,
  onOpenChange,
  selectedLabel,
  referenceDate,
  isLast30DaysActive,
  onQuickSelect,
  onApplyResult,
}: PeriodSelectionPopoverProps) => {
  const [inputValue, setInputValue] = useState("");


  const preview = useMemo(() => {
    if (!inputValue) {
      return { label: null, parsed: null } as const;
    }
    const parsed = parseNaturalLanguagePeriod(inputValue, referenceDate);
    return {
      parsed,
      label: generateNaturalLanguagePreview(parsed),
    } as const;
  }, [inputValue, referenceDate]);

  const closePopover = () => {
    onOpenChange(false);
  };

  const resetInput = () => {
    setInputValue("");
  };

  const applyResult = (value: string) => {
    const parsed = parseNaturalLanguagePeriod(value, referenceDate);
    if (!parsed) {
      return;
    }
    onApplyResult(parsed);
    resetInput();
    closePopover();
  };

  const handleInputChange = (value: string) => {
    setInputValue(value);
  };

  const handleKeyDown: KeyboardEventHandler<HTMLInputElement> = (event) => {
    if (event.key === "Enter") {
      event.preventDefault();
      applyResult(inputValue);
    }
    if (event.key === "Escape") {
      resetInput();
    }
  };


  const handleQuickSelect = (preset: QuickPreset) => {
    onQuickSelect(preset);
    resetInput();
    closePopover();
  };

  return (
    <Popover open={open} onOpenChange={onOpenChange}>
      <PopoverTrigger asChild>
        <Button variant="outline" className="h-9">
          {selectedLabel}
          <ChevronDown className="w-4 h-4 text-muted-foreground" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-96 p-4" align="end">
        <div className="space-y-4">
          <div className="text-sm font-medium">Select Time Period</div>

          <div className="grid grid-cols-3 gap-2">
            <Button
              variant={isLast30DaysActive ? "default" : "outline"}
              size="sm"
              onClick={() => handleQuickSelect("last30days")}
              className="h-8 text-xs"
            >
              Last 30 Days
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleQuickSelect("thisMonth")}
              className="h-8 text-xs"
            >
              This Month
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleQuickSelect("lastMonth")}
              className="h-8 text-xs"
            >
              Last Month
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleQuickSelect("thisQuarter")}
              className="h-8 text-xs"
            >
              This Quarter
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleQuickSelect("lastQuarter")}
              className="h-8 text-xs"
            >
              Last Quarter
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleQuickSelect("thisYear")}
              className="h-8 text-xs"
            >
              This Year
            </Button>
          </div>

          <Separator />

          <div className="space-y-3">
            <div className="text-xs text-muted-foreground">Or enter a custom period:</div>

            <div className="relative">
              <Input
                value={inputValue}
                onChange={(event) => handleInputChange(event.target.value)}
                onKeyDown={handleKeyDown}
                className="h-8 text-sm"
              />

              {inputValue && (
                <div className="mt-2 ml-3">
                  {preview.label ? (
                    <div className="flex items-center gap-2 text-xs">
                      <span className="font-medium text-green-600 dark:text-green-400">
                        {preview.label}
                      </span>
                    </div>
                  ) : (
                    <div className="text-xs text-amber-600 dark:text-amber-400">
                      Not recognized
                    </div>
                  )}
                </div>
              )}


            </div>
          </div>
        </div>
      </PopoverContent>
    </Popover>
  );
};

export default PeriodSelectionPopover;
