// BEGIN CHANGE: pagina Item Serial (lista + busca por serial)
"use client";

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

type CharOpt = {
  id: number;
  name: string;
  level: number;
  vocation: string;
  deleted: boolean;
  online: boolean;
  look: Look;
};

type SerialItem = {
  itemId: number;
  itemName: string;
  serial: string;
  location: "inventory" | "depot" | "house" | string;
  houseName?: string | null;
  playerName?: string | null;
  playerDeleted?: boolean;
  playerOnline?: boolean;
  pos?: { x: number; y: number; z: number };
  count?: number;
  containerPath?: string | null;
};

export default function SerialItemsPage() {
  const { t } = useI18n();
  const { ready, token, account, characters, setSession } = useAuth();
  const [chars, setChars] = useState<CharOpt[]>([]);
  const [playerId, setPlayerId] = useState("");
  const [items, setItems] = useState<SerialItem[]>([]);
  const [houseItems, setHouseItems] = useState<SerialItem[]>([]);
  const [listStatus, setListStatus] = useState<"idle" | "loading" | "ok" | "error">("idle");
  const [listErr, setListErr] = useState("");
  const [listHint, setListHint] = useState("");
  const [premiumOk, setPremiumOk] = useState<boolean | null>(
    account?.isPremium ?? null
  );

  const [serialInput, setSerialInput] = useState("");
  const [findStatus, setFindStatus] = useState<"idle" | "loading" | "ok" | "error">("idle");
  const [findErr, setFindErr] = useState("");
  const [found, setFound] = useState<SerialItem[]>([]);
  const [foundSerial, setFoundSerial] = useState("");

  const authHeaders = useCallback((): HeadersInit => {
    const h: Record<string, string> = {};
    if (token) h.Authorization = `Bearer ${token}`;
    return h;
  }, [token]);

  // BEGIN CHANGE: confirma Premium via me.php e atualiza sessao
  useEffect(() => {
    if (!ready || !token) return;
    fetch(apiUrl("me.php"), { headers: authHeaders() })
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => {
        if (!json?.account) return;
        const prem = !!json.account.isPremium;
        setPremiumOk(prem);
        setSession({
          token,
          account: { ...(account ?? json.account), ...json.account, isPremium: prem },
          characters: json.characters ?? characters,
        });
      })
      .catch(() => setPremiumOk(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ready, token, authHeaders]);
  // END CHANGE

  useEffect(() => {
    if (!ready) return;
    if (!token || !account) return;
    if (premiumOk === false) {
      setChars([]);
      return;
    }
    if (premiumOk !== true) return;
    fetch(apiUrl("serial-items.php?action=characters"), { headers: authHeaders() })
      .then(async (r) => {
        const j = await r.json().catch(() => ({}));
        if (!r.ok) {
          if (j.error === "premium_required") setPremiumOk(false);
          throw new Error("http");
        }
        return j;
      })
      .then((json) => {
        setChars((json.characters ?? []) as CharOpt[]);
      })
      .catch(() => setChars([]));
  }, [ready, token, account, authHeaders, premiumOk]);

  useEffect(() => {
    if (!token || !playerId || premiumOk !== true) {
      setItems([]);
      setHouseItems([]);
      setListStatus("idle");
      return;
    }
    let cancelled = false;
    setListStatus("loading");
    setListErr("");
    fetch(apiUrl(`serial-items.php?action=list&playerId=${encodeURIComponent(playerId)}`), {
      headers: authHeaders(),
    })
      .then((r) => r.json().then((j) => ({ ok: r.ok, j })))
      .then(({ ok, j }) => {
        if (cancelled) return;
        if (!ok || !j.ok) {
          if (j.error === "premium_required") setPremiumOk(false);
          setListStatus("error");
          setListErr(errLabel(typeof j.error === "string" ? j.error : "action_failed"));
          setItems([]);
          setHouseItems([]);
          return;
        }
        setItems((j.items ?? []) as SerialItem[]);
        setHouseItems((j.houseItems ?? []) as SerialItem[]);
        setListHint(typeof j.hint === "string" ? j.hint : "");
        setListStatus("ok");
      })
      .catch(() => {
        if (cancelled) return;
        setListStatus("error");
        setListErr(t.serialItems.loadFailed);
        setItems([]);
        setHouseItems([]);
      });
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token, playerId, authHeaders, premiumOk]);

  function errLabel(code: string) {
    const map = t.serialItems.errors as Record<string, string>;
    return map[code] || t.serialItems.loadFailed;
  }

  function locationLabel(loc: string) {
    if (loc === "inventory") return t.serialItems.locInventory;
    if (loc === "depot") return t.serialItems.locDepot;
    if (loc === "house") return t.serialItems.locHouse;
    return loc;
  }

  async function onFind(e: FormEvent) {
    e.preventDefault();
    if (!token || premiumOk !== true) return;
    setFindStatus("loading");
    setFindErr("");
    setFound([]);
    try {
      const r = await fetch(apiUrl("serial-items.php"), {
        method: "POST",
        headers: { ...authHeaders(), "Content-Type": "application/json" },
        body: JSON.stringify({ action: "find", serial: serialInput }),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok || !j.ok) {
        if (j.error === "premium_required") setPremiumOk(false);
        setFindStatus("error");
        setFindErr(errLabel(typeof j.error === "string" ? j.error : "action_failed"));
        return;
      }
      setFoundSerial(j.serial || serialInput);
      setFound((j.found ?? []) as SerialItem[]);
      setFindStatus("ok");
    } catch {
      setFindStatus("error");
      setFindErr(t.serialItems.loadFailed);
    }
  }

  const loggedIn = !!(ready && token && account);

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-5xl flex-1 px-6 py-14">
        <h1 className="text-3xl font-semibold tracking-tight">{t.serialItems.title}</h1>
        <p className="mt-2 text-muted">{t.serialItems.subtitle}</p>
        <ul className="mt-4 list-disc space-y-1 pl-5 text-sm text-muted">
          <li>{t.serialItems.hintSaved}</li>
          <li>{t.serialItems.hintSerialOnly}</li>
          <li>{t.serialItems.hintHouse}</li>
        </ul>

        {!loggedIn && ready && (
          <p className="mt-6 text-sm text-muted">
            {t.serialItems.needLogin}{" "}
            <Link href="/login" className="text-brand hover:underline">
              {t.nav.items.login}
            </Link>
          </p>
        )}

        {loggedIn && premiumOk === false && (
          <p className="mt-6 text-sm text-muted">
            {t.serialItems.needPremium}{" "}
            <Link href="/donate" className="text-brand hover:underline">
              {t.nav.items.donate}
            </Link>
          </p>
        )}

        {loggedIn && premiumOk === true && (
          <>
            <section className="mt-8 rounded-xl border border-border bg-panel p-5">
              <h2 className="text-lg font-semibold">{t.serialItems.myItemsTitle}</h2>
              <p className="mt-1 text-sm text-muted">{t.serialItems.myItemsHint}</p>

              <label className="mt-4 block text-sm">
                <span className="text-muted">{t.serialItems.character}</span>
                <select
                  className="mt-1 block min-w-[16rem] rounded border border-border bg-background px-3 py-2"
                  value={playerId}
                  onChange={(e) => setPlayerId(e.target.value)}
                >
                  <option value="">{t.serialItems.pickCharacter}</option>
                  {chars.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name} - {c.vocation} {c.level}
                      {c.online ? ` (${t.serialItems.online})` : ""}
                      {c.deleted ? ` (${t.serialItems.deleted})` : ""}
                    </option>
                  ))}
                </select>
              </label>

              {listStatus === "loading" && (
                <p className="mt-4 text-sm text-muted">{t.common.loading}</p>
              )}
              {listStatus === "error" && (
                <p className="mt-4 text-sm text-red-400">{listErr}</p>
              )}
              {listStatus === "ok" && items.length === 0 && (
                <p className="mt-4 text-sm text-muted">{t.serialItems.emptyList}</p>
              )}
              {listStatus === "ok" && items.length > 0 && (
                <>
                  <p className="mt-4 text-xs text-muted">
                    {t.serialItems.count.replace("{n}", String(items.length))}
                    {listHint ? ` - ${t.serialItems.hintSaved}` : ""}
                  </p>
                  <SerialTable
                    items={items}
                    showOwner={false}
                    locationLabel={locationLabel}
                    labels={{
                      item: t.serialItems.colItem,
                      name: t.serialItems.colName,
                      serial: t.serialItems.colSerial,
                      location: t.serialItems.colLocation,
                      owner: t.serialItems.colOwner,
                    }}
                  />
                </>
              )}

              {/* BEGIN CHANGE: house_items even without serial */}
              {listStatus === "ok" && (
                <div className="mt-8 border-t border-border pt-6">
                  <h3 className="text-base font-semibold">{t.serialItems.houseTitle}</h3>
                  <p className="mt-1 text-sm text-muted">{t.serialItems.houseHint}</p>
                  {houseItems.length === 0 ? (
                    <p className="mt-4 text-sm text-muted">{t.serialItems.houseEmpty}</p>
                  ) : (
                    <>
                      <p className="mt-4 text-xs text-muted">
                        {t.serialItems.houseCount.replace("{n}", String(houseItems.length))}
                      </p>
                      <HouseItemsTable
                        items={houseItems}
                        labels={{
                          item: t.serialItems.colItem,
                          name: t.serialItems.colName,
                          count: t.serialItems.colCount,
                          house: t.serialItems.colHouse,
                          location: t.serialItems.colLocation,
                        }}
                      />
                    </>
                  )}
                </div>
              )}
              {/* END CHANGE */}
            </section>

            <section className="mt-8 rounded-xl border border-border bg-panel p-5">
              <h2 className="text-lg font-semibold">{t.serialItems.findTitle}</h2>
              <p className="mt-1 text-sm text-muted">{t.serialItems.findHint}</p>

              <form onSubmit={onFind} className="mt-4 flex flex-wrap items-end gap-3">
                <label className="text-sm">
                  <span className="text-muted">{t.serialItems.serialLabel}</span>
                  <input
                    type="text"
                    value={serialInput}
                    onChange={(e) => setSerialInput(e.target.value)}
                    placeholder="XXXXX-XXXXX-XXXXX-XXXXX"
                    className="mt-1 block min-w-[18rem] rounded border border-border bg-background px-3 py-2 font-mono text-sm uppercase"
                    required
                  />
                </label>
                <button
                  type="submit"
                  disabled={findStatus === "loading"}
                  className="rounded bg-brand px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
                >
                  {t.serialItems.findBtn}
                </button>
              </form>

              {findStatus === "loading" && (
                <p className="mt-4 text-sm text-muted">{t.common.loading}</p>
              )}
              {findStatus === "error" && (
                <p className="mt-4 text-sm text-red-400">{findErr}</p>
              )}
              {findStatus === "ok" && found.length === 0 && (
                <p className="mt-4 text-sm text-muted">
                  {t.serialItems.notFound.replace("{serial}", foundSerial)}
                </p>
              )}
              {findStatus === "ok" && found.length > 0 && (
                <>
                  <p className="mt-4 text-xs text-muted">
                    {t.serialItems.foundFor.replace("{serial}", foundSerial)}
                  </p>
                  <SerialTable
                    items={found}
                    showOwner
                    locationLabel={locationLabel}
                    labels={{
                      item: t.serialItems.colItem,
                      name: t.serialItems.colName,
                      serial: t.serialItems.colSerial,
                      location: t.serialItems.colLocation,
                      owner: t.serialItems.colOwner,
                    }}
                  />
                </>
              )}
            </section>
          </>
        )}
      </main>
      <Footer />
    </div>
  );
}

