"use client";

import { useReducer, useEffect } from "react";
import {
  type WholesaleOrder,
  type WholesaleCustomer,
  type WholesaleProduct,
  type WholesaleSettings,
  type WholesaleDashboardStats,
  getWholesaleOrders,
  getWholesaleCustomers,
  getWholesaleProducts,
  getWholesaleSettings,
  getWholesaleDashboardStats,
  getRecentWebhookActivity,
} from "@/actions/wholesale";
import { getPendingWholesaleRegistrations } from "@/actions/wholesale-register";
import { getCurrentAdminUser } from "@/actions/admin-user";
import { type AdminUser } from "@/lib/admin-permissions";
import { PageHeader, AdminFilterTabs } from "@/components/admin/design-system";

import DashboardTab from "./DashboardTab";
import CustomersTab from "./CustomersTab";
import ProductsTab from "./ProductsTab";
import OrdersTab from "./OrdersTab";
import SettingsTab from "./SettingsTab";

type Tab = "dashboard" | "customers" | "products" | "orders" | "settings";

type WebhookActivity = Array<{
  id: string; event_type: string; order_id: string | null;
  status: string; attempts: number; created_at: string; response: string | null;
}>;

type Registration = {
  id: string; company_name: string | null; contact_name: string | null;
  email: string; phone: string | null; account_status: string; created_at: string;
};

type Msg = { kind: "success" | "error"; text: string };

type State = {
  tab: Tab;
  msg: Msg | null;
  adminUser: AdminUser | null;
  orders: WholesaleOrder[];
  customers: WholesaleCustomer[];
  products: WholesaleProduct[];
  settings: WholesaleSettings | null;
  stats: WholesaleDashboardStats | null;
  registrations: Registration[];
  loading: boolean;
  webhookActivity: WebhookActivity;
};

type Action =
  | { type: "set_tab"; tab: Tab }
  | { type: "set_msg"; msg: Msg | null }
  | { type: "set_admin_user"; adminUser: AdminUser | null }
  | { type: "set_orders"; orders: WholesaleOrder[] }
  | { type: "set_customers"; customers: WholesaleCustomer[] }
  | { type: "set_products"; products: WholesaleProduct[] }
  | { type: "set_settings"; settings: WholesaleSettings | null }
  | { type: "set_stats"; stats: WholesaleDashboardStats | null }
  | { type: "set_registrations"; registrations: Registration[] }
  | { type: "set_loading"; loading: boolean }
  | { type: "set_webhook_activity"; webhookActivity: WebhookActivity }
  | {
      type: "load_complete";
      payload: {
        adminUser: AdminUser | null;
        orders: WholesaleOrder[];
        customers: WholesaleCustomer[];
        products: WholesaleProduct[];
        settings: WholesaleSettings | null;
        stats: WholesaleDashboardStats | null;
        registrations: Registration[];
        webhookActivity: WebhookActivity;
      };
    };

const initialState: State = {
  tab: "dashboard",
  msg: null,
  adminUser: null,
  orders: [],
  customers: [],
  products: [],
  settings: null,
  stats: null,
  registrations: [],
  loading: true,
  webhookActivity: [],
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "set_tab":
      return { ...state, tab: action.tab };
    case "set_msg":
      return { ...state, msg: action.msg };
    case "set_admin_user":
      return { ...state, adminUser: action.adminUser };
    case "set_orders":
      return { ...state, orders: action.orders };
    case "set_customers":
      return { ...state, customers: action.customers };
    case "set_products":
      return { ...state, products: action.products };
    case "set_settings":
      return { ...state, settings: action.settings };
    case "set_stats":
      return { ...state, stats: action.stats };
    case "set_registrations":
      return { ...state, registrations: action.registrations };
    case "set_loading":
      return { ...state, loading: action.loading };
    case "set_webhook_activity":
      return { ...state, webhookActivity: action.webhookActivity };
    case "load_complete":
      return {
        ...state,
        adminUser: action.payload.adminUser,
        orders: action.payload.orders,
        customers: action.payload.customers,
        products: action.payload.products,
        settings: action.payload.settings,
        stats: action.payload.stats,
        registrations: action.payload.registrations,
        webhookActivity: action.payload.webhookActivity,
        loading: false,
      };
  }
}

// SVG Icon for Wholesale - defined at module level to prevent recreation on each render
function WholesaleIcon() {
  return (
    <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
    </svg>
  );
}

