import Link from "next/link";
import Card from "@/components/ui/Card";
import Badge from "@/components/ui/Badge";
import PageHeader from "@/components/ui/PageHeader";
import IntegrationActions from "@/components/integrations/IntegrationActions";
import ControlCenterNav from "@/components/layout/ControlCenterNav";
import { shopRepository } from "@/lib/repositories/shopRepository";
import { getShopeeHost, getShopeePartnerId, getShopeeRedirectUri } from "@/lib/shopee/client";
import { firstSearchParam, resolveShopScope } from "@/lib/storeScope";
import { getCurrentUser } from "@/lib/currentUser";

export const dynamic = "force-dynamic";

function tokenStatus(expiresAt: Date | null) {
  if (!expiresAt) return { label: "Unknown", tone: "warning" as const };
  const expired = Date.now() > expiresAt.getTime();
  return expired ? { label: "Expired", tone: "danger" as const } : { label: "Valid", tone: "success" as const };
}

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

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

export default async function IntegrationsPage({ searchParams }: { searchParams: SearchParams }) {
  const current = await getCurrentUser();
  const shops = current ? await shopRepository.findManyForUser(current) : [];
  const params = await searchParams;
  const activeShopId = resolveShopScope(firstSearchParam(params.shop_id), shops);
  const selected = activeShopId ? shops.find((shop) => shop.shopId === activeShopId) ?? null : null;
  const token = selected ? tokenStatus(selected.tokenExpiredAt) : null;

  return (
    <div className="space-y-5">
      <PageHeader eyebrow="Toko & Sistem" title="Diagnostik koneksi" description="Periksa satu toko ketika sinkronisasi bermasalah. Pengelolaan harian tetap dilakukan di halaman Toko & koneksi." actions={<>
        <Link className="ui-button ui-button-secondary" href="/tokens">Kembali ke daftar toko</Link>
        <Link className="ui-button ui-button-primary" href={`/logs${activeShopId ? `?shop_id=${activeShopId}` : ""}`}>Lihat aktivitas</Link>
      </>} />

      <ControlCenterNav />

      <section className="scope-toolbar">
        <form className="flex flex-wrap items-end gap-3">
          <label className="min-w-64 flex-1">
            <span className="muted-label">Toko yang diperiksa</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={activeShopId || ""}>
              <option value="">Semua toko</option>
              {shops.map((shop) => <option key={shop.shopId} value={shop.shopId}>{shop.shopName || shop.shopId}</option>)}
            </select>
          </label>
          <button className="ui-button ui-button-primary" type="submit">Tampilkan</button>
        </form>
      </section>

      <div className="grid gap-5 xl:grid-cols-[1fr_360px]">
        <Card title="Hasil pemeriksaan" description="Status token dan akses API untuk toko yang dipilih.">
          <div className="grid gap-3 text-sm">
            <div className="flex items-center justify-between">
              <span className="text-slate-500">Status</span>
              {selected ? <Badge tone="success">Terhubung</Badge> : <Badge tone={shops.length ? "info" : "warning"}>{shops.length ? `${shops.length} toko` : "Belum terhubung"}</Badge>}
            </div>
            <div className="flex items-center justify-between">
              <span className="text-slate-500">Lingkungan</span>
              <Badge tone="info">Live / Production</Badge>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-slate-500">Toko</span>
              <span className="font-bold">{selected?.shopName || selected?.shopId || `${shops.length} toko terhubung`}</span>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-slate-500">Kesehatan token</span>
              {token ? <Badge tone={token.tone}>{token.label}</Badge> : <Badge tone="warning">-</Badge>}
            </div>
            <div className="flex items-center justify-between">
              <span className="text-slate-500">Expired</span>
              <span className="text-right">{formatDate(selected?.tokenExpiredAt || null)}</span>
            </div>
          </div>

          <IntegrationActions shopId={selected?.shopId || null} />

          <details className="mt-4 rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs">
            <summary className="cursor-pointer font-semibold text-slate-700">Detail teknis</summary>
            <div className="mt-3 grid gap-3 text-slate-500 sm:grid-cols-[140px_1fr]"><span>API host</span><span className="break-all font-mono font-bold text-slate-700">{getShopeeHost()}</span><span>Redirect URL</span><span className="break-all font-mono font-bold text-slate-700">{getShopeeRedirectUri()}</span><span>Partner ID</span><span className="font-mono font-bold text-slate-700">{getShopeePartnerId()}</span><span>Shop ID</span><span className="font-mono font-bold text-slate-700">{selected?.shopId || "Pilih toko terlebih dahulu"}</span></div>
          </details>
        </Card>

        <Card title="Cakupan integrasi" description="Data Shopee yang ditangani Sellfin.">
          <div className="space-y-2 text-sm">
            <ServiceStatus label="Pesanan & status" active={Boolean(selected || shops.length)} />
            <ServiceStatus label="Produk & SKU" active={Boolean(selected || shops.length)} />
            <ServiceStatus label="Logistik & resi" active={Boolean(selected || shops.length)} />
            <ServiceStatus label="Settlement finance" active={Boolean(selected || shops.length)} />
            <ServiceStatus label="Push notification" active={Boolean(selected || shops.length)} />
          </div>
          <div className="mt-4 rounded-lg bg-slate-50 p-3 text-xs leading-5 text-slate-500">Label “tersedia” berarti modul didukung. Keberhasilan request nyata dapat dilihat di halaman Aktivitas.</div>
        </Card>
      </div>
    </div>
  );
}

function ServiceStatus({ label, active }: { label: string; active: boolean }) {
  return <div className="flex items-center justify-between rounded-lg border border-slate-100 px-3 py-2.5"><span className="font-medium text-slate-600">{label}</span><Badge tone={active ? "success" : "warning"}>{active ? "Tersedia" : "Belum terhubung"}</Badge></div>;
}
