// BEGIN CHANGE: pagina Biblioteca ? busca item -> monstros que dropam
"use client";

import { FormEvent, useState } from "react";
import Link from "next/link";
import { useI18n } from "@/i18n/LanguageProvider";
import { Navbar } from "@/components/Navbar";
import { Footer } from "@/components/Footer";
import { Outfit } from "@/components/Outfit";
import { ItemIcon } from "@/components/ItemIcon";
import { apiUrl, type Look } from "@/lib/api";

type DropMonster = {
  name: string;
  exp: number;
  health: number;
  race: string;
  look: Look | null;
  chance: number;
  countMax: number;
};

type ItemResult = {
  id: number;
  name: string;
  monsterCount: number;
  monsters: DropMonster[];
};

export default function ItemDropsPage() {
  const { t } = useI18n();
  const [query, setQuery] = useState("");
  const [rows, setRows] = useState<ItemResult[]>([]);
  const [status, setStatus] = useState<"idle" | "loading" | "ok" | "error">("idle");
  const [searched, setSearched] = useState("");

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    const q = query.trim();
    if (q.length < 2) return;
    setStatus("loading");
    setSearched(q);
    try {
      const res = await fetch(apiUrl(`item-drops.php?q=${encodeURIComponent(q)}`));
      if (!res.ok) throw new Error("http " + res.status);
      const json = await res.json();
      setRows(json.data ?? []);
      setStatus("ok");
    } catch {
      setRows([]);
      setStatus("error");
    }
  }

  const chancePct = (c: number) => (c > 0 ? `${(c / 1000).toFixed(1)}%` : "-");

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-6xl flex-1 px-6 py-14">
        <h1 className="text-3xl font-semibold tracking-tight">{t.itemDrops.title}</h1>
        <p className="mt-2 text-muted">{t.itemDrops.subtitle}</p>

        <form onSubmit={onSubmit} className="mt-6 flex flex-col gap-3 sm:flex-row sm:items-center">
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder={t.itemDrops.searchPlaceholder}
            className="w-full max-w-md rounded-lg border border-border bg-panel px-4 py-2 text-sm outline-none focus:border-brand/60"
          />
          <button
            type="submit"
            disabled={status === "loading" || query.trim().length < 2}
            className="rounded-lg bg-brand px-5 py-2 text-sm font-medium text-background transition-opacity hover:opacity-90 disabled:opacity-50"
          >
            {status === "loading" ? t.common.loading : t.itemDrops.searchBtn}
          </button>
        </form>

        {status === "error" && <p className="mt-8 text-muted">{t.common.error}</p>}
        {status === "ok" && rows.length === 0 && (
          <p className="mt-8 text-muted">
            {t.itemDrops.noResults} <span className="text-brand">{searched}</span>
          </p>
        )}

        {status === "ok" &&
          rows.map((item) => (
            <section key={item.id} className="mt-10">
              <div className="mb-4 flex items-center gap-3">
                <ItemIcon id={item.id} alt={item.name} />
                <div>
                  <h2 className="text-xl font-semibold tracking-tight">{item.name}</h2>
                  <p className="text-sm text-muted">
                    {t.itemDrops.itemId}: {item.id}  - {" "}
                    {item.monsterCount === 1
                      ? t.itemDrops.oneMonster
                      : t.itemDrops.manyMonsters.replace("{n}", String(item.monsterCount))}
                  </p>
                </div>
              </div>

              {item.monsters.length === 0 ? (
                <p className="text-sm text-muted">{t.itemDrops.noMonsters}</p>
              ) : (
                <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
                  {item.monsters.map((m) => (
                    <Link
                      key={`${item.id}-${m.name}`}
                      href={`/monster/?name=${encodeURIComponent(m.name)}`}
                      className="flex items-center gap-4 rounded-xl border border-border bg-panel p-4 transition-colors hover:border-brand/40"
                    >
                      <div className="grid shrink-0 place-items-center">
                        {m.look ? (
                          <Outfit look={m.look} size="grid" alt={m.name} />
                        ) : (
                          <span className="grid h-12 w-12 place-items-center rounded bg-background text-xs text-muted">
                            ?
                          </span>
                        )}
                      </div>
                      <div className="min-w-0">
                        <div className="truncate font-medium">{m.name}</div>
                        <div className="mt-1 text-xs text-muted">
                          {t.monsters.exp}: {m.exp.toLocaleString()}
                        </div>
                        <div className="text-xs text-muted">
                          {t.monsters.health}: {m.health.toLocaleString()}
                        </div>
                        <div className="mt-1 text-xs text-brand">
                          {t.itemDrops.chance}: {chancePct(m.chance)}
                          {m.countMax > 1 ? ` (x${m.countMax})` : ""}
                        </div>
                      </div>
                    </Link>
                  ))}
                </div>
              )}
            </section>
          ))}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
