"use client";

import { useReducer, useEffect } from "react";
import {
  type WholesaleCustomer,
  type WholesaleProduct,
  deleteWholesaleCustomer,
  saveWholesaleCustomer,
} from "@/actions/wholesale";
import { approveWholesaleRegistration } from "@/actions/wholesale-register";
import { formatDate } from "@/lib/format-date";
import { AdminButton, AdminBadge } from "@/components/admin/design-system";

import CustomerFormSection from "./CustomerForm";
import {
  type CustomerForm,
  EMPTY_CUSTOMER_FORM,
  customerFormFromCustomer,
} from "./customerFormState";
import CustomerListSection from "./CustomerList";
import CustomerPricingPanel from "./CustomerPricingPanel";
import PriceSheetModal from "./PriceSheetModal";

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

const EMPTY_REGISTRATIONS: Registration[] = [];

type State = {
  showForm: boolean;
  editing: WholesaleCustomer | null;
  subTab: "customers" | "registrations";
  form: CustomerForm;
  saving: boolean;
  processingReg: string | null;
  pricingCustomer: WholesaleCustomer | null;
  selectedCustomers: Set<string>;
  sendingPriceSheet: boolean;
  priceSheetTarget: { customerIds: string[]; defaultSubject: string } | null;
  openCustomerActions: string | null;
  deletingCustomer: string | null;
};

type Action =
  | { type: "set_show_form"; showForm: boolean }
  | { type: "set_sub_tab"; subTab: "customers" | "registrations" }
  | { type: "set_form_field"; field: keyof CustomerForm; value: CustomerForm[keyof CustomerForm] }
  | { type: "open_new" }
  | { type: "open_edit"; customer: WholesaleCustomer }
  | { type: "set_saving"; saving: boolean }
  | { type: "set_processing_reg"; processingReg: string | null }
  | { type: "set_pricing_customer"; pricingCustomer: WholesaleCustomer | null }
  | { type: "toggle_selected"; id: string }
  | { type: "toggle_all"; customerIds: string[] }
  | { type: "clear_selected" }
  | { type: "set_sending_price_sheet"; sending: boolean }
  | { type: "set_price_sheet_target"; target: { customerIds: string[]; defaultSubject: string } | null }
  | { type: "set_open_customer_actions"; id: string | null }
  | { type: "set_deleting_customer"; id: string | null };

const initialState: State = {
  showForm: false,
  editing: null,
  subTab: "customers",
  form: EMPTY_CUSTOMER_FORM,
  saving: false,
  processingReg: null,
  pricingCustomer: null,
  selectedCustomers: new Set(),
  sendingPriceSheet: false,
  priceSheetTarget: null,
  openCustomerActions: null,
  deletingCustomer: null,
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "set_show_form":
      return { ...state, showForm: action.showForm };
    case "set_sub_tab":
      return { ...state, subTab: action.subTab };
    case "set_form_field":
      return { ...state, form: { ...state.form, [action.field]: action.value } };
    case "open_new":
      return { ...state, editing: null, form: EMPTY_CUSTOMER_FORM, showForm: true };
    case "open_edit":
      return { ...state, editing: action.customer, form: customerFormFromCustomer(action.customer), showForm: true };
    case "set_saving":
      return { ...state, saving: action.saving };
    case "set_processing_reg":
      return { ...state, processingReg: action.processingReg };
    case "set_pricing_customer":
      return { ...state, pricingCustomer: action.pricingCustomer };
    case "toggle_selected": {
      const next = new Set(state.selectedCustomers);
      if (next.has(action.id)) next.delete(action.id); else next.add(action.id);
      return { ...state, selectedCustomers: next };
    }
    case "toggle_all": {
      if (state.selectedCustomers.size === action.customerIds.length) {
        return { ...state, selectedCustomers: new Set() };
      }
      return { ...state, selectedCustomers: new Set(action.customerIds) };
    }
    case "clear_selected":
      return { ...state, selectedCustomers: new Set() };
    case "set_sending_price_sheet":
      return { ...state, sendingPriceSheet: action.sending };
    case "set_price_sheet_target":
      return { ...state, priceSheetTarget: action.target };
    case "set_open_customer_actions":
      return { ...state, openCustomerActions: action.id };
    case "set_deleting_customer":
      return { ...state, deletingCustomer: action.id };
  }
}