function WholesaleLoadingSkeleton() {
  return (
    <div className="space-y-6 px-6 py-6">
      {/* Header skeleton */}
      <div className="flex items-center gap-4">
        <div className="w-10 h-10 rounded-xl bg-slate-200 animate-pulse" />
        <div className="space-y-2">
          <div className="h-6 w-40 bg-slate-200 rounded animate-pulse" />
          <div className="h-4 w-64 bg-slate-100 rounded animate-pulse" />
        </div>
      </div>

      {/* Tab bar skeleton */}
      <div className="flex gap-2">
        {[1, 2, 3, 4, 5].map(i => (
          <div key={i} className={`h-10 rounded-xl bg-slate-200 animate-pulse ${i === 1 ? "w-24" : "w-20"}`} />
        ))}
      </div>

      {/* Stat cards skeleton */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
        {[1, 2, 3, 4, 5, 6].map(i => (
          <div key={i} className="rounded-xl border border-slate-200 bg-white p-4 animate-pulse">
            <div className="h-3 w-20 bg-slate-100 rounded mb-2" />
            <div className="h-7 w-16 bg-slate-200 rounded" />
          </div>
        ))}
      </div>

      {/* Recent orders skeleton */}
      <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="h-5 w-28 bg-slate-200 rounded mb-4 animate-pulse" />
        <div className="space-y-3">
          {[1, 2, 3, 4].map(i => (
            <div key={i} className="flex items-center gap-4 py-3 border-b border-slate-100 last:border-0 animate-pulse">
              <div className="h-4 w-20 bg-slate-100 rounded" />
              <div className="h-4 w-32 bg-slate-100 rounded flex-1" />
              <div className="h-4 w-24 bg-slate-100 rounded hidden md:block" />
              <div className="h-5 w-12 bg-slate-100 rounded" />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

export default function WholesaleClient({ brandId }: { brandId: string }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  useEffect(() => {
    async function load() {
      const [au, o, c, p, s, st, r, wa] = await Promise.all([
        getCurrentAdminUser(),
        getWholesaleOrders(brandId),
        getWholesaleCustomers(brandId),
        getWholesaleProducts(brandId),
        getWholesaleSettings(brandId),
        getWholesaleDashboardStats(brandId),
        getPendingWholesaleRegistrations(brandId),
        getRecentWebhookActivity(brandId, 5),
      ]);
      dispatch({
        type: "load_complete",
        payload: {
          adminUser: au,
          orders: o,
          customers: c,
          products: p,
          settings: s,
          stats: st,
          registrations: r as Registration[],
          webhookActivity: wa as WebhookActivity,
        },
      });
    }
    load();
  }, [brandId]);

  function showMsg(kind: "success" | "error", text: string) {
    dispatch({ type: "set_msg", msg: { kind, text } });
    setTimeout(() => dispatch({ type: "set_msg", msg: null }), 4000);
  }

  if (state.loading) {
    return (
      <div className="min-h-screen bg-[var(--admin-bg)]">
        <WholesaleLoadingSkeleton />
      </div>
    );
  }

  const tabs = [
    { value: "dashboard", label: "Dashboard", count: undefined },
    { value: "customers", label: "Customers", count: state.customers.filter(c => c.account_status !== "pending_approval" && c.account_status !== "rejected").length },
    { value: "products", label: "Products", count: state.products.length },
    { value: "orders", label: "Orders", count: state.orders.length },
    { value: "settings", label: "Settings" },
  ];

  return (
    <div className="min-h-screen bg-[var(--admin-bg)]">
      <PageHeader
        icon={<WholesaleIcon />}
        title="Wholesale Portal"
        subtitle="Manage wholesale orders, customers, and products"
        className="mb-0"
      />

      {/* Tab nav */}
      <div className="px-6 pb-0">
        <AdminFilterTabs
          activeTab={state.tab}
          onTabChange={(value) => dispatch({ type: "set_tab", tab: value as Tab })}
          tabs={tabs}
          size="md"
        />
      </div>

      <div className="px-6 py-6">
        {state.msg && (
          <div className={`mb-4 rounded-xl border px-4 py-3 text-sm ${
            state.msg.kind === "success"
              ? "border-emerald-200 bg-emerald-50 text-emerald-700"
              : "border-red-200 bg-red-50 text-red-700"
          }`}>
            {state.msg.text}
          </div>
        )}

        {state.tab === "dashboard" && (
          <DashboardTab
            stats={state.stats!}
            recentOrders={state.orders.slice(0, 10)}
            brandId={brandId}
            onMsg={showMsg}
            webhookActivity={state.webhookActivity}
          />
        )}
        {state.tab === "customers" && (
          <CustomersTab
            customers={state.customers}
            products={state.products}
            brandId={brandId}
            onMsg={showMsg}
            registrations={state.registrations}
            onRefresh={async () => {
              const r = await getPendingWholesaleRegistrations(brandId);
              dispatch({ type: "set_registrations", registrations: r as Registration[] });
            }}
          />
        )}
        {state.tab === "products" && (
          <ProductsTab
            products={state.products}
            brandId={brandId}
            onMsg={showMsg}
            onRefresh={async () => {
              const p = await getWholesaleProducts(brandId);
              dispatch({ type: "set_products", products: p });
            }}
          />
        )}
        {state.tab === "orders" && (
          <OrdersTab
            orders={state.orders}
            customers={state.customers}
            brandId={brandId}
            onMsg={showMsg}
            onRefresh={async () => {
              const o = await getWholesaleOrders(brandId);
              dispatch({ type: "set_orders", orders: o });
            }}
          />
        )}
        {state.tab === "settings" && (
          <SettingsTab
            settings={state.settings}
            brandId={brandId}
            onMsg={showMsg}
            onRefresh={async () => {
              const s = await getWholesaleSettings(brandId);
              dispatch({ type: "set_settings", settings: s });
            }}
            canManageSettings={state.adminUser?.can_manage_settings ?? false}
          />
        )}
      </div>
    </div>
  );
}
