"use client";

import * as React from "react";
import { Calendar as CalendarIcon, ChevronLeft, ChevronRight, X } from "lucide-react";
import { motion, useReducedMotion } from "motion/react";

import { cn } from "@/lib/utils";
import { easeOutExpo } from "@/lib/motion";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
  SHORT_MONTHS,
  yearMonthFromDateInput,
  yearMonthInputValue,
} from "@/lib/date-utils";

export interface MonthYearPickerProps {
  value?: string;
  onChange: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  id?: string;
  className?: string;
  buttonClassName?: string;
  min?: string;
  max?: string;
  clearable?: boolean;
  align?: "start" | "center" | "end";
  title?: string;
}

export function MonthYearPicker({
  value,
  onChange,
  placeholder = "Select month",
  disabled = false,
  id,
  className,
  buttonClassName,
  min,
  max,
  clearable = false,
  align = "start",
  title,
}: MonthYearPickerProps) {
  const [open, setOpen] = React.useState(false);
  const reduceMotion = useReducedMotion();
  const selected = yearMonthFromDateInput(value);
  const minYm = yearMonthFromDateInput(min);
  const maxYm = yearMonthFromDateInput(max);
  const now = new Date();
  const [viewYear, setViewYear] = React.useState(
    selected?.year ?? now.getFullYear(),
  );

  React.useEffect(() => {
    if (selected) setViewYear(selected.year);
  }, [selected?.year]);

  const displayLabel = selected
    ? `${SHORT_MONTHS[selected.month - 1]} ${selected.year}`
    : placeholder;

  const ymValue = (year: number, month: number) => year * 100 + month;
  const minVal = minYm ? ymValue(minYm.year, minYm.month) : null;
  const maxVal = maxYm ? ymValue(maxYm.year, maxYm.month) : null;

  const isDisabledMonth = (year: number, month: number) => {
    const val = ymValue(year, month);
    if (minVal != null && val < minVal) return true;
    if (maxVal != null && val > maxVal) return true;
    return false;
  };

  const minYear = minYm?.year ?? 2018;
  const maxYear = maxYm?.year ?? now.getFullYear() + 5;

  const handleSelect = (month: number) => {
    if (isDisabledMonth(viewYear, month)) return;
    onChange(yearMonthInputValue(viewYear, month));
    setOpen(false);
  };

  const handleClear = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    onChange("");
  };

  return (
    <div className={cn("relative", className)}>
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            id={id}
            type="button"
            variant="outline"
            disabled={disabled}
            title={title}
            aria-label={title || placeholder}
            className={cn(
              "h-10 w-full justify-start gap-2 rounded-lg border-border bg-card px-3 text-left font-normal shadow-sm",
              "hover:border-primary/30 hover:bg-card",
              "focus-visible:ring-ring/40 data-[state=open]:border-primary/40 data-[state=open]:ring-2 data-[state=open]:ring-ring/40",
              !selected && "text-muted-foreground",
              selected && "text-foreground",
              buttonClassName,
            )}
          >
            <CalendarIcon className="h-4 w-4 shrink-0 text-primary" />
            <span className="min-w-0 flex-1 truncate tabular-nums">
              {displayLabel}
            </span>
            {clearable && selected && !disabled ? (
              <span
                role="button"
                tabIndex={0}
                aria-label="Clear month"
                className="rounded-md p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground"
                onClick={handleClear}
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    handleClear(e as unknown as React.MouseEvent);
                  }
                }}
              >
                <X className="h-3.5 w-3.5" />
              </span>
            ) : null}
          </Button>
        </PopoverTrigger>
        <PopoverContent
          align={align}
          sideOffset={8}
          className="w-[280px] p-0 overflow-hidden"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <motion.div
            initial={reduceMotion ? false : { opacity: 0, y: 4 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.18, ease: easeOutExpo }}
          >
            <div className="flex items-center justify-between border-b border-border px-3 py-2">
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-7 w-7"
                disabled={viewYear <= minYear}
                onClick={() => setViewYear((y) => y - 1)}
                aria-label="Previous year"
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <p className="text-sm font-semibold tabular-nums">{viewYear}</p>
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-7 w-7"
                disabled={viewYear >= maxYear}
                onClick={() => setViewYear((y) => y + 1)}
                aria-label="Next year"
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>

            <div className="grid grid-cols-3 gap-1 p-2">
              {SHORT_MONTHS.map((label, index) => {
                const month = index + 1;
                const isSelected =
                  selected?.year === viewYear && selected?.month === month;
                const monthDisabled = isDisabledMonth(viewYear, month);
                return (
                  <Button
                    key={label}
                    type="button"
                    variant={isSelected ? "default" : "ghost"}
                    size="sm"
                    disabled={monthDisabled}
                    className={cn(
                      "h-9 text-xs font-medium",
                      isSelected && "shadow-sm",
                    )}
                    onClick={() => handleSelect(month)}
                  >
                    {label}
                  </Button>
                );
              })}
            </div>
          </motion.div>
        </PopoverContent>
      </Popover>
    </div>
  );
}
