"use client";

import { useState, useTransition } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import Badge from "@/components/ui/Badge";
import EmptyState from "@/components/ui/EmptyState";
import OrdersTable from "./OrdersTable";
import OrderDetailDrawer from "./OrderDetailDrawer";
import OrderStatusTabs, { type OrderTabValue } from "./OrderStatusTabs";
import OrderFilters from "./OrderFilters";
import type { Order, OrderItem, OrderStatusCounts } from "./types";

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

type Initial = {
  shops: ShopRow[];
  activeShopId: string | null;
  status: string | null;
  sort: "update_time" | "create_time";
  q: string | null;
  dateFrom: string | null;
  dateTo: string | null;
  page: number;
  pageSize: number;
  renderedAt: string;
  total: number;
  statusCounts: OrderStatusCounts;
  orders: Order[];
  itemsByOrderSn: Record<string, OrderItem[]>;
};

type Toast = { tone: "success" | "danger" | "info"; message: string } | null;

function secondaryQueues(status: string | null): Array<{ label: string; value: OrderTabValue }> {
  if (["print_queue", "waiting_tracking", "need_print", "printed_waiting_dispatch"].includes(status || "")) return [];
  if (status === "incoming") return [
    { label: "Akan diatur", value: "incoming" },
    { label: "Sudah diproses", value: "waiting_tracking" },
    { label: "Gagal diproses", value: "delivery_problem_today" },
  ];
  if (status === "SHIPPED" || status === "TO_CONFIRM_RECEIVE") return [
    { label: "Semua dikirim", value: "SHIPPED" },
    { label: "Menunggu konfirmasi pembeli", value: "TO_CONFIRM_RECEIVE" },
  ];
  if (["problem", "payment_problem", "delivery_problem", "cancelled_returned"].includes(status || "")) return [
    { label: "Semua perlu ditinjau", value: "problem" },
    { label: "Pembayaran", value: "payment_problem" },
    { label: "Logistik", value: "delivery_problem" },
    { label: "Batal & retur", value: "cancelled_returned" },
  ];
  return [];
}

