"use client";

import Link from "next/link";
import { useState } from "react";
import { formatCurrency, formatDate } from "@/lib/utils";
import { useTableControls } from "@/components/ui/use-table-controls";
import { TableControls, SortableTh } from "@/components/ui/table-controls";
import { AddProductButton, EditProductButton } from "./product-form";
import { RowActionsMenu, RowActionsItem, RowActionsDestructiveItem, RowActionsSeparator } from "@/components/ui/row-actions-menu";
import { DeleteConfirmDialog } from "@/components/ui/delete-confirm-dialog";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { deleteProduct, toggleProductActive } from "./actions";

export type ProductRow = {
  id: string;
  code: string;
  name: string;
  description: string | null;
  lastPrice: number | null;
  lastVendorName: string | null;
  updatedAt: string; // ISO string
  isActive: boolean;
  vendorPriceCount: number;
};

const CHIPS = ["Active", "Inactive"];

function ProductActionsMenu({ product }: { product: ProductRow }) {
  const [editOpen, setEditOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [toggleOpen, setToggleOpen] = useState(false);

  return (
    <>
      <RowActionsMenu>
        <RowActionsItem onClick={() => setEditOpen(true)}>Edit</RowActionsItem>
        <RowActionsItem onClick={() => setToggleOpen(true)}>
          {product.isActive ? "Deactivate" : "Activate"}
        </RowActionsItem>
        <RowActionsSeparator />
        <RowActionsDestructiveItem onClick={() => setDeleteOpen(true)}>Delete</RowActionsDestructiveItem>
      </RowActionsMenu>

      <EditProductButton
        product={{ id: product.id, code: product.code, name: product.name, description: product.description, isActive: product.isActive }}
        open={editOpen}
        onOpenChange={setEditOpen}
      />
      <DeleteConfirmDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        label={product.name}
        onConfirm={() => deleteProduct(product.id)}
      />
      <ConfirmDialog
        open={toggleOpen}
        onOpenChange={setToggleOpen}
        title={product.isActive ? `Deactivate ${product.name}?` : `Activate ${product.name}?`}
        description={product.isActive ? `${product.name} will be hidden from new purchase orders.` : `${product.name} will become available for new purchase orders.`}
        confirmLabel={product.isActive ? "Deactivate" : "Activate"}
        onConfirm={() => toggleProductActive(product.id)}
      />
    </>
  );
}

export function ProductsTable({
  products,
  canManage,
  detailBase = "/inventory/items",
}: {
  products: ProductRow[];
  canManage: boolean;
  detailBase?: string;
}) {
  const { search, setSearch, sortKey, sortDir, toggleSort, activeFilters, toggleFilter, filtered } =
    useTableControls<ProductRow>({
      rows: products,
      defaultSortKey: "name",
      searchText: (p) =>
        [p.code, p.name, p.description ?? "", p.lastVendorName ?? "", p.isActive ? "active" : "inactive"].join(" "),
      chipMatch: (p, chip) => {
        if (chip.toLowerCase() === "active") return p.isActive;
        if (chip.toLowerCase() === "inactive") return !p.isActive;
        return false;
      },
      sortValue: (p, key) => {
        if (key === "isActive") return p.isActive ? "Active" : "Inactive";
        if (key === "lastVendorName") return p.lastVendorName ?? "";
        if (key === "lastPrice") return p.lastPrice ?? -Infinity;
        const val = p[key as keyof ProductRow];
        if (val === null || val === undefined) return "";
        return typeof val === "string" || typeof val === "number" || typeof val === "boolean" ? val : String(val);
      },
    });

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-semibold text-neutral-900">Item Catalogue</h1>
        {canManage && <AddProductButton />}
      </div>

      <TableControls
        search={search}
        onSearch={setSearch}
        searchPlaceholder="Search items…"
        chips={CHIPS}
        activeFilters={activeFilters}
        onToggleFilter={toggleFilter}
      />

      <div className="rounded-lg border border-neutral-200 bg-white overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-neutral-50 border-b border-neutral-200">
            <tr>
              <SortableTh sortKey="name" activeSortKey={sortKey as string | null} sortDir={sortDir} onSort={(k) => toggleSort(k as keyof ProductRow)}>Name</SortableTh>
              <SortableTh sortKey="code" activeSortKey={sortKey as string | null} sortDir={sortDir} onSort={(k) => toggleSort(k as keyof ProductRow)}>Code</SortableTh>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Description</th>
              <th className="px-4 py-3 text-right font-medium text-neutral-600">Vendors</th>
              <SortableTh sortKey="lastPrice" activeSortKey={sortKey as string | null} sortDir={sortDir} onSort={(k) => toggleSort(k as keyof ProductRow)} className="text-right">Last Price</SortableTh>
              <SortableTh sortKey="lastVendorName" activeSortKey={sortKey as string | null} sortDir={sortDir} onSort={(k) => toggleSort(k as keyof ProductRow)}>Last Vendor</SortableTh>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Updated</th>
              <SortableTh sortKey="isActive" activeSortKey={sortKey as string | null} sortDir={sortDir} onSort={(k) => toggleSort(k as keyof ProductRow)}>Status</SortableTh>
              {canManage && <th className="px-4 py-3 w-10"></th>}
            </tr>
          </thead>
          <tbody className="divide-y divide-neutral-100">
            {filtered.length === 0 && (
              <tr>
                <td colSpan={canManage ? 9 : 8} className="px-4 py-8 text-center text-neutral-400">
                  No items match your search.
                </td>
              </tr>
            )}
            {filtered.map((product) => (
              <tr key={product.id} className="hover:bg-neutral-50">
                <td className="px-4 py-3">
                  <Link
                    href={`${detailBase}/${product.id}`}
                    className="font-medium text-primary-600 hover:underline"
                  >
                    {product.name}
                  </Link>
                </td>
                <td className="px-4 py-3 font-mono text-xs text-neutral-500">{product.code}</td>
                <td className="px-4 py-3 text-neutral-500 max-w-xs truncate">
                  {product.description ?? <span className="italic text-neutral-400">—</span>}
                </td>
                <td className="px-4 py-3 text-right text-neutral-600">
                  {product.vendorPriceCount > 0
                    ? product.vendorPriceCount
                    : <span className="text-neutral-400">—</span>}
                </td>
                <td className="px-4 py-3 text-right text-neutral-700">
                  {product.lastPrice !== null
                    ? formatCurrency(product.lastPrice)
                    : <span className="text-neutral-400 italic">—</span>}
                </td>
                <td className="px-4 py-3 text-neutral-600">
                  {product.lastVendorName ?? <span className="italic text-neutral-400">—</span>}
                </td>
                <td className="px-4 py-3 text-neutral-500">{formatDate(product.updatedAt)}</td>
                <td className="px-4 py-3">
                  <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${
                    product.isActive ? "bg-success-100 text-success-700" : "bg-neutral-100 text-neutral-500"
                  }`}>
                    {product.isActive ? "Active" : "Inactive"}
                  </span>
                </td>
                {canManage && (
                  <td className="px-4 py-3">
                    <ProductActionsMenu product={product} />
                  </td>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <p className="mt-3 text-xs text-neutral-400">
        Items and vendor prices are updated automatically when a PO is marked as paid.
      </p>
    </div>
  );
}
