"use client";

import { useReducer, useEffect } from "react";
import {
  type WholesaleProduct,
  deleteWholesaleProduct,
  saveWholesaleProduct,
} from "@/actions/wholesale";
import { AdminButton, AdminBadge } from "@/components/admin/design-system";

type ProductForm = {
  name: string;
  description: string;
  unitType: string;
  availability: string;
  qtyAvailable: number;
  priceTiers: string;
  hpSku: string;
  hpItemId: string;
  handlingInstructions: string;
  storageWarning: string;
  productLabel: string;
};

const EMPTY_PRODUCT_FORM: ProductForm = {
  name: "",
  description: "",
  unitType: "each",
  availability: "available",
  qtyAvailable: 0,
  priceTiers: "",
  hpSku: "",
  hpItemId: "",
  handlingInstructions: "",
  storageWarning: "",
  productLabel: "",
};

function productFormFromProduct(p: WholesaleProduct): ProductForm {
  return {
    name: p.name,
    description: p.description ?? "",
    unitType: p.unit_type,
    availability: p.availability,
    qtyAvailable: Number(p.qty_available),
    priceTiers: JSON.stringify(p.price_tiers),
    hpSku: p.hp_sku ?? "",
    hpItemId: p.hp_item_id ?? "",
    handlingInstructions: p.handling_instructions ?? "",
    storageWarning: p.storage_warning ?? "",
    productLabel: p.product_label ?? "",
  };
}

type State = {
  showForm: boolean;
  editing: WholesaleProduct | null;
  form: ProductForm;
  saving: boolean;
  openProductActions: string | null;
  deletingProduct: string | null;
};

type Action =
  | { type: "open_new" }
  | { type: "open_edit"; product: WholesaleProduct }
  | { type: "set_show_form"; showForm: boolean }
  | { type: "set_form_field"; field: keyof ProductForm; value: ProductForm[keyof ProductForm] }
  | { type: "set_saving"; saving: boolean }
  | { type: "set_open_product_actions"; id: string | null }
  | { type: "set_deleting_product"; id: string | null };

