import Link from "next/link";
import Badge from "@/components/ui/Badge";
import PageHeader from "@/components/ui/PageHeader";
import ControlCenterNav from "@/components/layout/ControlCenterNav";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
import { shopRepository } from "@/lib/repositories/shopRepository";
import { firstSearchParam, resolveShopScope } from "@/lib/storeScope";
import { getCurrentUser } from "@/lib/currentUser";

export const dynamic = "force-dynamic";

function formatDate(value: Date) {
  return new Intl.DateTimeFormat("id-ID", { dateStyle: "medium", timeStyle: "medium" }).format(value);
}

function categoryWhere(type: string): Prisma.ShopeeApiLogWhereInput | null {
  if (type === "orders") return { OR: [{ path: { contains: "/orders" } }, { path: { contains: "/push" } }, { path: { contains: "auto-sync" } }] };
  if (type === "products") return { path: { contains: "/products" } };
  if (type === "finance") return { OR: [{ path: { contains: "/finance" } }, { path: { contains: "escrow" } }, { path: { contains: "payment" } }] };
  if (type === "connection") return { OR: [{ path: { contains: "/token" } }, { path: { contains: "/auth" } }, { path: { contains: "shop_info" } }] };
  return null;
}

function logTitle(path: string) {
  if (path.includes("products")) return "Sinkron produk";
  if (path.includes("finance") || path.includes("escrow") || path.includes("payment")) return "Sinkron finance";
  if (path.includes("push")) return "Push Shopee";
  if (path.includes("orders") || path.includes("auto-sync")) return "Sinkron pesanan";
  if (path.includes("token")) return "Token akses";
  if (path.includes("auth")) return "Otorisasi";
  return "Request Shopee API";
}

type SearchParams = Promise<Record<string, string | string[] | undefined>>;

