"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
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 { deleteCompany, toggleCompanyActive } from "./actions";

export type CompanyRow = {
  id: string;
  name: string;
  code: string | null;
  gstNumber: string | null;
  address: string | null;
  telephone: string | null;
  mobile: string | null;
  email: string | null;
  invoiceEmail: string | null;
  invoiceAddress: string | null;
  isActive: boolean;
};

function CompanyActionsMenu({ company }: { company: CompanyRow }) {
  const router = useRouter();
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [toggleOpen, setToggleOpen] = useState(false);

  return (
    <>
      <RowActionsMenu>
        <RowActionsItem onClick={() => router.push(`/admin/companies/${company.id}/edit`)}>Edit</RowActionsItem>
        <RowActionsItem onClick={() => setToggleOpen(true)}>
          {company.isActive ? "Deactivate" : "Activate"}
        </RowActionsItem>
        <RowActionsSeparator />
        <RowActionsDestructiveItem onClick={() => setDeleteOpen(true)}>Delete</RowActionsDestructiveItem>
      </RowActionsMenu>
      <DeleteConfirmDialog
        open={deleteOpen} onOpenChange={setDeleteOpen}
        label={company.name} onConfirm={() => deleteCompany(company.id)}
      />
      <ConfirmDialog
        open={toggleOpen} onOpenChange={setToggleOpen}
        title={company.isActive ? `Deactivate ${company.name}?` : `Activate ${company.name}?`}
        description={company.isActive ? `${company.name} will not appear in new PO selections.` : `${company.name} will become available for new POs.`}
        confirmLabel={company.isActive ? "Deactivate" : "Activate"}
        onConfirm={() => toggleCompanyActive(company.id)}
      />
    </>
  );
}

export function CompaniesTable({ companies }: { companies: CompanyRow[] }) {
  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-neutral-900">Company Management</h1>
          <p className="text-sm text-neutral-500 mt-0.5">Sister companies used for invoicing and purchase orders</p>
        </div>
        <Link href="/admin/companies/new"
          className="rounded-lg bg-primary-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-primary-700 transition-colors">
          + Add Company
        </Link>
      </div>

      <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>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Company Name</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">GST Number</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Contact</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Status</th>
              <th className="px-4 py-3 w-10"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-neutral-100">
            {companies.length === 0 && (
              <tr>
                <td colSpan={5} className="px-4 py-10 text-center text-neutral-400">
                  No companies yet. Add one to start selecting it on purchase orders.
                </td>
              </tr>
            )}
            {companies.map((c) => (
              <tr key={c.id} className="hover:bg-neutral-50">
                <td className="px-4 py-3">
                  <div className="flex items-center gap-2">
                    {c.code && (
                      <span className="font-mono text-xs font-semibold text-primary-700 bg-primary-50 px-1.5 py-0.5 rounded">{c.code}</span>
                    )}
                    <p className="font-medium text-neutral-900">{c.name}</p>
                  </div>
                  {c.address && <p className="text-xs text-neutral-400 mt-0.5 truncate max-w-xs">{c.address}</p>}
                </td>
                <td className="px-4 py-3 font-mono text-xs text-neutral-600">{c.gstNumber ?? <span className="italic text-neutral-400">—</span>}</td>
                <td className="px-4 py-3 text-xs text-neutral-500 space-y-0.5">
                  {c.telephone && <p>☎ {c.telephone}</p>}
                  {c.mobile && <p>📱 {c.mobile}</p>}
                  {c.email && <p>✉ {c.email}</p>}
                  {c.invoiceEmail && <p className="text-neutral-400">📄 {c.invoiceEmail}</p>}
                  {!c.telephone && !c.mobile && !c.email && !c.invoiceEmail && <span className="italic 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 ${c.isActive ? "bg-success-100 text-success-700" : "bg-neutral-100 text-neutral-500"}`}>
                    {c.isActive ? "Active" : "Inactive"}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <CompanyActionsMenu company={c} />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
