"use client";

import { useReducer, useEffect, useRef } from "react";
import {
  type WholesaleOrder,
  type WholesaleCustomer,
  bulkFulfillWholesaleOrders,
  bulkRecordWholesaleDeposit,
  recordWholesaleDeposit,
} from "@/actions/wholesale";
import OrderDetailsModal from "@/components/wholesale/OrderDetailsModal";

import OrdersFilterBar from "./OrdersFilterBar";
import OrdersBulkActionsBar from "./OrdersBulkActionsBar";
import OrdersManifestSection from "./OrdersManifestSection";
import OrdersTable from "./OrdersTable";
import OrdersDepositModal from "./OrdersDepositModal";
import OrdersBulkDepositModal from "./OrdersBulkDepositModal";
import { fulfillWithNotifications, openManifestWindow } from "./ordersActions";

type State = {
  showDepForm: string | null;
  depAmount: string;
  depMethod: string;
  fulfilling: string | null;
  manifestLoading: boolean;
  selected: Set<string>;
  statusFilter: string;
  dateFrom: string;
  dateTo: string;
  searchQuery: string;
  bulkDepAmount: string;
  bulkDepMethod: string;
  showBulkDep: boolean;
  bulkLoading: boolean;
  openActions: string | null;
  showViewOrder: WholesaleOrder | null;
};

type Action =
  | { type: "set_show_dep_form"; id: string | null }
  | { type: "set_dep_amount"; amount: string }
  | { type: "set_dep_method"; method: string }
  | { type: "set_fulfilling"; id: string | null }
  | { type: "set_manifest_loading"; loading: boolean }
  | { type: "toggle_selected"; id: string }
  | { type: "toggle_all"; ids: string[] }
  | { type: "clear_selected" }
  | { type: "set_status_filter"; value: string }
  | { type: "set_date_from"; value: string }
  | { type: "set_date_to"; value: string }
  | { type: "set_search_query"; value: string }
  | { type: "set_bulk_dep_amount"; amount: string }
  | { type: "set_bulk_dep_method"; method: string }
  | { type: "set_show_bulk_dep"; show: boolean }
  | { type: "set_bulk_loading"; loading: boolean }
  | { type: "set_open_actions"; id: string | null }
  | { type: "set_show_view_order"; order: WholesaleOrder | null };

const initialState: State = {
  showDepForm: null,
  depAmount: "",
  depMethod: "cash",
  fulfilling: null,
  manifestLoading: false,
  selected: new Set(),
  statusFilter: "all",
  dateFrom: "",
  dateTo: "",
  searchQuery: "",
  bulkDepAmount: "",
  bulkDepMethod: "cash",
  showBulkDep: false,
  bulkLoading: false,
  openActions: null,
  showViewOrder: null,
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "set_show_dep_form":
      return { ...state, showDepForm: action.id };
    case "set_dep_amount":
      return { ...state, depAmount: action.amount };
    case "set_dep_method":
      return { ...state, depMethod: action.method };
    case "set_fulfilling":
      return { ...state, fulfilling: action.id };
    case "set_manifest_loading":
      return { ...state, manifestLoading: action.loading };
    case "toggle_selected": {
      const next = new Set(state.selected);
      if (next.has(action.id)) next.delete(action.id); else next.add(action.id);
      return { ...state, selected: next };
    }
    case "toggle_all": {
      if (state.selected.size === action.ids.length) {
        return { ...state, selected: new Set() };
      }
      return { ...state, selected: new Set(action.ids) };
    }
    case "clear_selected":
      return { ...state, selected: new Set() };
    case "set_status_filter":
      return { ...state, statusFilter: action.value };
    case "set_date_from":
      return { ...state, dateFrom: action.value };
    case "set_date_to":
      return { ...state, dateTo: action.value };
    case "set_search_query":
      return { ...state, searchQuery: action.value };
    case "set_bulk_dep_amount":
      return { ...state, bulkDepAmount: action.amount };
    case "set_bulk_dep_method":
      return { ...state, bulkDepMethod: action.method };
    case "set_show_bulk_dep":
      return { ...state, showBulkDep: action.show };
    case "set_bulk_loading":
      return { ...state, bulkLoading: action.loading };
    case "set_open_actions":
      return { ...state, openActions: action.id };
    case "set_show_view_order":
      return { ...state, showViewOrder: action.order };
  }
}

