"use client";

import Link from "next/link";
import { useState } from "react";
import { useTableControls } from "@/components/ui/use-table-controls";
import { TableControls, SortableTh } from "@/components/ui/table-controls";
import { AddVendorButton, EditVendorButton } from "./vendor-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 { deleteVendor, toggleVendorActive, verifyVendor } from "./actions";

type ContactRow = {
  name: string;
  role: string;
  mobile: string;
  email: string;
  isPrimary: boolean;
};

export type VendorRow = {
  id: string;
  vendorId: string | null;
  name: string;
  gstin: string | null;
  address: string | null;
  pincode: string | null;
  isVerified: boolean;
  isActive: boolean;
  itemCount: number;
  contacts: ContactRow[];
};

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

function VendorActionsMenu({ vendor }: { vendor: VendorRow }) {
  const [editOpen, setEditOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [toggleOpen, setToggleOpen] = useState(false);
  const [verifyOpen, setVerifyOpen] = useState(false);

  return (
    <>
      <RowActionsMenu>
        <RowActionsItem onClick={() => setEditOpen(true)}>Edit</RowActionsItem>
        {!vendor.isVerified && (
          <RowActionsItem onClick={() => setVerifyOpen(true)}>Verify vendor</RowActionsItem>
        )}
        <RowActionsItem onClick={() => setToggleOpen(true)}>
          {vendor.isActive ? "Deactivate" : "Activate"}
        </RowActionsItem>
        <RowActionsSeparator />
        <RowActionsDestructiveItem onClick={() => setDeleteOpen(true)}>Delete</RowActionsDestructiveItem>
      </RowActionsMenu>

      <ConfirmDialog
        open={verifyOpen}
        onOpenChange={setVerifyOpen}
        title={`Verify ${vendor.name}?`}
        description="Marks this vendor as verified and approved for use across the portal."
        confirmLabel="Verify"
        onConfirm={() => verifyVendor(vendor.id)}
      />

      <EditVendorButton
        vendor={{
          id: vendor.id,
          name: vendor.name,
          vendorId: vendor.vendorId,
          address: vendor.address,
          pincode: vendor.pincode,
          gstin: vendor.gstin,
          isActive: vendor.isActive,
          contacts: vendor.contacts,
        }}
        open={editOpen}
        onOpenChange={setEditOpen}
      />
      <DeleteConfirmDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        label={vendor.name}
        onConfirm={() => deleteVendor(vendor.id)}
      />
      <ConfirmDialog
        open={toggleOpen}
        onOpenChange={setToggleOpen}
        title={vendor.isActive ? `Deactivate ${vendor.name}?` : `Activate ${vendor.name}?`}
        description={vendor.isActive ? `${vendor.name} will be hidden from new purchase orders.` : `${vendor.name} will become available for new purchase orders.`}
        confirmLabel={vendor.isActive ? "Deactivate" : "Activate"}
        onConfirm={() => toggleVendorActive(vendor.id)}
      />
    </>
  );
}

export function VendorsTable({
  vendors,
  suggestedVendorId,
}: {
  vendors: VendorRow[];
  suggestedVendorId: string;
}) {
  const { search, setSearch, sortKey, sortDir, toggleSort, activeFilters, toggleFilter, filtered } =
    useTableControls<VendorRow>({
      rows: vendors,
      defaultSortKey: "name",
      searchText: (v) =>
        [v.vendorId ?? "", v.name, v.gstin ?? "", v.address ?? "", v.isVerified ? "verified" : "unverified", v.isActive ? "active" : "inactive"].join(" "),
      chipMatch: (v, chip) => {
        const cl = chip.toLowerCase();
        if (cl === "verified") return v.isVerified;
        if (cl === "unverified") return !v.isVerified;
        if (cl === "active") return v.isActive;
        if (cl === "inactive") return !v.isActive;
        return false;
      },
      sortValue: (v, key) => {
        if (key === "isVerified") return v.isVerified ? "Verified" : "Unverified";
        if (key === "isActive") return v.isActive ? "Active" : "Inactive";
        const val = v[key as keyof VendorRow];
        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">Vendor Registry</h1>
        <AddVendorButton suggestedId={suggestedVendorId} />
      </div>

      <TableControls
        search={search}
        onSearch={setSearch}
        searchPlaceholder="Search vendors…"
        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="vendorId" activeSortKey={sortKey as string | null} sortDir={sortDir} onSort={(k) => toggleSort(k as keyof VendorRow)}>Vendor ID</SortableTh>
              <SortableTh sortKey="name" activeSortKey={sortKey as string | null} sortDir={sortDir} onSort={(k) => toggleSort(k as keyof VendorRow)}>Name</SortableTh>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Contact</th>
              <th className="px-4 py-3 text-right font-medium text-neutral-600">Items</th>
              <SortableTh sortKey="isVerified" activeSortKey={sortKey as string | null} sortDir={sortDir} onSort={(k) => toggleSort(k as keyof VendorRow)}>Verified</SortableTh>
              <SortableTh sortKey="isActive" activeSortKey={sortKey as string | null} sortDir={sortDir} onSort={(k) => toggleSort(k as keyof VendorRow)}>Status</SortableTh>
              <th className="px-4 py-3 w-10"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-neutral-100">
            {filtered.length === 0 && (
              <tr>
                <td colSpan={7} className="px-4 py-8 text-center text-neutral-400">
                  No vendors match your search.
                </td>
              </tr>
            )}
            {filtered.map((vendor) => (
              <tr key={vendor.id} className="hover:bg-neutral-50">
                <td className="px-4 py-3 font-mono text-xs text-neutral-600">
                  {vendor.vendorId ?? <span className="text-warning-700 italic">Pending</span>}
                </td>
                <td className="px-4 py-3">
                  <Link
                    href={`/admin/vendors/${vendor.id}`}
                    className="font-medium text-primary-600 hover:underline"
                  >
                    {vendor.name}
                  </Link>
                </td>
                <td className="px-4 py-3 text-neutral-600">
                  {vendor.contacts.length > 0 ? (
                    <>
                      <span>{vendor.contacts[0].name}</span>
                      {vendor.contacts[0].email && (
                        <span className="block text-xs text-neutral-400">{vendor.contacts[0].email}</span>
                      )}
                      {vendor.contacts.length > 1 && (
                        <span className="block text-xs text-neutral-400">+{vendor.contacts.length - 1} more</span>
                      )}
                    </>
                  ) : "—"}
                </td>
                <td className="px-4 py-3 text-right text-neutral-600">
                  {vendor.itemCount > 0 ? vendor.itemCount : <span className="text-neutral-400">—</span>}
                </td>
                <td className="px-4 py-3">
                  <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${
                    vendor.isVerified ? "bg-success-100 text-success-700" : "bg-warning-100 text-warning-700"
                  }`}>
                    {vendor.isVerified ? "Verified" : "Unverified"}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${
                    vendor.isActive ? "bg-success-100 text-success-700" : "bg-neutral-100 text-neutral-500"
                  }`}>
                    {vendor.isActive ? "Active" : "Inactive"}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <VendorActionsMenu vendor={vendor} />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