function SerialTable({
  items,
  showOwner,
  locationLabel,
  labels,
}: {
  items: SerialItem[];
  showOwner: boolean;
  locationLabel: (loc: string) => string;
  labels: {
    item: string;
    name: string;
    serial: string;
    location: string;
    owner: string;
  };
}) {
  return (
    <div className="mt-4 overflow-x-auto rounded-lg border border-border">
      <table className="w-full min-w-[36rem] text-sm">
        <thead>
          <tr className="border-b border-border bg-background/50 text-left text-muted">
            <th className="px-3 py-2 font-medium">{labels.item}</th>
            <th className="px-3 py-2 font-medium">{labels.name}</th>
            <th className="px-3 py-2 font-medium">{labels.serial}</th>
            <th className="px-3 py-2 font-medium">{labels.location}</th>
            {showOwner ? (
              <th className="px-3 py-2 font-medium">{labels.owner}</th>
            ) : null}
          </tr>
        </thead>
        <tbody>
          {items.map((it, idx) => {
            let loc = locationLabel(it.location);
            if (it.location === "house" && it.houseName) {
              loc = `${loc}: ${it.houseName}`;
              if (it.pos) loc += ` (${it.pos.x}, ${it.pos.y}, ${it.pos.z})`;
            }
            return (
              <tr
                key={`${it.serial}-${it.location}-${idx}`}
                className="border-b border-border/40 last:border-0"
              >
                <td className="px-3 py-2">
                  <ItemIcon id={it.itemId} size={32} alt={it.itemName} />
                </td>
                <td className="px-3 py-2 font-medium">{it.itemName}</td>
                <td className="px-3 py-2 font-mono text-xs">{it.serial || "-"}</td>
                <td className="px-3 py-2 text-muted">{loc}</td>
                {showOwner ? (
                  <td className="px-3 py-2">{it.playerName || "-"}</td>
                ) : null}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
// END CHANGE

function HouseItemsTable({
  items,
  labels,
}: {
  items: SerialItem[];
  labels: {
    item: string;
    name: string;
    count: string;
    house: string;
    location: string;
  };
}) {
  return (
    <div className="mt-4 overflow-x-auto rounded-lg border border-border">
      <table className="w-full min-w-[36rem] text-sm">
        <thead>
          <tr className="border-b border-border bg-background/50 text-left text-muted">
            <th className="px-3 py-2 font-medium">{labels.item}</th>
            <th className="px-3 py-2 font-medium">{labels.name}</th>
            <th className="px-3 py-2 font-medium">{labels.count}</th>
            <th className="px-3 py-2 font-medium">{labels.house}</th>
            <th className="px-3 py-2 font-medium">{labels.location}</th>
          </tr>
        </thead>
        <tbody>
          {items.map((it, idx) => {
            const loc =
              it.containerPath ||
              (it.pos ? `(${it.pos.x}, ${it.pos.y}, ${it.pos.z})` : "-");
            return (
              <tr
                key={`house-${it.itemId}-${idx}`}
                className="border-b border-border/40 last:border-0"
              >
                <td className="px-3 py-2">
                  <ItemIcon id={it.itemId} size={32} alt={it.itemName} />
                </td>
                <td className="px-3 py-2 font-medium">{it.itemName}</td>
                <td className="px-3 py-2">{it.count ?? 1}</td>
                <td className="px-3 py-2 text-muted">{it.houseName || "-"}</td>
                <td className="px-3 py-2 text-muted">{loc}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