export default function OrdersTab({ orders, customers, brandId, onMsg, onRefresh }: {
  orders: WholesaleOrder[];
  customers: WholesaleCustomer[];
  brandId: string;
  onMsg: (kind: "success" | "error", text: string) => void;
  onRefresh: () => void;
}) {
  const [state, dispatch] = useReducer(reducer, initialState);
  const deletingRef = useRef<string | null>(null);

  const filtered = orders.filter(o => {
    if (state.statusFilter !== "all" && o.status !== state.statusFilter) return false;
    if (state.dateFrom && (!o.anticipated_pickup_date || o.anticipated_pickup_date < state.dateFrom)) return false;
    if (state.dateTo && (!o.anticipated_pickup_date || o.anticipated_pickup_date > state.dateTo)) return false;
    if (state.searchQuery) {
      const q = state.searchQuery.toLowerCase();
      if (!(o.company_name?.toLowerCase().includes(q) || o.invoice_number?.toLowerCase().includes(q) || o.customer_email?.toLowerCase().includes(q))) return false;
    }
    return true;
  });

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

  async function handleBulkFulfill() {
    if (state.selected.size === 0) return;
    dispatch({ type: "set_bulk_loading", loading: true });
    const result = await bulkFulfillWholesaleOrders(Array.from(state.selected));
    dispatch({ type: "set_bulk_loading", loading: false });
    if (result.success) {
      onMsg("success", `${result.count} order(s) marked as fulfilled.`);
      dispatch({ type: "clear_selected" });
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Bulk fulfill failed.");
    }
  }

  async function handleBulkDeposit() {
    if (state.selected.size === 0 || !state.bulkDepAmount) return;
    dispatch({ type: "set_bulk_loading", loading: true });
    const result = await bulkRecordWholesaleDeposit(Array.from(state.selected), Number(state.bulkDepAmount), state.bulkDepMethod);
    dispatch({ type: "set_bulk_loading", loading: false });
    if (result.success) {
      onMsg("success", `Deposit recorded on ${result.count} order(s).`);
      dispatch({ type: "clear_selected" });
      dispatch({ type: "set_show_bulk_dep", show: false });
      dispatch({ type: "set_bulk_dep_amount", amount: "" });
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Bulk deposit failed.");
    }
  }

  async function handleFulfill(orderId: string) {
    dispatch({ type: "set_fulfilling", id: orderId });
    const result = await fulfillWithNotifications(orderId, orders, customers, brandId);
    dispatch({ type: "set_fulfilling", id: null });
    if (result.success) {
      onMsg("success", "Order marked as fulfilled.");
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Failed to fulfill order.");
    }
  }

  async function handleRecordDeposit(orderId: string) {
    const result = await recordWholesaleDeposit(orderId, Number(state.depAmount), state.depMethod);
    dispatch({ type: "set_show_dep_form", id: null });
    dispatch({ type: "set_dep_amount", amount: "" });
    if (result.success) {
      onMsg("success", "Deposit recorded.");
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Failed to record deposit.");
    }
  }

  async function handleCancelOrder(orderId: string) {
    if (!confirm("Cancel this order? This cannot be undone.")) return;
    const { updateWholesaleOrderStatus } = await import("@/actions/wholesale");
    const result = await updateWholesaleOrderStatus(orderId, "cancelled");
    if (result.success) {
      onMsg("success", "Order cancelled.");
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Failed to cancel order.");
    }
  }

  async function handleDeleteOrder(orderId: string) {
    if (!confirm("Delete this order? Fulfilled and paid orders cannot be deleted. This cannot be undone.")) return;
    deletingRef.current = orderId;
    const { deleteWholesaleOrder } = await import("@/actions/wholesale");
    const result = await deleteWholesaleOrder(orderId);
    deletingRef.current = null;
    if (result.success) {
      onMsg("success", "Order deleted.");
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Failed to delete order.");
    }
  }

  function handleGenerateManifest() {
    dispatch({ type: "set_manifest_loading", loading: true });
    const pending = filtered.filter(o => o.fulfillment_status !== "fulfilled");
    if (pending.length === 0) {
      dispatch({ type: "set_manifest_loading", loading: false });
      return;
    }
    openManifestWindow(pending, brandId);
    dispatch({ type: "set_manifest_loading", loading: false });
  }

  function handleGenerateManifestForOrder(o: WholesaleOrder) {
    openManifestWindow([o], brandId);
  }

  function handleSendPriceSheetForOrder(o: WholesaleOrder) {
    fetch("/api/wholesale/price-sheet", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ customerIds: [o.customer_id], brandId }),
    })
      .then(r => r.json())
      .then(() => onMsg("success", `Price sheet sent to customer.`))
      .catch(() => onMsg("error", "Failed to send price sheet."));
  }

  const filteredIds = filtered.map(o => o.id);

  return (
    <div className="space-y-4">
      <h2 className="text-lg font-semibold text-[var(--admin-text-primary)]">Wholesale Orders ({orders.length})</h2>

      {/* Filter bar */}
      <OrdersFilterBar
        filters={{
          statusFilter: state.statusFilter,
          dateFrom: state.dateFrom,
          dateTo: state.dateTo,
          searchQuery: state.searchQuery,
        }}
        filteredCount={filtered.length}
        totalCount={orders.length}
        onStatusChange={(v) => dispatch({ type: "set_status_filter", value: v })}
        onDateFromChange={(v) => dispatch({ type: "set_date_from", value: v })}
        onDateToChange={(v) => dispatch({ type: "set_date_to", value: v })}
        onSearchChange={(v) => dispatch({ type: "set_search_query", value: v })}
        onSearchClear={() => dispatch({ type: "set_search_query", value: "" })}
      />

      {/* Bulk actions */}
      {state.selected.size > 0 && (
        <OrdersBulkActionsBar
          selectedCount={state.selected.size}
          bulkLoading={state.bulkLoading}
          onBulkFulfill={handleBulkFulfill}
          onOpenBulkDeposit={() => dispatch({ type: "set_show_bulk_dep", show: true })}
          onClearSelection={() => dispatch({ type: "clear_selected" })}
        />
      )}

      {/* Manifest section */}
      <OrdersManifestSection
        manifestLoading={state.manifestLoading}
        onGenerateManifest={handleGenerateManifest}
      />

      <OrdersTable
        orders={filtered}
        selected={state.selected}
        fulfilling={state.fulfilling}
        openActions={state.openActions}
        onToggleSelect={(id) => dispatch({ type: "toggle_selected", id })}
        onToggleAll={() => dispatch({ type: "toggle_all", ids: filteredIds })}
        onFulfill={handleFulfill}
        onRecordDeposit={(id) => dispatch({ type: "set_show_dep_form", id })}
        onToggleActions={(id) => dispatch({ type: "set_open_actions", id: state.openActions === id ? null : id })}
        onCloseActions={() => dispatch({ type: "set_open_actions", id: null })}
        onViewOrder={(o) => dispatch({ type: "set_show_view_order", order: o })}
        onGenerateManifestForOrder={handleGenerateManifestForOrder}
        onSendPriceSheetForOrder={handleSendPriceSheetForOrder}
        onCancelOrder={handleCancelOrder}
        onDeleteOrder={handleDeleteOrder}
      />

      {/* Deposit modal */}
      {state.showDepForm && (
        <OrdersDepositModal
          depAmount={state.depAmount}
          depMethod={state.depMethod}
          onAmountChange={(v) => dispatch({ type: "set_dep_amount", amount: v })}
          onMethodChange={(v) => dispatch({ type: "set_dep_method", method: v })}
          onConfirm={() => handleRecordDeposit(state.showDepForm!)}
          onCancel={() => dispatch({ type: "set_show_dep_form", id: null })}
        />
      )}

      {/* Bulk Deposit modal */}
      {state.showBulkDep && (
        <OrdersBulkDepositModal
          selectedCount={state.selected.size}
          bulkDepAmount={state.bulkDepAmount}
          bulkDepMethod={state.bulkDepMethod}
          bulkLoading={state.bulkLoading}
          onAmountChange={(v) => dispatch({ type: "set_bulk_dep_amount", amount: v })}
          onMethodChange={(v) => dispatch({ type: "set_bulk_dep_method", method: v })}
          onConfirm={handleBulkDeposit}
          onCancel={() => dispatch({ type: "set_show_bulk_dep", show: false })}
        />
      )}

      {/* Order Details modal */}
      {state.showViewOrder && (
        <OrderDetailsModal
          order={state.showViewOrder}
          onClose={() => dispatch({ type: "set_show_view_order", order: null })}
          onFulfill={handleFulfill}
          onRecordDeposit={(id) => {
            dispatch({ type: "set_show_view_order", order: null });
            dispatch({ type: "set_show_dep_form", id });
          }}
          fulfilling={state.fulfilling}
        />
      )}
    </div>
  );
}