export default async function LogsPage({ searchParams }: { searchParams: SearchParams }) {
  const current = await getCurrentUser();
  const [params, shops] = await Promise.all([searchParams, current ? shopRepository.findScopeOptionsForUser(current) : Promise.resolve([])]);
  const shopId = resolveShopScope(firstSearchParam(params.shop_id), shops);
  const result = firstSearchParam(params.result) || "all";
  const type = firstSearchParam(params.type) || "all";
  const q = firstSearchParam(params.q) || "";
  const page = Math.max(Number(firstSearchParam(params.page)) || 1, 1);
  const pageSize = 50;
  const baseAnd: Prisma.ShopeeApiLogWhereInput[] = [];
  if (shopId) baseAnd.push({ shopId });
  else if (current?.role !== "super_admin") baseAnd.push({ shopId: { in: shops.map((shop) => shop.shopId) } });
  const category = categoryWhere(type);
  if (category) baseAnd.push(category);
  if (q) baseAnd.push({ OR: [{ path: { contains: q } }, { message: { contains: q } }] });
  const baseWhere: Prisma.ShopeeApiLogWhereInput = baseAnd.length ? { AND: baseAnd } : {};
  const where: Prisma.ShopeeApiLogWhereInput = result === "success" ? { AND: [baseWhere, { success: true }] } : result === "failed" ? { AND: [baseWhere, { success: false }] } : baseWhere;
  const [logs, filteredTotal, total, failed, latestSuccess] = await Promise.all([
    prisma.shopeeApiLog.findMany({ where, orderBy: { createdAt: "desc" }, skip: (page - 1) * pageSize, take: pageSize }),
    prisma.shopeeApiLog.count({ where }),
    prisma.shopeeApiLog.count({ where: baseWhere }),
    prisma.shopeeApiLog.count({ where: { AND: [baseWhere, { success: false }] } }),
    prisma.shopeeApiLog.findFirst({ where: { AND: [baseWhere, { success: true }] }, orderBy: { createdAt: "desc" } }),
  ]);
  const totalPages = Math.max(Math.ceil(filteredTotal / pageSize), 1);
  const query = new URLSearchParams({ result, type });
  if (shopId) query.set("shop_id", shopId);
  if (q) query.set("q", q);

  return (
    <div className="space-y-5">
      <PageHeader eyebrow="Toko & Sistem" title="Aktivitas" description="Riwayat sinkronisasi dan error API. Gunakan filter untuk menemukan masalah pada toko atau modul tertentu." actions={<><Link className="ui-button ui-button-secondary" href="/integrations">Diagnostik koneksi</Link><Link className="ui-button ui-button-primary" href={`/orders${shopId ? `?shop_id=${shopId}` : ""}`}>Buka pesanan</Link></>} />

      <ControlCenterNav />

      <section className="activity-overview">
        <div className="activity-overview-copy"><span className={`system-health-dot ${failed ? "is-warning" : "is-good"}`} /><div><div className="text-sm font-bold text-slate-950">{failed ? `${failed} aktivitas gagal perlu diperiksa` : "Tidak ada kegagalan pada cakupan ini"}</div><div className="mt-1 text-xs text-slate-500">Sukses terakhir: {latestSuccess ? formatDate(latestSuccess.createdAt) : "belum ada"}</div></div></div>
        <div className="activity-overview-stats"><span><strong>{total}</strong>Total</span><span><strong className="text-emerald-700">{total - failed}</strong>Sukses</span><span><strong className={failed ? "text-rose-700" : "text-slate-950"}>{failed}</strong>Gagal</span></div>
      </section>

      <section className="scope-toolbar">
        <form className="grid gap-3 lg:grid-cols-[1fr_1fr_1fr_1.4fr_auto] lg:items-end">
          <label><span className="muted-label">Toko</span><select className="mt-2 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm" name="shop_id" defaultValue={shopId || ""}><option value="">Semua toko</option>{shops.map((shop) => <option key={shop.shopId} value={shop.shopId}>{shop.shopName || shop.shopId}{shop.connected ? "" : " · disconnected"}</option>)}</select></label>
          <label><span className="muted-label">Modul</span><select className="mt-2 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm" name="type" defaultValue={type}><option value="all">Semua modul</option><option value="orders">Pesanan & push</option><option value="products">Produk</option><option value="finance">Finance</option><option value="connection">Koneksi & token</option></select></label>
          <label><span className="muted-label">Hasil</span><select className="mt-2 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm" name="result" defaultValue={result}><option value="all">Semua hasil</option><option value="success">Sukses</option><option value="failed">Gagal</option></select></label>
          <label><span className="muted-label">Cari aktivitas</span><input className="mt-2 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm" name="q" defaultValue={q} placeholder="Pesan error atau endpoint" /></label>
          <button className="ui-button ui-button-primary" type="submit">Terapkan</button>
        </form>
      </section>

      <section className="surface overflow-hidden">
        <div className="overflow-auto">
          <table className="w-full min-w-[880px] text-left text-sm">
            <thead className="bg-slate-50 text-xs uppercase tracking-wide text-slate-500">
              <tr>
                <th className="px-4 py-3">Waktu</th>
                <th className="px-4 py-3">Toko</th>
                <th className="px-4 py-3">Aktivitas</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Pesan</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {logs.map((log) => (
                <tr key={log.id} className="hover:bg-slate-50">
                  <td className="px-4 py-3 text-xs text-slate-500">{formatDate(log.createdAt)}</td>
                  <td className="px-4 py-3 font-mono text-xs">{log.shopId || "-"}</td>
                  <td className="px-4 py-3"><div className="font-semibold text-slate-800">{logTitle(log.path)}</div><div className="mt-1 font-mono text-[10px] text-slate-400">{log.method} {log.path}</div></td>
                  <td className="px-4 py-3"><Badge tone={log.success ? "success" : "danger"}>{log.statusCode || "-"} {log.success ? "OK" : "Fail"}</Badge></td>
                  <td className="px-4 py-3 text-slate-600">{log.message || "-"}</td>
                </tr>
              ))}
            </tbody>
          </table>
          {logs.length === 0 ? <div className="py-10 text-center text-sm text-slate-500">Tidak ada aktivitas yang cocok dengan filter.</div> : null}
        </div>
      </section>
      {filteredTotal > 0 ? <div className="flex flex-wrap items-center justify-between gap-3 text-sm text-slate-500"><span>Menampilkan {(page - 1) * pageSize + 1}–{Math.min(page * pageSize, filteredTotal)} dari {filteredTotal} aktivitas</span><div className="flex items-center gap-2">{page > 1 ? <Link className="rounded-lg border border-slate-200 bg-white px-3 py-2 font-bold" href={`/logs?${query.toString()}&page=${page - 1}`}>Sebelumnya</Link> : null}<span className="font-semibold">{page} / {totalPages}</span>{page < totalPages ? <Link className="rounded-lg border border-slate-200 bg-white px-3 py-2 font-bold" href={`/logs?${query.toString()}&page=${page + 1}`}>Berikutnya</Link> : null}</div></div> : null}
    </div>
  );
}
