"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";

export type CookLog = {
  id: string;
  cookedAt: string;
  servings: number | null;
  notes: string | null;
};

export function EditCookLogDialog({
  recipeId,
  log,
  open,
  onOpenChange,
  onSaved,
}: {
  recipeId: string;
  log: CookLog;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSaved: (updated: CookLog) => void;
}) {
  const t = useTranslations("recipe");
  const tCommon = useTranslations("common");
  const [date, setDate] = useState(log.cookedAt.slice(0, 10));
  const [servings, setServings] = useState(log.servings ?? "");
  const [notes, setNotes] = useState(log.notes ?? "");
  const [saving, setSaving] = useState(false);

  async function handleSave() {
    setSaving(true);
    try {
      const res = await fetch(`/api/v1/recipes/${recipeId}/cooked/${log.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          cookedAt: date,
          servings: servings === "" ? null : Number(servings),
          notes: notes.trim() || null,
        }),
      });
      if (!res.ok) { toast.error(t("editCookLogFailed")); return; }
      toast.success(t("editCookLogSaved"));
      onSaved({ id: log.id, cookedAt: new Date(date).toISOString(), servings: servings === "" ? null : Number(servings), notes: notes.trim() || null });
      onOpenChange(false);
    } finally {
      setSaving(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-sm">
        <DialogHeader>
          <DialogTitle>{t("editCookLogTitle")}</DialogTitle>
        </DialogHeader>
        <div className="space-y-3">
          <div className="space-y-1.5">
            <Label htmlFor="cook-log-date">{t("markCookedDateLabel")}</Label>
            <Input id="cook-log-date" type="date" value={date} max={new Date().toISOString().slice(0, 10)} onChange={(e) => setDate(e.target.value)} />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="cook-log-servings">{t("markCookedServingsLabel")}</Label>
            <Input
              id="cook-log-servings"
              type="number"
              min={1}
              value={servings}
              onChange={(e) => setServings(e.target.value === "" ? "" : Math.max(1, Number(e.target.value)))}
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="cook-log-notes">{t("cookLogNotesLabel")}</Label>
            <Textarea id="cook-log-notes" value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} />
          </div>
        </div>
        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
            {tCommon("cancel")}
          </Button>
          <Button type="button" onClick={() => { void handleSave(); }} disabled={saving}>
            {saving ? tCommon("saving") : tCommon("save")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