export default function OrdersPageClient({ initial }: { initial: Initial }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [toast, setToast] = useState<Toast>(null);
  const [selectedOrderSn, setSelectedOrderSn] = useState<string | null>(null);
  const [selectedShopId, setSelectedShopId] = useState<string | null>(null);
  const [syncing, setSyncing] = useState(false);
  const [refreshing, startRefresh] = useTransition();

  const pageCount = Math.max(Math.ceil(initial.total / initial.pageSize), 1);
  const subQueues = secondaryQueues(initial.status);

  function refreshOrders() {
    startRefresh(() => router.refresh());
  }

  function queryHref(next: Record<string, string | number | null | undefined>) {
    const params = new URLSearchParams(searchParams.toString());
    for (const [key, value] of Object.entries(next)) {
      if (value === null || value === undefined || value === "") params.delete(key);
      else params.set(key, String(value));
    }
    const shouldResetPage = ["status", "q", "shop_id", "date_from", "date_to", "sort", "page_size"].some((key) =>
      Object.prototype.hasOwnProperty.call(next, key)
    );
    if (shouldResetPage) params.delete("page");
    const suffix = params.toString();
    return suffix ? `/orders?${suffix}` : "/orders";
  }

  function updateQuery(next: Record<string, string | number | null | undefined>) {
    router.push(queryHref(next));
  }

  function hrefForStatus(status: OrderTabValue) {
    return queryHref({ status });
  }

  async function syncOrders() {
    const targets = initial.activeShopId
      ? initial.shops.filter((shop) => shop.shopId === initial.activeShopId && shop.connected)
      : initial.shops.filter((shop) => shop.connected);
    if (targets.length === 0) {
      setToast({ tone: "danger", message: "Tidak ada toko aktif yang bisa disinkronkan." });
      return;
    }
    setSyncing(true);
    setToast({ tone: "info", message: `Sinkronisasi ${targets.length} toko sedang berjalan...` });
    try {
      const res = await fetch("/api/shopee/dashboard/auto-sync", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ mode: "orders", ...(initial.activeShopId ? { shopId: initial.activeShopId } : {}) }),
      });
      const json = (await res.json()) as { ok?: boolean; success?: boolean; error?: string; data?: { orders?: { uniqueOrderSns?: number } } };
      if (!res.ok || !json.ok || !json.success) throw new Error(json.error || "Sinkronisasi pesanan belum lengkap. Periksa Aktivitas Sistem lalu ulangi.");
      setToast({ tone: "success", message: `${targets.length} toko selesai diperiksa. ${json.data?.orders?.uniqueOrderSns || 0} order unik dibaca dari Shopee.` });
      router.refresh();
    } catch (error) {
      setToast({ tone: "danger", message: error instanceof Error ? error.message : "Sinkronisasi pesanan gagal." });
    } finally {
      setSyncing(false);
    }
  }

  return (
    <div className="space-y-5">
      {toast ? (
        <div className="sticky top-[76px] z-40 rounded-xl border border-slate-200 bg-white p-3 shadow-lg">
          <Badge tone={toast.tone === "danger" ? "danger" : toast.tone === "success" ? "success" : "info"}>
            {toast.tone === "danger" ? "Error" : toast.tone === "success" ? "Sukses" : "Info"}
          </Badge>
          <span className="ml-2 text-sm text-slate-700">{toast.message}</span>
          <button className="float-right text-sm font-semibold text-slate-500 hover:text-slate-950" onClick={() => setToast(null)}>
            Tutup
          </button>
        </div>
      ) : null}

      <section className="order-navigation overflow-hidden rounded-[14px] border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-900">
        <div className="flex flex-wrap items-center justify-between gap-3 p-3.5">
          <OrderStatusTabs
            value={(initial.status as OrderTabValue) || "incoming"}
            hrefFor={hrefForStatus}
            counts={initial.statusCounts}
          />

        </div>

        {subQueues.length ? (
          <div className="flex flex-wrap items-center gap-5 border-t border-slate-100 bg-slate-50/60 px-4 py-2.5 text-[12px] dark:border-slate-800 dark:bg-slate-950/30">
            {subQueues.map((queue) => (
              <Link className={`border-b-2 py-1 font-bold ${initial.status === queue.value ? "border-emerald-600 text-emerald-700" : "border-transparent text-slate-500 hover:text-slate-900 dark:text-slate-400"}`} href={hrefForStatus(queue.value)} key={queue.value}>
                {queue.label}
              </Link>
            ))}
          </div>
        ) : null}

        <div>
          <OrderFilters
            shops={initial.shops}
            activeShopId={initial.activeShopId}
            defaultValue={initial.q || ""}
            defaultDateFrom={initial.dateFrom || ""}
            defaultDateTo={initial.dateTo || ""}
          />
        </div>
      </section>

      {initial.orders.length === 0 ? (
        <EmptyState
          title={initial.shops.length === 0 ? "Shopee belum terhubung." : "Belum ada pesanan."}
          description={
            initial.shops.length === 0
              ? "Hubungkan Shopee dulu dari halaman Toko Shopee."
              : "Data diperbarui otomatis dari Shopee saat aplikasi terbuka atau saat push order masuk."
          }
          action={initial.shops.length === 0 ? { label: "Buka Toko Shopee", href: "/tokens" } : undefined}
        />
      ) : (
        <OrdersTable
          orders={initial.orders}
          itemsByOrderSn={initial.itemsByOrderSn}
          shopNames={Object.fromEntries(initial.shops.map((shop) => [shop.shopId, shop.shopName || shop.shopId]))}
          renderedAt={initial.renderedAt}
          sort={initial.sort}
          onSortChange={(value) => updateQuery({ sort: value })}
          onOpenDetail={(orderSn, shopId) => {
            setSelectedOrderSn(orderSn);
            setSelectedShopId(shopId);
          }}
          onToast={setToast}
          onRefresh={refreshOrders}
          onSync={syncOrders}
          syncing={syncing}
          refreshing={refreshing}
        />
      )}

      <div className="flex flex-wrap items-center justify-between gap-3 text-sm text-slate-500">
        <span>
          Menampilkan <b className="text-slate-950">{initial.orders.length}</b> dari{" "}
          <b className="text-slate-950">{initial.total}</b> order
        </span>
        <div className="flex items-center gap-2">
          {initial.page <= 1 ? <span className="ui-button ui-button-secondary cursor-not-allowed opacity-50">Sebelumnya</span> : <Link className="ui-button ui-button-secondary" href={queryHref({ page: initial.page - 1 })}>Sebelumnya</Link>}
          <span className="font-semibold text-slate-700">Halaman {initial.page} / {pageCount}</span>
          {initial.page >= pageCount ? <span className="ui-button ui-button-secondary cursor-not-allowed opacity-50">Berikutnya</span> : <Link className="ui-button ui-button-secondary" href={queryHref({ page: initial.page + 1 })}>Berikutnya</Link>}
          <select
            className="rounded-lg border border-slate-200 bg-white px-2 py-2 text-sm font-semibold text-slate-700"
            value={initial.pageSize}
            onChange={(event) => updateQuery({ page_size: event.target.value, page: 1 })}
          >
            <option value="10">10/hal</option>
            <option value="25">25/hal</option>
            <option value="50">50/hal</option>
          </select>
        </div>
      </div>

      <OrderDetailDrawer
        open={Boolean(selectedOrderSn)}
        orderSn={selectedOrderSn}
        shopId={selectedShopId}
        onClose={() => setSelectedOrderSn(null)}
        onToast={setToast}
        onRefresh={refreshOrders}
      />
    </div>
  );
}
