"use client";

import {
  type WholesaleCustomer,
} from "@/actions/wholesale";
import { formatDate } from "@/lib/format-date";
import { AdminButton, AdminBadge } from "@/components/admin/design-system";

type CustomerListSectionProps = {
  customers: WholesaleCustomer[];
  selectedCustomers: Set<string>;
  allCustomerIds: string[];
  openCustomerActions: string | null;
  deletingCustomer: string | null;
  sendingPriceSheet: boolean;
  onToggle: (id: string) => void;
  onToggleAll: () => void;
  onToggleActions: (id: string) => void;
  onCloseActions: () => void;
  onEdit: (c: WholesaleCustomer) => void;
  onPricing: (c: WholesaleCustomer) => void;
  onDelete: (id: string) => void;
  onSendPriceSheet: (ids: string[]) => void;
};

export default function CustomerListSection({
  customers,
  selectedCustomers,
  allCustomerIds,
  openCustomerActions,
  deletingCustomer,
  sendingPriceSheet,
  onToggle,
  onToggleAll,
  onToggleActions,
  onCloseActions,
  onEdit,
  onPricing,
  onDelete,
  onSendPriceSheet,
}: CustomerListSectionProps) {
  return (
    <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">
              <input aria-label="Checkbox" type="checkbox" className="rounded border-[var(--admin-border)]"
                checked={selectedCustomers.size === customers.length && customers.length > 0}
                onChange={onToggleAll}
              />
            </th>
            <th className="px-5 py-3 font-semibold text-left">Company</th>
            <th className="px-5 py-3 font-semibold text-left">Contact</th>
            <th className="px-5 py-3 font-semibold text-left">Status</th>
            <th className="px-5 py-3 font-semibold text-left">Credit</th>
            <th className="px-5 py-3 font-semibold text-left">Deposits</th>
            <th className="px-5 py-3 font-semibold text-left">Created</th>
            <th className="px-5 py-3" aria-label="Actions"></th>
          </tr>
        </thead>
        <tbody className="divide-y divide-[var(--admin-border-light)]">
          {customers.length === 0 ? (
            <tr>
              <td colSpan={8} 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="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"/>
                    </svg>
                  </div>
                  <p className="text-sm font-semibold text-slate-600 mb-1">No customers yet</p>
                  <p className="text-xs text-slate-400">Wholesale customers will appear here once registered.</p>
                </div>
              </td>
            </tr>
          ) : customers.map(c => (
            <CustomerRow
              key={c.id}
              customer={c}
              isSelected={selectedCustomers.has(c.id)}
              isActionsOpen={openCustomerActions === c.id}
              isDeleting={deletingCustomer === c.id}
              onToggle={() => onToggle(c.id)}
              onToggleActions={() => onToggleActions(c.id)}
              onCloseActions={onCloseActions}
              onEdit={() => onEdit(c)}
              onPricing={() => onPricing(c)}
              onDelete={() => onDelete(c.id)}
              onSendPriceSheet={() => onSendPriceSheet([c.id])}
            />
          ))}
        </tbody>
        {selectedCustomers.size > 0 && (
          <tfoot className="bg-[var(--admin-accent-light)] border-t border-[var(--admin-accent)]">
            <tr>
              <td colSpan={8} className="px-5 py-3 flex items-center gap-4">
                <span className="text-sm text-[var(--admin-accent-text)] font-medium">{selectedCustomers.size} selected</span>
                <AdminButton
                  onClick={() => onSendPriceSheet(allCustomerIds.filter(id => selectedCustomers.has(id)))}
                  disabled={sendingPriceSheet}
                  variant="primary"
                  size="sm"
                  isLoading={sendingPriceSheet}
                >
                  {sendingPriceSheet ? "Sending..." : `Send Price Sheet to ${selectedCustomers.size} Customer(s)`}
                </AdminButton>
              </td>
            </tr>
          </tfoot>
        )}
      </table>
    </div>
  );
}

