"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Badge from "@/components/ui/Badge";
import Button from "@/components/ui/Button";
import Card from "@/components/ui/Card";
import ActionMenu from "@/components/ui/ActionMenu";
import PageHeader from "@/components/ui/PageHeader";
import ControlCenterNav from "@/components/layout/ControlCenterNav";

type Shop = {
  shopId: string;
  shopName: string | null;
  status: string;
  connectedAt: string;
  tokenExpiredAt: string | null;
  refreshTokenExpiredAt: string;
  lastRefreshAt: string;
  tokenHealth: {
    status: string;
    label: string;
    message: string;
  };
  orders: number;
  revenue: number;
};

type HistoricalShop = Pick<Shop, "shopId" | "shopName" | "orders" | "revenue">;

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

function tokenTone(status: string) {
  if (status === "valid") return "success" as const;
  if (status === "expired" || status === "reconnect_required") return "danger" as const;
  return "warning" as const;
}

function money(value: number) {
  return `IDR ${value.toLocaleString("id-ID")}`;
}

export default function TokensPageClient({ shops, historicalShops }: { shops: Shop[]; historicalShops: HistoricalShop[] }) {
  const router = useRouter();
  const [loadingShopId, setLoadingShopId] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [dangerShopId, setDangerShopId] = useState<string | null>(null);
  const [purgeShopId, setPurgeShopId] = useState<string | null>(null);
  const reconnectRequired = shops.filter((shop) => shop.tokenHealth.status === "reconnect_required");

  async function refreshToken(shopId: string) {
    setLoadingShopId(shopId);
    setMessage(null);
    try {
      const res = await fetch("/api/shopee/token/refresh", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ shopId }),
      });
      const json = (await res.json()) as { ok: boolean; error?: string; data?: { tokenExpiredAt?: string | null } };
      if (!res.ok || !json.ok) throw new Error(json.error || "Gagal refresh token.");
      setMessage(`Token berhasil direfresh. Expired: ${formatDate(json.data?.tokenExpiredAt ?? null)}`);
      router.refresh();
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "Gagal refresh token.");
    } finally {
      setLoadingShopId(null);
    }
  }

  async function testConnection(shopId: string) {
    setLoadingShopId(shopId);
    setMessage(null);
    try {
      const res = await fetch("/api/shopee/test-connection", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ shopId }),
      });
      const json = (await res.json()) as { ok: boolean; error?: string; data?: { shopName?: string | null; status?: string | null } };
      if (!res.ok || !json.ok) throw new Error(json.error || "Gagal test koneksi.");
      setMessage(`Koneksi Shopee OK${json.data?.shopName ? `: ${json.data.shopName}` : ""}.`);
      router.refresh();
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "Gagal test koneksi.");
    } finally {
      setLoadingShopId(null);
    }
  }

  async function syncNow(shopId: string) {
    setLoadingShopId(shopId);
    setMessage(null);
    try {
      const res = await fetch("/api/shopee/dashboard/auto-sync", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ shopId, mode: "quick" }),
      });
      const json = (await res.json()) as { ok: boolean; error?: string; message?: string; data?: { message?: string } };
      if (!res.ok || !json.ok) throw new Error(json.error || json.message || "Sinkronisasi gagal.");
      setMessage(json.data?.message || "Sinkronisasi toko dimulai. Data terbaru akan segera tersedia.");
      router.refresh();
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "Sinkronisasi gagal.");
    } finally {
      setLoadingShopId(null);
    }
  }

  async function disconnect(shopId: string) {
    if (dangerShopId !== shopId) {
      setDangerShopId(shopId);
      setMessage("Klik Hapus toko sekali lagi. Toko akan diputus lalu dipindahkan ke bagian Historis, tempat tombol Hapus permanen tersedia.");
      return;
    }
    setLoadingShopId(shopId);
    try {
      const res = await fetch("/api/shopee/disconnect", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ shopId }),
      });
      const json = await res.json();
      if (!res.ok || !json.ok) throw new Error(json.error || "Gagal disconnect token lokal.");
      setMessage(`Toko ${shopId} dipindahkan ke Historis. Gunakan Hapus permanen di bagian Historis untuk menghapus seluruh datanya.`);
      router.refresh();
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "Gagal disconnect token lokal.");
    } finally {
      setLoadingShopId(null);
    }
  }

  async function purgeHistoricalShop(shopId: string) {
    if (purgeShopId !== shopId) {
      setPurgeShopId(shopId);
      setMessage(`Klik Hapus permanen sekali lagi untuk menghapus seluruh data lokal Shop ID ${shopId}.`);
      return;
    }
    setLoadingShopId(shopId);
    setMessage(null);
    try {
      const res = await fetch("/api/shopee/purge-shop", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ shopId, confirmation: shopId }),
      });
      const json = (await res.json()) as { ok?: boolean; error?: string; data?: { deletedOrders?: number } };
      if (!res.ok || !json.ok) throw new Error(json.error || "Gagal menghapus toko historis.");
      setMessage(`Toko historis ${shopId} dan ${json.data?.deletedOrders || 0} order lokal berhasil dihapus.`);
      setPurgeShopId(null);
      router.refresh();
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "Gagal menghapus toko historis.");
    } finally {
      setLoadingShopId(null);
    }
  }

  return (
    <div className="space-y-5">
      <PageHeader eyebrow="Toko & Sistem" title="Toko & koneksi" description="Satu tempat untuk melihat toko Shopee, kondisi token, aktivitas data, dan tindakan koneksi." actions={<>
        <a className="ui-button ui-button-secondary" href="/integrations">Diagnostik API</a>
        <a className="ui-button ui-button-primary" href="/api/shopee/auth-url?go=1">Hubungkan toko</a>
      </>} />

      <ControlCenterNav />

      {message ? <div className="rounded-xl border border-slate-200 bg-white p-3 text-sm font-semibold text-slate-700 shadow-sm">{message}</div> : null}
      {reconnectRequired.length ? <div role="status" className="rounded-xl border border-rose-200 bg-rose-50 p-4 text-sm text-rose-950 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-200"><div className="font-bold">{reconnectRequired.length} toko perlu dihubungkan ulang</div><p className="mt-1 text-xs leading-5">Refresh token Shopee hanya berlaku 30 hari dan sudah kedaluwarsa. Data lama tetap aman. Gunakan tombol Hubungkan ulang pada tiap toko; setelah OAuth berhasil, sinkronkan pesanan kembali.</p></div> : null}

      <section className="system-health">
        <div className="system-health-copy">
          <span className={`system-health-dot ${shops.some((shop) => shop.tokenHealth.status !== "valid") ? "is-warning" : "is-good"}`} />
          <div><div className="text-sm font-bold text-slate-950">{shops.length ? `${shops.length} toko terhubung` : "Belum ada toko terhubung"}</div><div className="mt-1 text-xs text-slate-500">{shops.every((shop) => shop.tokenHealth.status === "valid") ? "Seluruh koneksi siap menerima sinkronisasi." : "Ada token yang perlu diperiksa sebelum sinkronisasi."}</div></div>
        </div>
        <div className="system-health-stats">
          <ConnectionStat label="Sehat" value={shops.filter((shop) => shop.tokenHealth.status === "valid").length} />
          <ConnectionStat label="Perlu perhatian" value={shops.filter((shop) => shop.tokenHealth.status !== "valid").length} warning />
          <ConnectionStat label="Historis" value={historicalShops.length} />
        </div>
      </section>

      <Card title="Daftar toko" description="Sinkronkan data harian dari sini. Gunakan menu Kelola hanya untuk perawatan koneksi.">
        {shops.length === 0 ? (
          <div className="rounded-xl border border-dashed border-slate-200 p-8 text-center">
            <div className="text-lg font-bold text-slate-950">Belum ada toko terhubung</div>
            <p className="mt-2 text-sm text-slate-500">Hubungkan akun Shopee Live untuk mulai menarik pesanan dan produk.</p>
            <a className="ui-button ui-button-primary mt-4" href="/api/shopee/auth-url?go=1">Hubungkan toko</a>
          </div>
        ) : (
          <div className="store-list">
            <div className="store-list-header" aria-hidden="true"><span>Toko</span><span>Koneksi</span><span>Aktivitas</span><span>Tindakan</span></div>
            {shops.map((shop) => (
              <div key={shop.shopId} className="store-row">
                <div className="store-identity">
                  <span className="store-avatar">S</span>
                  <div className="min-w-0">
                  <div className="flex flex-wrap items-center gap-2">
                      <div className="truncate text-sm font-bold text-slate-950">{shop.shopName || shop.shopId}</div>
                      <Badge tone={shop.status === "active" ? "success" : "neutral"}>{shop.status === "active" ? "Aktif" : shop.status}</Badge>
                    </div>
                    <div className="mt-1 font-mono text-[11px] text-slate-400">Shop ID {shop.shopId}</div>
                    <a className="mt-2 inline-flex text-xs font-semibold text-emerald-700 hover:text-emerald-800" href={`/orders?shop_id=${encodeURIComponent(shop.shopId)}`}>Buka pesanan →</a>
                  </div>
                </div>
                <div className="store-connection">
                  <Badge tone={tokenTone(shop.tokenHealth.status)}>{shop.tokenHealth.label}</Badge>
                  <div className="mt-2 text-xs text-slate-500">Token: <span className="font-medium text-slate-700">{formatDate(shop.tokenExpiredAt)}</span></div>
                  <div className="mt-1 text-[11px] leading-5 text-slate-400">{shop.tokenHealth.message}</div>
                </div>
                <div className="store-activity">
                  <div><strong>{shop.orders.toLocaleString("id-ID")}</strong><span> order tersimpan</span></div>
                  <div className="mt-1"><strong>{money(shop.revenue)}</strong><span> GMV</span></div>
                  <div className="mt-2 text-[11px] text-slate-400">Refresh terakhir {formatDate(shop.lastRefreshAt)}</div>
                </div>
                <div className="store-actions">
                  {shop.tokenHealth.status === "reconnect_required" ? <a className="ui-button ui-button-primary" href="/api/shopee/auth-url?go=1">Hubungkan ulang</a> : <Button variant="primary" loading={loadingShopId === shop.shopId} onClick={() => syncNow(shop.shopId)}>Sinkronkan</Button>}
                  <ActionMenu label="Kelola" items={[
                    { label: "Uji koneksi API", description: shop.tokenHealth.status === "reconnect_required" ? "Hubungkan ulang toko terlebih dahulu" : "Periksa akses toko ke Shopee", disabled: shop.tokenHealth.status === "reconnect_required", onClick: () => testConnection(shop.shopId) },
                    { label: "Refresh token", description: shop.tokenHealth.status === "reconnect_required" ? "Refresh token lewat masa berlaku; OAuth diperlukan" : "Perbarui masa aktif akses", disabled: shop.tokenHealth.status === "reconnect_required", onClick: () => refreshToken(shop.shopId) },
                    { label: "Disconnect toko", description: "Putuskan koneksi, data historis tetap disimpan", danger: true, onClick: () => disconnect(shop.shopId) },
                  ]} />
                  <Button variant="danger" loading={loadingShopId === shop.shopId} onClick={() => disconnect(shop.shopId)}>{dangerShopId === shop.shopId ? "Konfirmasi hapus toko" : "Hapus toko"}</Button>
                  <details className="store-details">
                    <summary>Detail token</summary>
                    <div>Terhubung {formatDate(shop.connectedAt)}</div>
                    <div>Refresh token {formatDate(shop.refreshTokenExpiredAt)}</div>
                  </details>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      {historicalShops.length > 0 ? (
        <Card title="Toko tidak terhubung" description="Riwayat lokal tetap tersimpan. Hubungkan kembali hanya jika toko masih digunakan.">
          <div className="grid gap-3">
            {historicalShops.map((shop) => (
              <div className="flex flex-wrap items-center justify-between gap-4 rounded-xl border border-amber-200 bg-amber-50 p-4" key={shop.shopId}>
                <div>
                  <div className="flex flex-wrap items-center gap-2">
                    <div className="font-bold text-slate-950">{shop.shopName || shop.shopId}</div>
                    <Badge tone="warning">Tidak terhubung</Badge>
                  </div>
                  <div className="mt-2 text-sm text-slate-600">{shop.orders} order · GMV terdata {money(shop.revenue)} · Shop ID {shop.shopId}</div>
                  <div className="mt-1 text-xs text-slate-500">Data lama tetap tersedia dan terisolasi. Reconnect diperlukan untuk sinkronisasi baru.</div>
                </div>
                <div className="flex gap-2">
                  <a className="ui-button ui-button-secondary" href={`/orders?shop_id=${encodeURIComponent(shop.shopId)}`}>Lihat data</a>
                  <a className="ui-button ui-button-primary" href="/api/shopee/auth-url?go=1">Hubungkan lagi</a>
                  <Button variant="danger" loading={loadingShopId === shop.shopId} onClick={() => purgeHistoricalShop(shop.shopId)}>{purgeShopId === shop.shopId ? "Konfirmasi hapus" : "Hapus permanen"}</Button>
                </div>
              </div>
            ))}
          </div>
        </Card>
      ) : null}
    </div>
  );
}

function ConnectionStat({ label, value, warning = false }: { label: string; value: number; warning?: boolean }) {
  return <div><strong className={warning && value ? "text-amber-700" : "text-slate-950"}>{value}</strong><span>{label}</span></div>;
}
