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-8 gap-1.5 rounded-full border-[#e7e5e1] bg-white px-3.5 text-xs font-semibold text-[#2b2925] shadow-none hover:bg-[#faf9f7]"
        >
          {selectedLabel}
          <ChevronDown className="h-3.5 w-3.5 text-[#a09b92]" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-96 rounded-[14px] border-[#e7e5e1] p-4 shadow-lg" align="end">
        <div className="space-y-4">
          <div className="text-[10.5px] font-semibold uppercase tracking-wide text-[#a09b92]">
            Time period
          </div>

          <div className="grid grid-cols-3 gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleQuickSelect("last30days")}
              className={`h-8 rounded-full text-xs shadow-none ${
                isLast30DaysActive
                  ? "border-[#2b2925] bg-[#2b2925] text-white hover:bg-[#2b2925]/90 hover:text-white"
                  : "border-[#e7e5e1] text-[#2b2925] hover:bg-[#faf9f7]"
              }`}
            >
              Last 30 Days
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="h-8 rounded-full border-[#e7e5e1] text-xs text-[#2b2925] shadow-none hover:bg-[#faf9f7]"
              onClick={() => handleQuickSelect("thisMonth")}
            >
              This Month
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="h-8 rounded-full border-[#e7e5e1] text-xs text-[#2b2925] shadow-none hover:bg-[#faf9f7]"
              onClick={() => handleQuickSelect("lastMonth")}
            >
              Last Month
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="h-8 rounded-full border-[#e7e5e1] text-xs text-[#2b2925] shadow-none hover:bg-[#faf9f7]"
              onClick={() => handleQuickSelect("thisQuarter")}
            >
              This Quarter
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="h-8 rounded-full border-[#e7e5e1] text-xs text-[#2b2925] shadow-none hover:bg-[#faf9f7]"
              onClick={() => handleQuickSelect("lastQuarter")}
            >
              Last Quarter
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="h-8 rounded-full border-[#e7e5e1] text-xs text-[#2b2925] shadow-none hover:bg-[#faf9f7]"
              onClick={() => handleQuickSelect("thisYear")}
            >
              This Year
            </Button>
          </div>

          <Separator />

          <div className="space-y-3">
            <div className="text-xs text-[#7c7870]">Or enter a custom period:</div>

            <div className="relative">
              <Input
                value={inputValue}
                onChange={(event) => handleInputChange(event.target.value)}
                onKeyDown={handleKeyDown}
                className="h-8 rounded-full border-[#e7e5e1] px-3.5 text-sm shadow-none"
              />

              {inputValue && (
                <div className="mt-2 ml-3">
                  {preview.label ? (
                    <div className="flex items-center gap-2 text-xs">
                      <span className="font-medium text-[#237a4d]">
                        {preview.label}
                      </span>
                    </div>
                  ) : (
                    <div className="text-xs text-[#a87a24]">
                      Not recognized
                    </div>
                  )}
                </div>
              )}


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

export default PeriodSelectionPopover;