type CustomerRowProps = {
  customer: WholesaleCustomer;
  isSelected: boolean;
  isActionsOpen: boolean;
  isDeleting: boolean;
  onToggle: () => void;
  onToggleActions: () => void;
  onCloseActions: () => void;
  onEdit: () => void;
  onPricing: () => void;
  onDelete: () => void;
  onSendPriceSheet: () => void;
};

function CustomerRow({
  customer: c,
  isSelected,
  isActionsOpen,
  isDeleting,
  onToggle,
  onToggleActions,
  onCloseActions,
  onEdit,
  onPricing,
  onDelete,
  onSendPriceSheet,
}: CustomerRowProps) {
  return (
    <tr className="hover:bg-[var(--admin-bg-subtle)]">
      <td className="px-5 py-3">
        <input aria-label="Checkbox" type="checkbox" className="rounded border-[var(--admin-border)]"
          checked={isSelected}
          onChange={onToggle}
        />
      </td>
      <td className="px-5 py-3 font-medium text-[var(--admin-text-primary)]">{c.company_name ?? "—"}</td>
      <td className="px-5 py-3 text-[var(--admin-text-secondary)]">{c.contact_name ?? "—"}<br/><span className="text-xs text-[var(--admin-text-muted)]">{c.email}</span></td>
      <td className="px-5 py-3">
        <AdminBadge variant={c.account_status === "active" ? "success" : c.account_status === "on_hold" ? "warning" : "danger"}>
          {c.account_status}
        </AdminBadge>
      </td>
      <td className="px-5 py-3 text-[var(--admin-text-secondary)]">
        {c.credit_limit <= 0 ? "Unlimited" : `$${Number(c.credit_limit).toFixed(2)}`}
      </td>
      <td className="px-5 py-3 text-[var(--admin-text-secondary)]">
        {c.deposits_enabled ? `${c.deposit_percentage}%` : "—"}
      </td>
      <td className="px-5 py-3 text-[var(--admin-text-muted)] text-xs">{formatDate(new Date(c.created_at))}</td>
      <td className="px-5 py-4 customer-actions-cell relative">
        <div className="flex items-center gap-1.5">
          <button type="button"
            onClick={onSendPriceSheet}
            title="Send price sheet"
            aria-label="Send price sheet"
            className="inline-flex items-center justify-center rounded-xl w-9 h-9 text-[var(--admin-accent)] hover:text-[var(--admin-accent-text)] hover:bg-[var(--admin-accent-light)] transition-colors"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
          </button>
          <div className="relative">
            <button type="button"
              onClick={onToggleActions}
              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>
            {isActionsOpen && (
              <div
                className="absolute bottom-full right-0 mb-1 z-30 w-52 rounded-xl bg-white shadow-xl ring-1 ring-[var(--admin-border)] py-1 text-sm"
                onClick={e => e.stopPropagation()}
              >
                <button type="button"
                  onClick={() => { onCloseActions(); onEdit(); }}
                  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 Customer
                </button>
                <button type="button"
                  onClick={() => { onCloseActions(); onPricing(); }}
                  className="w-full text-left px-4 py-3 text-[var(--admin-text-secondary)] hover:bg-[var(--admin-bg-subtle)] flex items-center gap-3"
                >
                  <svg className="w-4 h-4 text-[var(--admin-text-muted)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                  Pricing
                </button>
                <a
                  href={`/wholesale/portal?preview_customer_id=${c.id}&_admin_preview=1`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-full text-left px-4 py-3 text-[var(--admin-text-secondary)] hover:bg-[var(--admin-bg-subtle)] flex items-center gap-3"
                >
                  <svg className="w-4 h-4 text-[var(--admin-text-muted)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                  View Portal As
                </a>
                <div className="my-1 border-t border-[var(--admin-border)]" />
                <button type="button"
                  onClick={() => { onCloseActions(); onDelete(); }}
                  disabled={isDeleting}
                  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>
                  {isDeleting ? "Deleting..." : "Delete Customer"}
                </button>
              </div>
            )}
          </div>
        </div>
      </td>
    </tr>
  );
}