const initialState: State = {
  showForm: false,
  editing: null,
  form: EMPTY_PRODUCT_FORM,
  saving: false,
  openProductActions: null,
  deletingProduct: null,
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "open_new":
      return { ...state, editing: null, form: EMPTY_PRODUCT_FORM, showForm: true };
    case "open_edit":
      return { ...state, editing: action.product, form: productFormFromProduct(action.product), showForm: true };
    case "set_show_form":
      return { ...state, showForm: action.showForm };
    case "set_form_field":
      return { ...state, form: { ...state.form, [action.field]: action.value } };
    case "set_saving":
      return { ...state, saving: action.saving };
    case "set_open_product_actions":
      return { ...state, openProductActions: action.id };
    case "set_deleting_product":
      return { ...state, deletingProduct: action.id };
  }
}

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

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

  async function handleDeleteProduct(productId: string) {
    if (!confirm("Delete this product? Products attached to order items cannot be deleted. Set availability to unavailable instead.")) return;
    dispatch({ type: "set_deleting_product", id: productId });
    const result = await deleteWholesaleProduct(productId);
    dispatch({ type: "set_deleting_product", id: null });
    if (result.success) {
      onMsg("success", "Product deleted.");
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Failed to delete product.");
    }
  }

  async function handleSave() {
    dispatch({ type: "set_saving", saving: true });
    let tiers: Array<{ min_qty: number; max_qty: number; price: number }> = [];
    try { tiers = JSON.parse(state.form.priceTiers || "[]"); } catch {}
    const result = await saveWholesaleProduct({
      brandId,
      id: state.editing?.id,
      name: state.form.name,
      description: state.form.description || undefined,
      unitType: state.form.unitType,
      availability: state.form.availability,
      qtyAvailable: state.form.qtyAvailable,
      priceTiers: tiers,
      hpSku: state.form.hpSku || undefined,
      hpItemId: state.form.hpItemId || undefined,
      handlingInstructions: state.form.handlingInstructions || undefined,
      storageWarning: state.form.storageWarning || undefined,
      productLabel: state.form.productLabel || undefined,
    });
    dispatch({ type: "set_saving", saving: false });
    if (result.success) {
      onMsg("success", state.editing ? "Product updated." : "Product created.");
      dispatch({ type: "set_show_form", showForm: false });
      onRefresh();
    } else {
      onMsg("error", result.error ?? "Failed to save.");
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold text-[var(--admin-text-primary)]">Wholesale Products ({products.length})</h2>
        <AdminButton variant="primary" size="sm" onClick={() => dispatch({ type: "open_new" })}>
          + Add Product
        </AdminButton>
      </div>

      {state.showForm && (
        <div className="rounded-2xl bg-white border border-[var(--admin-border)] p-6 shadow-sm">
          <h3 className="font-semibold text-[var(--admin-text-primary)] mb-4">{state.editing ? "Edit Product" : "New Product"}</h3>
          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-2">
              <label htmlFor="ws-prod-name" className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1">Product Name</label>
              <input aria-label="Ws Prod Name" id="ws-prod-name" value={state.form.name} onChange={e => dispatch({ type: "set_form_field", field: "name", value: e.target.value })}
                className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]" />
            </div>
            <div className="col-span-2">
              <label htmlFor="ws-prod-desc" className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1">Description</label>
              <textarea aria-label="Ws Prod Desc" id="ws-prod-desc" value={state.form.description} onChange={e => dispatch({ type: "set_form_field", field: "description", value: e.target.value })}
                className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]" rows={2} />
            </div>
            <div>
              <label htmlFor="ws-prod-unit" className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1">Unit Type</label>
              <select aria-label="Ws Prod Unit" id="ws-prod-unit" value={state.form.unitType} onChange={e => dispatch({ type: "set_form_field", field: "unitType", value: e.target.value })}
                className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]">
                {["each", "48-count box", "bag", "pallet", "bin", "load", "custom"].map(u => (
                  <option key={u} value={u}>{u}</option>
                ))}
              </select>
            </div>
            <div>
              <label htmlFor="fld-1-availability"  className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1">Availability</label>
              <select id="fld-1-availability"  aria-label="Select" value={state.form.availability} onChange={e => dispatch({ type: "set_form_field", field: "availability", value: e.target.value })}
                className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]">
                <option value="available">Available</option>
                <option value="unavailable">Unavailable</option>
                <option value="coming_soon">Coming Soon</option>
              </select>
            </div>
            <div>
              <label htmlFor="fld-2-qty-available"  className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1">Qty Available</label>
              <input id="fld-2-qty-available"  aria-label="Number" type="number" value={state.form.qtyAvailable} onChange={e => dispatch({ type: "set_form_field", field: "qtyAvailable", value: Number(e.target.value) })}
                className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]" />
            </div>
            <div>
              <label htmlFor="fld-3-hp-sku"  className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1">HP SKU</label>
              <input id="fld-3-hp-sku"  aria-label="Input" value={state.form.hpSku} onChange={e => dispatch({ type: "set_form_field", field: "hpSku", value: e.target.value })}
                className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]" />
            </div>
            <div className="col-span-2">
              <label htmlFor="fld-4-price-tiers-json-array-of-min-qty1max-qty24price20"  className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1">Price Tiers (JSON array of {"{\"min_qty\":1,\"max_qty\":24,\"price\":20}"})</label>
              <input id="fld-4-price-tiers-json-array-of-min-qty1max-qty24price20"  aria-label="[{&quot;min Qty&quot;:1,&quot;max Qty&quot;:24,&quot;price&quot;:20},{&quot;min Qty&quot;:25,&quot;max Qty&quot;:0,&quot;price&quot;:18}]" value={state.form.priceTiers} onChange={e => dispatch({ type: "set_form_field", field: "priceTiers", value: e.target.value })}
                placeholder='[{"min_qty":1,"max_qty":24,"price":20},{"min_qty":25,"max_qty":0,"price":18}]'
                className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm font-mono outline-none focus:border-[var(--admin-accent)]" />
            </div>
          </div>
          <div className="mt-4 flex gap-3">
            <AdminButton onClick={handleSave} disabled={state.saving} variant="primary" isLoading={state.saving}>
              {state.saving ? "Saving..." : "Save Product"}
            </AdminButton>
            <AdminButton onClick={() => dispatch({ type: "set_show_form", showForm: false })} variant="secondary">
              Cancel
            </AdminButton>
          </div>
        </div>
      )}

      <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">Product</th>
              <th className="px-5 py-3 font-semibold text-left">Unit</th>
              <th className="px-5 py-3 font-semibold text-left">Availability</th>
              <th className="px-5 py-3 font-semibold text-left">In Stock</th>
              <th className="px-5 py-3 font-semibold text-left">HP SKU</th>
              <th className="px-5 py-3" aria-label="Actions"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-[var(--admin-border-light)]">
            {products.length === 0 ? (
              <tr>
                <td colSpan={6} className="py-12 text-center">
                  <div className="flex flex-col items-center">
                    <div className="w-12 h-12 bg-slate-100 rounded-2xl flex items-center justify-center mx-auto mb-3">
                      <svg className="w-6 h-6 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
                      </svg>
                    </div>
                    <p className="text-sm font-semibold text-slate-600 mb-1">No wholesale products yet</p>
                    <p className="text-xs text-slate-400">Add products to your wholesale catalog to get started.</p>
                  </div>
                </td>
              </tr>
            ) : products.map(p => (
              <tr key={p.id} className="hover:bg-[var(--admin-bg-subtle)]">
                <td className="px-5 py-3 font-medium text-[var(--admin-text-primary)]">{p.name}</td>
                <td className="px-5 py-3 text-[var(--admin-text-secondary)]">{p.unit_type}</td>
                <td className="px-5 py-3">
                  <AdminBadge variant={p.availability === "available" ? "success" : p.availability === "coming_soon" ? "warning" : "default"}>
                    {p.availability.replace("_", " ")}
                  </AdminBadge>
                </td>
                <td className="px-5 py-3 text-[var(--admin-text-secondary)]">{p.qty_available}</td>
                <td className="px-5 py-4 font-mono text-xs text-[var(--admin-text-muted)]">{p.hp_sku ?? "—"}</td>
                <td className="px-5 py-4 product-actions-cell relative">
                  <div className="flex items-center gap-1.5">
                    <div className="relative">
                      <button type="button"
                        onClick={(e) => {
                          e.stopPropagation();
                          dispatch({ type: "set_open_product_actions", id: state.openProductActions === p.id ? null : p.id });
                        }}
                        title="More actions"
                        aria-label="More actions"
                        className="inline-flex items-center justify-center rounded-xl w-9 h-9 text-[var(--admin-text-muted)] hover:text-[var(--admin-text-secondary)] hover:bg-[var(--admin-bg-subtle)] transition-colors"
                      >
                        <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><circle cx="10" cy="4" r="1.5"/><circle cx="10" cy="10" r="1.5"/><circle cx="10" cy="16" r="1.5"/></svg>
                      </button>
                      {state.openProductActions === p.id && (
                        <div
                          className="absolute bottom-full right-0 mb-1 z-30 w-48 rounded-xl bg-white shadow-xl ring-1 ring-[var(--admin-border)] py-1 text-sm"
                          onClick={e => e.stopPropagation()}
                        >
                          <button type="button"
                            onClick={() => { dispatch({ type: "set_open_product_actions", id: null }); dispatch({ type: "open_edit", product: p }); }}
                            className="w-full text-left px-4 py-3 text-[var(--admin-accent)] hover:bg-[var(--admin-accent-light)] flex items-center gap-3 font-medium"
                          >
                            <svg className="w-4 h-4 text-[var(--admin-accent)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                            Edit Product
                          </button>
                          <div className="my-1 border-t border-[var(--admin-border)]" />
                          <button type="button"
                            onClick={() => { dispatch({ type: "set_open_product_actions", id: null }); handleDeleteProduct(p.id); }}
                            disabled={state.deletingProduct === p.id}
                            className="w-full text-left px-4 py-3 text-[var(--admin-danger)] hover:bg-[var(--admin-danger-light)] flex items-center gap-3 disabled:opacity-50"
                          >
                            <svg className="w-4 h-4 text-[var(--admin-danger)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                            {state.deletingProduct === p.id ? "Deleting..." : "Delete Product"}
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