export default function CustomersTab({
  customers,
  products,
  brandId,
  onMsg,
  registrations = EMPTY_REGISTRATIONS,
  onRefresh,
}: {
  customers: WholesaleCustomer[];
  products: WholesaleProduct[];
  brandId: string;
  onMsg: (kind: "success" | "error", text: string) => void;
  registrations?: Registration[];
  onRefresh: () => void;
}) {
  const [state, dispatch] = useReducer(reducer, initialState);

  // Close customer actions dropdown when clicking outside
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (!(e.target as Element).closest(".customer-actions-cell")) {
        dispatch({ type: "set_open_customer_actions", id: null });
      }
    }
    document.addEventListener("click", handleClick);
    return () => document.removeEventListener("click", handleClick);
  }, []);

  async function handleApproveReject(regId: string, action: "approve" | "reject") {
    dispatch({ type: "set_processing_reg", processingReg: regId });
    const result = await approveWholesaleRegistration(regId, brandId, action);
    dispatch({ type: "set_processing_reg", processingReg: null });
    if (result.success) {
      onMsg("success", action === "approve" ? "Registration approved." : "Registration rejected.");
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Failed to process registration.");
    }
  }

  async function handleDeleteCustomer(customerId: string) {
    if (!confirm("Delete this customer? This cannot be undone. Customers with existing orders cannot be deleted.")) return;
    dispatch({ type: "set_deleting_customer", id: customerId });
    const result = await deleteWholesaleCustomer(customerId);
    dispatch({ type: "set_deleting_customer", id: null });
    if (result.success) {
      onMsg("success", "Customer deleted.");
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Failed to delete customer.");
    }
  }

  async function handleSave() {
    dispatch({ type: "set_saving", saving: true });
    const result = await saveWholesaleCustomer({
      brandId,
      userId: state.editing?.user_id ?? undefined,
      companyName: state.form.companyName || undefined,
      contactName: state.form.contactName || undefined,
      email: state.form.email || undefined,
      phone: state.form.phone || undefined,
      accountStatus: state.form.accountStatus,
      creditLimit: state.form.creditLimit,
      depositsEnabled: state.form.depositsEnabled,
      depositThreshold: state.form.depositThreshold ? Number(state.form.depositThreshold) : undefined,
      depositPercentage: state.form.depositPercentage ? Number(state.form.depositPercentage) : undefined,
      orderEmail: state.form.orderEmail || undefined,
      invoiceEmail: state.form.invoiceEmail || undefined,
      adminNotes: state.form.adminNotes || undefined,
    });
    dispatch({ type: "set_saving", saving: false });
    if (result.success) {
      onMsg("success", state.editing ? "Customer updated." : "Customer created.");
      dispatch({ type: "set_show_form", showForm: false });
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Failed to save.");
    }
  }

  function openPriceSheetModal(customerIds: string[]) {
    if (customerIds.length === 0) return;
    dispatch({
      type: "set_price_sheet_target",
      target: {
        customerIds,
        defaultSubject: `Wholesale Price Sheet — ${new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}`,
      },
    });
  }

  async function handleConfirmPriceSheet(subject: string, customNote: string) {
    if (!state.priceSheetTarget) return;
    dispatch({ type: "set_sending_price_sheet", sending: true });
    dispatch({ type: "set_price_sheet_target", target: null });
    try {
      const res = await fetch("/api/wholesale/price-sheet", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          customerIds: state.priceSheetTarget.customerIds,
          brandId,
          subject,
          customNote: customNote || undefined,
        }),
      });
      const data = await res.json();
      if (res.ok) {
        onMsg("success", `Price sheet sent to ${data.enqueued} customer(s).`);
        dispatch({ type: "clear_selected" });
      } else {
        onMsg("error", data.error ?? "Failed to send price sheet.");
      }
    } catch {
      onMsg("error", "Failed to send price sheet.");
    } finally {
      dispatch({ type: "set_sending_price_sheet", sending: false });
    }
  }

  const allCustomerIds = customers.map(c => c.id);

  return (
    <div className="space-y-4">
      {/* Sub-tab nav */}
      <div className="flex items-center gap-4">
        <AdminButton
          variant={state.subTab === "customers" ? "primary" : "secondary"}
          size="sm"
          onClick={() => dispatch({ type: "set_sub_tab", subTab: "customers" })}
        >
          Customers ({customers.filter(c => c.account_status !== "pending_approval" && c.account_status !== "rejected").length})
        </AdminButton>
        <AdminButton
          variant={state.subTab === "registrations" ? "primary" : "secondary"}
          size="sm"
          onClick={() => dispatch({ type: "set_sub_tab", subTab: "registrations" })}
        >
          Registrations ({registrations.filter(r => r.account_status === "pending_approval").length})
        </AdminButton>
        {state.subTab === "customers" && (
          <AdminButton
            variant="primary"
            size="sm"
            onClick={() => dispatch({ type: "open_new" })}
            className="ml-auto"
          >
            + Add Customer
          </AdminButton>
        )}
      </div>

      {state.subTab === "registrations" && (
        <RegistrationsSection
          registrations={registrations}
          processingReg={state.processingReg}
          onApproveReject={handleApproveReject}
        />
      )}

      {state.subTab === "customers" && (
        <>
          {state.showForm && (
            <CustomerFormSection
              editing={state.editing}
              form={state.form}
              saving={state.saving}
              onFieldChange={(field, value) => dispatch({ type: "set_form_field", field, value })}
              onSave={handleSave}
              onCancel={() => dispatch({ type: "set_show_form", showForm: false })}
            />
          )}

          <CustomerListSection
            customers={customers}
            selectedCustomers={state.selectedCustomers}
            allCustomerIds={allCustomerIds}
            openCustomerActions={state.openCustomerActions}
            deletingCustomer={state.deletingCustomer}
            sendingPriceSheet={state.sendingPriceSheet}
            onToggle={(id) => dispatch({ type: "toggle_selected", id })}
            onToggleAll={() => dispatch({ type: "toggle_all", customerIds: allCustomerIds })}
            onToggleActions={(id) => dispatch({ type: "set_open_customer_actions", id: state.openCustomerActions === id ? null : id })}
            onCloseActions={() => dispatch({ type: "set_open_customer_actions", id: null })}
            onEdit={(c) => dispatch({ type: "open_edit", customer: c })}
            onPricing={(c) => dispatch({ type: "set_pricing_customer", pricingCustomer: c })}
            onDelete={handleDeleteCustomer}
            onSendPriceSheet={openPriceSheetModal}
          />
        </>
      )}

      {/* Customer Pricing Overlays Panel */}
      {state.pricingCustomer && (
        <CustomerPricingPanel
          customer={state.pricingCustomer}
          products={products}
          onClose={() => dispatch({ type: "set_pricing_customer", pricingCustomer: null })}
          onMsg={onMsg}
        />
      )}

      {/* Price Sheet Modal */}
      {state.priceSheetTarget && (
        <PriceSheetModal
          customerCount={state.priceSheetTarget.customerIds.length}
          defaultSubject={state.priceSheetTarget.defaultSubject}
          onConfirm={handleConfirmPriceSheet}
          onClose={() => {
            dispatch({ type: "set_price_sheet_target", target: null });
            dispatch({ type: "set_sending_price_sheet", sending: false });
          }}
        />
      )}
    </div>
  );
}

