import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Bootstrap, Item } from "../../types.js";
import { helpers, TODAY_STR, enrichItems } from "../../types.js";
import { fmt } from "../../format.js";
import { api } from "../../api.js";
import { Btn, Field, Icon, Input, Textarea } from "../primitives/index.js";
import { ScanField, type ScanResult } from "../ScanField.js";
import { ModalBackdrop, ModalHeader, ModalFooter } from "./ModalChrome.js";
import { useToast } from "../Toast.js";

export function ConsumeFlow({
  data,
  onClose,
  item: initialItem,
}: {
  data: Bootstrap;
  onClose: () => void;
  item: Item | null;
}) {
  const qc = useQueryClient();
  const { toast } = useToast();
  const allItems = enrichItems(data);
  const active = allItems.filter((i) => i.status === "active");
  const [itemId, setItemId] = useState(initialItem?.id ?? active[0]?.id ?? "");
  const [rating, setRating] = useState(4);
  const [notes, setNotes] = useState("");
  const [date, setDate] = useState(TODAY_STR);
  const [error, setError] = useState<string | null>(null);

  const item = allItems.find((i) => i.id === itemId);

  const finish = useMutation({
    mutationFn: () => api.finishInventoryItem(itemId, { date, rating, notes }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["bootstrap"] });
      toast(`Marked ${item?.name ?? "item"} as consumed — ${rating}/5 stars`);
      onClose();
    },
    onError: (e: Error) => setError(e.message),
  });

  const handleScan = (result: ScanResult) => {
    if (result.kind === "item") {
      setItemId(result.item.id);
    }
  };

  if (!item) return null;
  const bin = data.bins.find((b) => b.id === item.binId);
  const lifespan = Math.round((+new Date(date) - +new Date(item.purchaseDate)) / 86_400_000);

  return (
    <ModalBackdrop onClose={onClose}>
      <div
        style={{
          width: "min(720px, 96vw)",
          margin: "40px 20px",
          background: "var(--bg)",
          border: "1px solid var(--line)",
          borderRadius: "var(--r-lg)",
          boxShadow: "var(--shadow-lg)",
        }}
      >
        <ModalHeader title="Mark as consumed" eyebrow="" onClose={onClose} />

        <div style={{ padding: 32 }}>
          <ScanField
            items={active}
            products={[]}
            matchedLabel={item ? `${item.assetId} · ${item.name}` : null}
            onMatch={handleScan}
          />

          <div
            style={{
              marginTop: 16,
              padding: 16,
              background: "var(--bg-2)",
              border: "1px solid var(--line)",
              borderRadius: "var(--r-md)",
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            <div>
              <div className="serif" style={{ fontSize: 22, fontWeight: 500 }}>
                {item.name}
              </div>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>
                <span className="mono">{item.assetId}</span> · {helpers.brandName(data, item.brandId)} · {bin?.name} · purchased{" "}
                {fmt.dateShort(item.purchaseDate)}
              </div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>LASTED</div>
              <div className="serif" style={{ fontSize: 24 }}>{lifespan} days</div>
            </div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 24 }}>
            <Field label="Date finished">
              <Input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
            </Field>
            <Field label="Rating">
              <div
                style={{
                  display: "flex",
                  gap: 4,
                  alignItems: "center",
                  padding: "10px 12px",
                  background: "var(--bg)",
                  border: "1px solid var(--line)",
                  borderRadius: "var(--r-md)",
                }}
              >
                {[1, 2, 3, 4, 5].map((n) => (
                  <button
                    key={n}
                    onClick={() => setRating(n)}
                    style={{ border: "none", background: "transparent", cursor: "pointer", padding: 2 }}
                  >
                    <Icon
                      name="star"
                      size={20}
                      color={n <= rating ? "var(--amber)" : "var(--ink-4)"}
                    />
                  </button>
                ))}
                <span
                  style={{
                    marginLeft: "auto",
                    fontSize: 12,
                    color: "var(--ink-3)",
                    fontFamily: "var(--mono)",
                  }}
                >
                  {rating}/5
                </span>
              </div>
            </Field>
          </div>
          <div style={{ marginTop: 16 }}>
            <Field label="Final notes" hint="Flavor, effects, would you rebuy">
              <Textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="What stood out?"
              />
            </Field>
          </div>

          {error && (
            <div style={{ marginTop: 14, fontSize: 12, color: "var(--terracotta)" }}>{error}</div>
          )}
        </div>

        <ModalFooter>
          <div />
          <div style={{ display: "flex", gap: 8 }}>
            <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
            <Btn
              variant="primary"
              icon="check"
              disabled={finish.isPending}
              onClick={() => finish.mutate()}
            >
              {finish.isPending ? "Saving…" : "Mark consumed"}
            </Btn>
          </div>
        </ModalFooter>
      </div>
    </ModalBackdrop>
  );
}
