"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { GROCERY_CATEGORIES } from "@/lib/grocery-categories";

export type PantryItem = {
  id: string;
  rawName: string;
  quantity: string | null;
  unit: string | null;
  notes: string | null;
  aisle: string | null;
  expiresAt: string | null;
};

const OTHER_VALUE = "__other__";

function categoryLabel(value: string, tShopping: (key: string) => string): string {
  return value === OTHER_VALUE ? tShopping("aisleOther") : tShopping(`categories.${value}`);
}

export function PantryItemDialog({
  item,
  open,
  onOpenChange,
  onSaved,
}: {
  item: PantryItem;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSaved: (updated: PantryItem) => void;
}) {
  const t = useTranslations("pantry");
  const tShopping = useTranslations("shoppingLists");
  const tCommon = useTranslations("common");
  const [rawName, setRawName] = useState(item.rawName);
  const [quantity, setQuantity] = useState(item.quantity ?? "");
  const [unit, setUnit] = useState(item.unit ?? "");
  const [aisle, setAisle] = useState(item.aisle ?? OTHER_VALUE);
  const [notes, setNotes] = useState(item.notes ?? "");
  const [expiresAt, setExpiresAt] = useState(item.expiresAt ? item.expiresAt.slice(0, 10) : "");
  const [saving, setSaving] = useState(false);

  async function handleSave() {
    if (!rawName.trim()) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/v1/pantry/${item.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          rawName: rawName.trim(),
          quantity: quantity.trim() || null,
          unit: unit.trim() || null,
          aisle: aisle === OTHER_VALUE ? null : aisle,
          notes: notes.trim() || null,
          expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null,
        }),
      });
      if (!res.ok) { toast.error(t("editFailed")); return; }
      toast.success(t("editSaved"));
      onSaved({
        id: item.id,
        rawName: rawName.trim(),
        quantity: quantity.trim() || null,
        unit: unit.trim() || null,
        aisle: aisle === OTHER_VALUE ? null : aisle,
        notes: notes.trim() || null,
        expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null,
      });
      onOpenChange(false);
    } finally {
      setSaving(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-sm">
        <DialogHeader>
          <DialogTitle>{t("editDialogTitle")}</DialogTitle>
        </DialogHeader>
        <div className="space-y-3">
          <div className="space-y-1.5">
            <Label htmlFor="pantry-edit-name">{t("itemNamePlaceholder")}</Label>
            <Input id="pantry-edit-name" value={rawName} onChange={(e) => setRawName(e.target.value)} />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label htmlFor="pantry-edit-qty">{t("qtyPlaceholder")}</Label>
              <Input id="pantry-edit-qty" value={quantity} onChange={(e) => setQuantity(e.target.value)} />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="pantry-edit-unit">{t("unitPlaceholder")}</Label>
              <Input id="pantry-edit-unit" value={unit} onChange={(e) => setUnit(e.target.value)} />
            </div>
          </div>
          <div className="space-y-1.5">
            <Label>{t("categoryLabel")}</Label>
            <Select value={aisle} onValueChange={(v) => setAisle(v ?? OTHER_VALUE)}>
              <SelectTrigger>
                <SelectValue>{(v: string) => categoryLabel(v, tShopping)}</SelectValue>
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={OTHER_VALUE}>{tShopping("aisleOther")}</SelectItem>
                {GROCERY_CATEGORIES.map((c) => (
                  <SelectItem key={c} value={c}>{tShopping(`categories.${c}`)}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="pantry-edit-expiry">{t("colExpires")}</Label>
            <Input id="pantry-edit-expiry" type="date" value={expiresAt} onChange={(e) => setExpiresAt(e.target.value)} />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="pantry-edit-notes">{t("notesLabel")}</Label>
            <Textarea id="pantry-edit-notes" value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} placeholder={t("notesPlaceholder")} />
          </div>
        </div>
        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
            {tCommon("cancel")}
          </Button>
          <Button type="button" onClick={() => { void handleSave(); }} disabled={saving || !rawName.trim()}>
            {saving ? tCommon("saving") : tCommon("save")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
