"use client";

import * as React from "react";
import { format, parse } from "date-fns";
import { enUS } from "date-fns/locale";
import { CalendarIcon } from "lucide-react";
import { useTranslation } from "react-i18next";

import { Button, buttonVariants } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import { Label } from "@/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";

export function AdminDateField({
  id,
  label,
  value,
  onChange,
  placeholder,
}: {
  id: string;
  label: string;
  /** `yyyy-MM-dd` or empty */
  value: string;
  onChange: (next: string) => void;
  placeholder?: string;
}) {
  const { t } = useTranslation(["common"]);
  const [open, setOpen] = React.useState(false);
  const resolvedPlaceholder = placeholder ?? t("date.placeholder", { ns: "common", defaultValue: "Select date" });

  const parsed = React.useMemo(() => {
    if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
      return undefined;
    }
    const d = parse(value, "yyyy-MM-dd", new Date());
    return Number.isNaN(d.getTime()) ? undefined : d;
  }, [value]);

  const summary = parsed ? format(parsed, "yyyy-MM-dd", { locale: enUS }) : resolvedPlaceholder;

  return (
    <div className="grid gap-1.5">
      <Label htmlFor={id}>{label}</Label>
      <Popover
        modal={false}
        open={open}
        onOpenChange={(next) => {
          setOpen(next);
        }}
      >
        <PopoverTrigger
          type="button"
          id={id}
          className={cn(
            buttonVariants({ variant: "outline", size: "default" }),
            "h-8 w-full justify-start gap-2 px-2.5 font-normal md:text-sm",
            !parsed && "text-muted-foreground",
          )}
        >
          <CalendarIcon className="pointer-events-none size-4 shrink-0 opacity-70" aria-hidden />
          <span className="min-w-0 flex-1 truncate text-left">{summary}</span>
        </PopoverTrigger>
        <PopoverContent align="start" sideOffset={6} className="w-auto min-w-fit p-0">
          <Calendar
            mode="single"
            locale={enUS}
            captionLayout="dropdown"
            selected={parsed}
            defaultMonth={parsed}
            onSelect={(d) => {
              onChange(d ? format(d, "yyyy-MM-dd") : "");
              setOpen(false);
            }}
          />
          <div className="flex justify-end border-t px-2 py-1">
            <Button
              type="button"
              variant="ghost"
              size="xs"
              className="h-7 px-2"
              onClick={() => {
                onChange("");
                setOpen(false);
              }}
            >
              {t("actions.clear", { ns: "common", defaultValue: "Clear" })}
            </Button>
          </div>
        </PopoverContent>
      </Popover>
    </div>
  );
}
