"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { ALL_STORES_VALUE } from "@/lib/storeScope";
import { useTheme } from "./ThemeProvider";
import { useCurrentUser } from "./CurrentUserContext";

type StatusPayload = {
  connected: boolean;
  shopCount: number;
  tokenStatus: string;
  tokenLabel: string;
  attentionCount: number;
  failedToday: number;
};

type ShopOption = { shopId: string; shopName: string | null; connected: boolean };

const pageTitles: Record<string, string> = {
  "/dashboard": "Ringkasan", "/orders": "Pesanan", "/products": "Produk", "/stock": "Stok",
  "/tokens": "Toko & Sistem", "/integrations": "Toko & Sistem", "/finance": "Profit", "/reports": "Laporan",
  "/logs": "Aktivitas Sistem", "/admin": "Super Admin", "/settings": "Pengaturan & AI", "/users": "Manajemen Pengguna",
};

export default function Topbar({ onMenu }: { onMenu: () => void }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const { theme, toggle } = useTheme();
  const currentUser = useCurrentUser();
  const selectedShopId = searchParams.get("shop_id") || ALL_STORES_VALUE;
  const adminMode = currentUser?.role === "super_admin" && (pathname === "/admin" || pathname === "/users" || (selectedShopId === ALL_STORES_VALUE && ["/tokens", "/logs", "/settings"].includes(pathname)));
  const [status, setStatus] = useState<StatusPayload | null>(null);
  const [shops, setShops] = useState<ShopOption[]>([]);

  useEffect(() => {
    if (adminMode) return;
    let cancelled = false;
    Promise.all([
      fetch(`/api/shopee/status?shop_id=${encodeURIComponent(selectedShopId)}`).then((res) => res.json()),
      fetch("/api/shopee/shops").then((res) => res.json()),
    ]).then(([statusJson, shopsJson]) => {
      if (cancelled) return;
      if (statusJson?.ok) setStatus(statusJson.data);
      if (Array.isArray(shopsJson)) setShops(shopsJson.map((shop) => ({ shopId: shop.shop_id, shopName: shop.shop_name, connected: Boolean(shop.connected) })));
    }).catch(() => undefined);
    return () => { cancelled = true; };
  }, [adminMode, selectedShopId]);

  async function logout() {
    await fetch("/api/logout", { method: "POST" }).catch(() => undefined);
    window.location.href = "/login";
  }

  const tokenBad = status?.tokenStatus === "expired" || status?.tokenStatus === "reconnect_required";
  const selectedLabel = selectedShopId === ALL_STORES_VALUE ? "Semua Toko" : shops.find((shop) => shop.shopId === selectedShopId)?.shopName || selectedShopId;
  const pageTitle = pageTitles[pathname] || "Workspace";
  const subtitle = adminMode ? "Kelola Owner, akses toko, dan pengaturan sistem" : `${selectedLabel} • ${status ? status.connected ? "Data Shopee aktif" : "Belum terhubung" : "Memeriksa koneksi"}`;
  const selectedShopKnown = selectedShopId === ALL_STORES_VALUE || shops.some((shop) => shop.shopId === selectedShopId);

  return (
    <header className="sticky top-0 z-40 border-b border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-950">
      <div className="flex min-h-16 items-center gap-3 px-4 sm:px-6 xl:px-8">
        <button aria-label="Buka menu" className="grid h-9 w-9 shrink-0 place-items-center rounded-[10px] border border-slate-200 text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-900 lg:hidden" onClick={onMenu} type="button">
          <svg aria-hidden="true" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path d="M4 7h16M4 12h16M4 17h16" /></svg>
        </button>
        <div className="min-w-0 flex-1">
          <div className="truncate text-[15px] font-bold tracking-tight text-slate-950 dark:text-white">{pageTitle}</div>
          <div className="mt-0.5 hidden truncate text-[11px] text-slate-500 sm:block">{subtitle}</div>
        </div>
        {!adminMode && status?.attentionCount ? (
          <Link className="hidden rounded-full border border-rose-200 bg-rose-50 px-3 py-1.5 text-[11px] font-bold text-rose-700 hover:bg-rose-100 dark:border-rose-900 dark:bg-rose-950/40 dark:text-rose-300 sm:block" href={`/orders?shop_id=${encodeURIComponent(selectedShopId)}&status=failed_today`}>
            {status.failedToday} perlu perhatian
          </Link>
        ) : null}
        {!adminMode && status?.connected ? <span className="hidden items-center gap-2 rounded-full border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-[11px] font-bold text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-300 xl:flex"><span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />Shopee tersambung</span> : null}
        {!adminMode ? <label className="flex min-w-0 items-center gap-2 rounded-xl border border-slate-200 bg-white px-2.5 py-2 shadow-sm dark:border-slate-700 dark:bg-slate-900">
          <svg aria-hidden="true" className="hidden h-4 w-4 shrink-0 text-slate-400 sm:block" fill="none" stroke="currentColor" strokeWidth="1.8" viewBox="0 0 24 24"><path d="M3 10h18M5 10v11h14V10M5 10l1-6h12l1 6M9 21v-6h6v6" /></svg>
          <select aria-label="Pilih toko aktif" className="max-w-[105px] bg-transparent text-xs font-bold text-slate-800 outline-none dark:text-slate-100 sm:max-w-[170px] sm:text-[13px]"
            value={selectedShopId}
            onChange={(event) => { const next = new URL(window.location.href); next.searchParams.set("shop_id", event.target.value); next.searchParams.delete("page"); window.location.href = next.toString(); }}>
            <option value={ALL_STORES_VALUE}>Semua Toko</option>
            {!selectedShopKnown ? <option value={selectedShopId}>{selectedShopId}</option> : null}
            {shops.map((shop) => <option key={shop.shopId} value={shop.shopId}>{shop.shopName || shop.shopId}{shop.connected ? "" : " · disconnected"}</option>)}
          </select>
        </label> : <span className="hidden rounded-full border border-violet-200 bg-violet-50 px-3 py-1.5 text-xs font-bold text-violet-800 sm:inline-flex">Mode Super Admin</span>}
        {!adminMode ? <span className={["hidden h-2 w-2 rounded-full lg:block", status?.connected ? tokenBad ? "bg-amber-500" : "bg-emerald-500" : "bg-slate-300"].join(" ")} title={status?.tokenLabel || "Memeriksa koneksi"} /> : null}
        {!adminMode && status && !status.connected ? <a className="hidden rounded-[10px] bg-emerald-500 px-3 py-2 text-xs font-black text-slate-950 hover:bg-emerald-400 md:inline-flex" href="/api/shopee/auth-url?go=1">Hubungkan toko</a> : null}
        <button aria-label={theme === "dark" ? "Gunakan tema terang" : "Gunakan tema gelap"} className="grid h-9 w-9 shrink-0 place-items-center rounded-[10px] border border-slate-200 text-slate-500 hover:bg-slate-50 hover:text-slate-950 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-900" onClick={toggle} type="button">{theme === "dark" ? "☀" : "☾"}</button>
        <button aria-label="Keluar" className="grid h-9 w-9 shrink-0 place-items-center rounded-[10px] border border-slate-200 text-slate-500 hover:border-rose-200 hover:bg-rose-50 hover:text-rose-700 dark:border-slate-700 dark:text-slate-300" onClick={logout} type="button">
          <svg aria-hidden="true" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="1.8" viewBox="0 0 24 24"><path d="M10 5H5v14h5M14 8l4 4-4 4M8 12h10" /></svg>
        </button>
      </div>
    </header>
  );
}