// ── Subcomponents ─────────────────────────────────────────────────────────────

type RegistrationsSectionProps = {
  registrations: Registration[];
  processingReg: string | null;
  onApproveReject: (regId: string, action: "approve" | "reject") => void;
};

function RegistrationsSection({ registrations, processingReg, onApproveReject }: RegistrationsSectionProps) {
  const pending = registrations.filter(r => r.account_status === "pending_approval");
  return (
    <div className="space-y-3">
      <h3 className="text-sm font-semibold text-[var(--admin-text-secondary)]">Pending Registrations</h3>
      {pending.length === 0 ? (
        <p className="text-sm text-[var(--admin-text-muted)] py-4 text-center">No pending registrations.</p>
      ) : (
        <div className="rounded-2xl bg-white border border-[var(--admin-border)] shadow-sm overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-[var(--admin-bg-subtle)] text-[var(--admin-text-muted)]">
              <tr>
                <th className="px-5 py-3 font-semibold text-left">Company</th>
                <th className="px-5 py-3 font-semibold text-left">Contact</th>
                <th className="px-5 py-3 font-semibold text-left">Status</th>
                <th className="px-5 py-3 font-semibold text-left">Registered</th>
                <th className="px-5 py-3" aria-label="Actions"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[var(--admin-border-light)]">
              {pending.map(r => (
                <tr key={r.id} className="hover:bg-[var(--admin-bg-subtle)]">
                  <td className="px-5 py-3 font-medium text-[var(--admin-text-primary)]">{r.company_name ?? "—"}</td>
                  <td className="px-5 py-3 text-[var(--admin-text-secondary)]">{r.contact_name ?? "—"}<br/><span className="text-xs text-[var(--admin-text-muted)]">{r.email}</span></td>
                  <td className="px-5 py-3">
                    <AdminBadge variant="warning">Pending</AdminBadge>
                  </td>
                  <td className="px-5 py-3 text-[var(--admin-text-muted)] text-xs">{formatDate(new Date(r.created_at))}</td>
                  <td className="px-5 py-3">
                    <div className="flex gap-2">
                      <AdminButton
                        variant="primary"
                        size="sm"
                        onClick={() => onApproveReject(r.id, "approve")}
                        disabled={processingReg === r.id}
                        isLoading={processingReg === r.id}
                      >
                        {processingReg === r.id ? "..." : "Approve"}
                      </AdminButton>
                      <AdminButton
                        variant="danger"
                        size="sm"
                        onClick={() => onApproveReject(r.id, "reject")}
                        disabled={processingReg === r.id}
                      >
                        Reject
                      </AdminButton>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
