'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Alert, App, Button, DatePicker, Dropdown, Empty, Input, Segmented, Select, Skeleton, Tooltip } from 'antd';
import dayjs from 'dayjs';
import { Icon } from '../ui/Icon';
import { usePermissions } from '../../lib/usePermissions';
import { UserAvatar } from '../ui/UserAvatar';
import { FilterTabsBar, PageHeader, TablePager } from '../platform/PlatformPrimitives';
import { fmtDate } from '../platform/platformFormat';
import { ApiError } from '../../lib/api';
import { LEAD_VIEWS, STATUS_LABEL, inr, leadsApi, notifyLeadsChanged, type DirectoryUser, type FollowUpFilter, type Lead, type LeadPage, type LeadSort, type LeadStatus, type LeadView } from '../../lib/leads';
import { servicesApi } from '../../lib/services';
import type { AuthUser } from '../../context/AuthContext';
import { LeadStatusBadge } from './LeadBits';
import { LeadFormModal } from './LeadFormModal';
import { LeadConvertModal } from './LeadConvertModal';
import { formatFollowUpBadge } from './LeadDetails';
import { useDeleteLead } from './useDeleteLead';
import { ModuleImportModal } from '../crm/ModuleImportModal';
import { dataOpsApi } from '../../lib/data-ops';
import { useCrmOptions } from '../../lib/options';

const { RangePicker } = DatePicker;

const COLUMNS: Array<{ key: LeadSort; label: string; right?: boolean }> = [
  { key: 'name', label: 'Name' },
  { key: 'serviceInterest', label: 'Service' },
  { key: 'status', label: 'Status' },
  { key: 'nextFollowUpAt', label: 'Follow-up' },
  { key: 'source', label: 'Source' },
  { key: 'owner', label: 'Owner' },
  { key: 'estimatedValue', label: 'Est. value', right: true },
  { key: 'createdAt', label: 'Added' },
];

const STATUS_COLOR: Record<LeadStatus, string> = {
  NEW: '#3b82f6',
  CONTACTED: '#6366f1',
  QUALIFIED: '#10b981',
  NURTURING: '#f59e0b',
  UNQUALIFIED: '#64748b',
  CONVERTED: '#8b5cf6',
};

/**
 * Leads page: consistent CRM toolbar, grouped actions (Export & Import together),
 * structured filter panel, standard Table & Kanban Board views.
 */
export function LeadsListView({ user }: { user: AuthUser }) {
  const router = useRouter();
  const [layoutMode, setLayoutMode] = useState<'table' | 'board'>('table');
  const [showFilters, setShowFilters] = useState(false);
  const [view, setView] = useState<LeadView>('all');
  const [search, setSearch] = useState('');
  const [q, setQ] = useState('');
  const [status, setStatus] = useState<LeadStatus | undefined>();
  const [source, setSource] = useState<string | undefined>();
  const [service, setService] = useState<string | undefined>();
  const [ownerId, setOwnerId] = useState<string | undefined>();
  const [followUp, setFollowUp] = useState<FollowUpFilter | undefined>();
  const [createdRange, setCreatedRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null] | null>(null);

  const [sort, setSort] = useState<{ key: LeadSort; dir: 'asc' | 'desc' }>({
    key: 'createdAt',
    dir: 'desc',
  });
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [reload, setReload] = useState(0);

  const [data, setData] = useState<LeadPage | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [people, setPeople] = useState<DirectoryUser[]>([]);
  const options = useCrmOptions();
  const sourceOptions = options.leadSources.map((s) => ({ value: s, label: s }));
  const [services, setServices] = useState<string[]>([]);

  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<Lead | null>(null);
  const [defaultCreateStatus, setDefaultCreateStatus] = useState<LeadStatus | undefined>();
  const [convertingLead, setConvertingLead] = useState<Lead | null>(null);
  const [convertOpen, setConvertOpen] = useState(false);

  // Drag and drop state for Kanban
  const [dragId, setDragId] = useState<string | null>(null);
  const [overStatus, setOverStatus] = useState<LeadStatus | null>(null);
  const [flashId, setFlashId] = useState<string | null>(null);

  const deleteLead = useDeleteLead();
  const { message } = App.useApp();
  const { can } = usePermissions();
  const canCreate = can('leads', 'create');
  const canEdit = can('leads', 'update');
  const mayDelete = can('leads', 'delete');
  const canExport = can('data_ops', 'export');
  const canImport = can('data_ops', 'create');
  const [importOpen, setImportOpen] = useState(false);
  const [exporting, setExporting] = useState(false);

  const getActiveFilters = useCallback(() => {
    const createdFrom = createdRange?.[0] ? createdRange[0].startOf('day').toISOString() : undefined;
    const createdTo = createdRange?.[1] ? createdRange[1].endOf('day').toISOString() : undefined;
    return {
      view,
      q,
      status,
      source,
      service,
      ownerId,
      followUp: followUp && followUp !== 'all' ? followUp : undefined,
      createdFrom,
      createdTo,
    };
  }, [view, q, status, source, service, ownerId, followUp, createdRange]);

  const handleExport = async () => {
    setExporting(true);
    try {
      await dataOpsApi.exportExcel('leads', getActiveFilters());
      message.success('Leads exported to Excel successfully');
    } catch (err) {
      message.error((err as Error).message || 'Export failed');
    } finally {
      setExporting(false);
    }
  };

  const handleExportPdf = async () => {
    setExporting(true);
    try {
      await dataOpsApi.exportPdf('leads', getActiveFilters());
      message.success('Leads PDF report downloaded successfully');
    } catch (err) {
      message.error((err as Error).message || 'PDF export failed');
    } finally {
      setExporting(false);
    }
  };

  // Search waits for a short pause in typing.
  useEffect(() => {
    const t = setTimeout(() => {
      setQ(search.trim());
      setPage(1);
    }, 300);
    return () => clearTimeout(t);
  }, [search]);

  useEffect(() => {
    let active = true;
    const load = async () => {
      await Promise.resolve();
      if (!active) return;
      setLoading(true);
      try {
        const d = await leadsApi.list({
          view,
          q,
          status,
          source,
          serviceInterest: service,
          ownerId,
          followUp,
          createdFrom: createdRange?.[0] ? createdRange[0].startOf('day').toISOString() : undefined,
          createdTo: createdRange?.[1] ? createdRange[1].endOf('day').toISOString() : undefined,
          sort: sort.key,
          dir: sort.dir,
          page: layoutMode === 'board' ? 1 : page,
          pageSize: layoutMode === 'board' ? 100 : pageSize,
        });
        if (!active) return;
        setData(d);
        setError(null);
      } catch (err) {
        if (!active) return;
        setError(err instanceof ApiError ? err.message : 'Leads could not be loaded.');
      } finally {
        if (active) setLoading(false);
      }
    };
    void load();
    return () => {
      active = false;
    };
  }, [view, q, status, source, service, ownerId, followUp, createdRange, sort, page, pageSize, reload, layoutMode]);

  useEffect(() => {
    leadsApi
      .directory()
      .then(setPeople)
      .catch(() => setPeople([]));
    servicesApi
      .list()
      .then((records) => setServices(records.map((r) => r.name)))
      .catch(() => setServices([]));
  }, []);

  useEffect(() => {
    const onChanged = () => setReload((n) => n + 1);
    window.addEventListener('tcx:leads-changed', onChanged);
    return () => window.removeEventListener('tcx:leads-changed', onChanged);
  }, []);

  const activeFilterCount = [Boolean(status), Boolean(service), Boolean(source), Boolean(ownerId), Boolean(followUp), Boolean(createdRange)].filter(Boolean).length;

  const filtered = activeFilterCount > 0;

  const clearFilters = useCallback(() => {
    setStatus(undefined);
    setSource(undefined);
    setService(undefined);
    setOwnerId(undefined);
    setFollowUp(undefined);
    setCreatedRange(null);
    setPage(1);
  }, []);

  const toggleSort = (key: LeadSort) => {
    setSort((s) =>
      s.key === key
        ? { key, dir: s.dir === 'asc' ? 'desc' : 'asc' }
        : {
            key,
            dir: key === 'name' || key === 'source' || key === 'owner' ? 'asc' : 'desc',
          },
    );
    setPage(1);
  };

  const openCreate = (initialStatus?: LeadStatus) => {
    setEditing(null);
    setDefaultCreateStatus(initialStatus);
    setFormOpen(true);
  };

  const moveLeadToStatus = async (lead: Lead, newStatus: LeadStatus) => {
    if (lead.status === newStatus) return;
    try {
      await leadsApi.update(lead.id, { status: newStatus });
      setFlashId(lead.id);
      message.success(`${lead.name} moved to ${STATUS_LABEL[newStatus]}`);
      setReload((n) => n + 1);
      notifyLeadsChanged();
      setTimeout(() => setFlashId(null), 1200);
    } catch (err) {
      message.error((err as Error).message || 'Failed to update status');
    }
  };

  const counts = data?.counts;
  const subtitle = 'Capture, qualify, and nurture prospects to convert them into high-value sales opportunities.';

  const tabs = useMemo(
    () =>
      LEAD_VIEWS.map((v) => ({
        key: v.key,
        label: v.label,
        count: counts?.[v.key],
      })),
    [counts],
  );

  const kanbanStatuses = useMemo<LeadStatus[]>(() => {
    if (view === 'converted') return ['CONVERTED'];
    if (view === 'all') return ['NEW', 'CONTACTED', 'NURTURING', 'QUALIFIED', 'UNQUALIFIED', 'CONVERTED'];
    return ['NEW', 'CONTACTED', 'NURTURING', 'QUALIFIED', 'UNQUALIFIED'];
  }, [view]);

  const maxColumnSum = useMemo(() => {
    if (!data?.items) return 1;
    const sums = kanbanStatuses.map((st) => data.items.filter((l) => l.status === st).reduce((acc, l) => acc + (l.estimatedValue || 0), 0));
    return Math.max(1, ...sums);
  }, [data, kanbanStatuses]);

  return (
    <div>
      <PageHeader eyebrow="Sales" title="Leads" subtitle={subtitle} />

      <FilterTabsBar
        tabs={tabs}
        activeKey={view}
        onChange={(k) => {
          setView(k as LeadView);
          setPage(1);
        }}
      />

      {/* Standard CRM Toolbar matching all other pages */}
      <div className="mb-4 flex flex-wrap items-center gap-2.5">
        <Input allowClear prefix={<Icon name="search" size={15} />} placeholder="Search leads" aria-label="Search leads" value={search} onChange={(e) => setSearch(e.target.value)} className="w-full sm:!w-[280px]" />

        <Button icon={<Icon name="filter" size={14} />} onClick={() => setShowFilters((prev) => !prev)}>
          Filters {activeFilterCount > 0 ? `(${activeFilterCount})` : ''}
        </Button>

        {filtered ? (
          <Button type="text" size="small" onClick={clearFilters}>
            Clear filters
          </Button>
        ) : null}

        <div className="flex-1" />

        {/* Action Buttons in logical order: View Toggle -> Export -> Import -> New Lead */}
        <Segmented
          value={layoutMode}
          onChange={(val) => setLayoutMode(val as 'table' | 'board')}
          options={[
            { value: 'table', label: 'Table', icon: <Icon name="list" size={14} /> },
            { value: 'board', label: 'Board', icon: <Icon name="pipeline" size={14} /> },
          ]}
        />

        <Tooltip title={canExport ? undefined : 'Your role does not allow exporting. Ask your organization admin.'}>
          <span className="inline-flex">
            <Dropdown
              disabled={!canExport}
              menu={{
                items: [
                  {
                    key: 'excel',
                    label: 'Export to Excel (.xlsx)',
                    icon: <Icon name="download" size={14} />,
                    disabled: !canExport || exporting,
                    onClick: () => void handleExport(),
                  },
                  {
                    key: 'pdf',
                    label: 'Export to PDF (.pdf)',
                    icon: <Icon name="download" size={14} />,
                    disabled: !canExport || exporting,
                    onClick: () => void handleExportPdf(),
                  },
                ],
              }}
            >
              <Button icon={<Icon name="download" size={15} />} loading={exporting} disabled={!canExport}>
                Export ▾
              </Button>
            </Dropdown>
          </span>
        </Tooltip>

        <Tooltip title={canImport ? undefined : 'Your role does not allow importing. Ask your organization admin.'}>
          <Button icon={<Icon name="upload" size={15} />} disabled={!canImport} onClick={() => setImportOpen(true)}>
            Import
          </Button>
        </Tooltip>

        {canCreate ? (
          <Button type="primary" icon={<Icon name="plus" size={16} />} onClick={() => openCreate()}>
            New lead
          </Button>
        ) : null}
      </div>

      {/* Structured "Filter by" Panel in equal-width 4-column grid */}
      {showFilters ? (
        <div className="tcx-surface-card p-4 mb-4">
          <div className="flex items-center justify-between mb-2.5">
            <span className="text-[11.5px] font-bold text-[var(--tcx-muted)] uppercase tracking-wider">Filter by</span>
            {filtered ? (
              <Button type="link" size="small" onClick={clearFilters} className="!p-0 text-xs">
                Clear all filters
              </Button>
            ) : null}
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
            <div>
              <Select
                aria-label="Status"
                placeholder="All Statuses"
                allowClear
                popupMatchSelectWidth={false}
                value={status}
                onChange={(v) => {
                  setStatus(v);
                  setPage(1);
                }}
                className="w-full"
                options={(Object.keys(STATUS_LABEL) as LeadStatus[]).map((s) => ({
                  value: s,
                  label: STATUS_LABEL[s],
                }))}
              />
            </div>
            <div>
              <Select
                aria-label="Service"
                placeholder="All Services"
                allowClear
                popupMatchSelectWidth={false}
                value={service}
                onChange={(v) => {
                  setService(v);
                  setPage(1);
                }}
                className="w-full"
                options={services.map((s) => ({ value: s, label: s }))}
              />
            </div>
            <div>
              <Select
                aria-label="Source"
                placeholder="All Sources"
                allowClear
                popupMatchSelectWidth={false}
                value={source}
                onChange={(v) => {
                  setSource(v);
                  setPage(1);
                }}
                className="w-full"
                options={sourceOptions}
              />
            </div>
            <div>
              <Select
                aria-label="Owner"
                placeholder="All Owners"
                allowClear
                popupMatchSelectWidth={false}
                value={ownerId}
                onChange={(v) => {
                  setOwnerId(v);
                  setPage(1);
                }}
                className="w-full"
                options={people.map((p) => ({ value: p.id, label: p.name }))}
              />
            </div>
          </div>

          <div className="mt-3 pt-3 border-t border-[var(--tcx-border)]">
            <span className="block text-[11px] font-bold text-[var(--tcx-muted)] uppercase tracking-wider mb-2">Dates & Timeline</span>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
              <div>
                <Select
                  aria-label="Follow-up Timeline"
                  placeholder="All Follow-ups"
                  allowClear
                  popupMatchSelectWidth={false}
                  value={followUp}
                  onChange={(v) => {
                    setFollowUp(v);
                    setPage(1);
                  }}
                  className="w-full"
                  options={[
                    { value: 'all', label: 'All Follow-ups' },
                    { value: 'overdue', label: 'Overdue' },
                    { value: 'today', label: 'Due Today' },
                    { value: 'this_week', label: 'This Week' },
                    { value: 'upcoming', label: 'Upcoming' },
                  ]}
                />
              </div>
              <div className="sm:col-span-1 lg:col-span-2">
                <RangePicker
                  placeholder={['Created from', 'Created to']}
                  value={createdRange}
                  onChange={(dates) => {
                    setCreatedRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null] | null);
                    setPage(1);
                  }}
                  className="w-full"
                />
              </div>
            </div>
          </div>
        </div>
      ) : null}

      {/* Main Content: Table or Kanban Board (Standard CRM Cards) */}
      {layoutMode === 'board' ? (
        <div>
          {error ? (
            <Alert type="error" showIcon title={error} />
          ) : loading && !data ? (
            <div className="tcx-surface-card p-6">
              <Skeleton active paragraph={{ rows: 8 }} />
            </div>
          ) : (
            <div className="tcx-kanban">
              {kanbanStatuses.map((st, colIdx) => {
                const color = STATUS_COLOR[st];
                const columnLeads = (data?.items || []).filter((l) => l.status === st);
                const columnSum = columnLeads.reduce((acc, l) => acc + (l.estimatedValue || 0), 0);
                const pct = Math.min(100, Math.round((columnSum / maxColumnSum) * 100));

                return (
                  <section key={st} className="tcx-kcol" aria-label={`${STATUS_LABEL[st]} status`}>
                    <div className="tcx-kcol-head">
                      <div className="tcx-kcol-title">
                        <i className="tcx-kcol-dot" style={{ background: color }} aria-hidden="true" />
                        <span>{STATUS_LABEL[st]}</span>
                        <span className="tcx-kcol-count">{columnLeads.length}</span>
                        {st !== 'CONVERTED' && canCreate ? <Button size="small" type="text" className="!ml-auto" aria-label={`Add lead to ${STATUS_LABEL[st]}`} icon={<Icon name="plus" size={13} />} onClick={() => openCreate(st)} /> : null}
                      </div>
                      <div className="tcx-kcol-sum">
                        <b>{inr(columnSum)}</b> · {columnLeads.length} {columnLeads.length === 1 ? 'lead' : 'leads'}
                      </div>
                      <div className="tcx-kcol-prog" aria-hidden="true">
                        <i
                          style={{
                            width: `${columnLeads.length ? Math.max(8, pct) : 0}%`,
                            background: color,
                          }}
                        />
                      </div>
                    </div>

                    <div
                      className={`tcx-kcol-body ${overStatus === st ? 'over' : ''}`}
                      onDragOver={(e) => {
                        if (!dragId) return;
                        e.preventDefault();
                        e.dataTransfer.dropEffect = 'move';
                        if (overStatus !== st) setOverStatus(st);
                      }}
                      onDragLeave={(e) => {
                        if (!e.currentTarget.contains(e.relatedTarget as Node)) {
                          setOverStatus((cur) => (cur === st ? null : cur));
                        }
                      }}
                      onDrop={(e) => {
                        e.preventDefault();
                        const droppedId = e.dataTransfer.getData('text/plain') || dragId;
                        setOverStatus(null);
                        setDragId(null);
                        if (!droppedId) return;
                        const found = data?.items.find((l) => l.id === droppedId);
                        if (found && found.status !== st) {
                          if (st === 'CONVERTED') {
                            if (found.status === 'UNQUALIFIED') {
                              message.warning('Dropped leads cannot be converted to customer');
                              return;
                            }
                            setConvertingLead(found);
                            setConvertOpen(true);
                            return;
                          }
                          void moveLeadToStatus(found, st);
                        }
                      }}
                    >
                      {columnLeads.length === 0 ? (
                        <div className="tcx-kcol-empty">Drop lead here</div>
                      ) : (
                        columnLeads.map((lead) => (
                          <div
                            key={lead.id}
                            role="button"
                            tabIndex={0}
                            draggable={lead.status !== 'CONVERTED' && canEdit}
                            onDragStart={(e) => {
                              setDragId(lead.id);
                              e.dataTransfer.effectAllowed = 'move';
                              e.dataTransfer.setData('text/plain', lead.id);
                            }}
                            onDragEnd={() => {
                              setDragId(null);
                              setOverStatus(null);
                            }}
                            onClick={() => router.push(`/app/leads/${lead.id}`)}
                            onKeyDown={(e) => {
                              if (e.key === 'Enter' || e.key === ' ') {
                                e.preventDefault();
                                router.push(`/app/leads/${lead.id}`);
                                return;
                              }
                              if (e.shiftKey && (e.key === 'ArrowRight' || e.key === 'ArrowLeft')) {
                                e.preventDefault();
                                const nextIdx = e.key === 'ArrowRight' ? Math.min(kanbanStatuses.length - 1, colIdx + 1) : Math.max(0, colIdx - 1);
                                const nextSt = kanbanStatuses[nextIdx];
                                if (nextSt && nextSt !== lead.status) {
                                  if (nextSt === 'CONVERTED') {
                                    if (lead.status === 'UNQUALIFIED') {
                                      message.warning('Dropped leads cannot be converted to customer');
                                      return;
                                    }
                                    setConvertingLead(lead);
                                    setConvertOpen(true);
                                    return;
                                  }
                                  void moveLeadToStatus(lead, nextSt);
                                }
                              }
                            }}
                            className={`tcx-kcard text-left ${dragId === lead.id ? 'dragging' : ''} ${flashId === lead.id ? 'flash' : ''}`}
                          >
                            <div className="flex items-start justify-between gap-2">
                              <div className="min-w-0">
                                <div className="truncate font-semibold leading-snug text-[var(--tcx-text)]">{lead.name}</div>
                                {lead.company ? <div className="mt-0.5 truncate text-[12px] text-[var(--tcx-muted)]">{lead.company}</div> : null}
                              </div>
                            </div>

                            {lead.serviceInterest ? (
                              <div>
                                <span className="inline-block max-w-full truncate rounded bg-[var(--tcx-surface-2)] px-2 py-0.5 text-[11px] font-medium text-[var(--tcx-text)]">{lead.serviceInterest}</span>
                              </div>
                            ) : null}

                            <div className="flex items-center justify-between gap-2">
                              <span className="tcx-kcard-amt">{inr(lead.estimatedValue)}</span>
                              {lead.nextFollowUpAt ? <div className="text-[11px] leading-tight">{formatFollowUpBadge(lead.nextFollowUpAt)}</div> : null}
                            </div>

                            <div className="flex items-center justify-between gap-2 text-[12px] text-[var(--tcx-muted)]">
                              <span className="inline-flex min-w-0 items-center gap-1.5 truncate">
                                {lead.owner ? (
                                  <>
                                    <UserAvatar name={lead.owner.name} size={18} />
                                    <span className="truncate">{lead.owner.name}</span>
                                  </>
                                ) : (
                                  'Unassigned'
                                )}
                              </span>
                              <span className="shrink-0 text-[11px] text-[var(--tcx-muted)]">{lead.source ?? fmtDate(lead.createdAt)}</span>
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  </section>
                );
              })}
            </div>
          )}
        </div>
      ) : (
        /* Standard Table View - Clean and Consistent with the rest of CRM */
        <div className="tcx-surface-card overflow-hidden">
          {error ? (
            <div className="p-6">
              <Alert
                type="error"
                showIcon
                title={error}
                action={
                  <Button size="small" onClick={() => setReload((n) => n + 1)}>
                    Retry
                  </Button>
                }
              />
            </div>
          ) : !data ? (
            <div className="p-6">
              <Skeleton active paragraph={{ rows: 8 }} />
            </div>
          ) : data.items.length === 0 ? (
            <div className="py-14">
              {filtered || q || view !== 'all' ? (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={
                    <span>
                      <b className="block text-[var(--tcx-text)]">No leads match</b>
                      Try a different search term, or clear the filters to see everything.
                    </span>
                  }
                >
                  {filtered || q ? (
                    <Button
                      onClick={() => {
                        setSearch('');
                        clearFilters();
                      }}
                    >
                      Clear filters
                    </Button>
                  ) : null}
                </Empty>
              ) : (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={
                    <span>
                      <b className="block text-[var(--tcx-text)]">No leads yet</b>
                      Leads are people who might buy. Add your first one.
                    </span>
                  }
                >
                  {canCreate ? (
                    <Button type="primary" icon={<Icon name="plus" size={16} />} onClick={() => openCreate()}>
                      New lead
                    </Button>
                  ) : null}
                </Empty>
              )}
            </div>
          ) : (
            <>
              <div className="tcx-table-scroll" aria-busy={loading}>
                <table className={`tcx-table ${loading ? 'opacity-60' : ''}`}>
                  <thead>
                    <tr>
                      {COLUMNS.map((c) => {
                        const on = sort.key === c.key;
                        return (
                          <th key={c.key} className={c.right ? 'tcx-right' : undefined} aria-sort={on ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'}>
                            <button type="button" className="tcx-th-sort" onClick={() => toggleSort(c.key)}>
                              {c.label}
                              {on ? <Icon name="chevronDown" size={12} className={sort.dir === 'asc' ? 'rotate-180' : ''} /> : null}
                            </button>
                          </th>
                        );
                      })}
                      <th className="tcx-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.items.map((l) => (
                      <tr
                        key={l.id}
                        className="tcx-row-click"
                        tabIndex={0}
                        onClick={() => router.push(`/app/leads/${l.id}`)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') router.push(`/app/leads/${l.id}`);
                        }}
                      >
                        <td>
                          <div className="flex items-center gap-3">
                            <UserAvatar name={l.name} size={30} />
                            <div className="min-w-0">
                              <Link href={`/app/leads/${l.id}`} onClick={(e) => e.stopPropagation()} className="truncate font-semibold text-[var(--tcx-text)] hover:text-[var(--tcx-primary)]">
                                {l.name}
                              </Link>
                              {l.company ? <div className="truncate text-[12.5px] text-[var(--tcx-muted)]">{l.company}</div> : null}
                              {l.nextFollowUpAt ? <div className="mt-0.5 text-[11px] leading-tight">{formatFollowUpBadge(l.nextFollowUpAt)}</div> : null}
                            </div>
                          </div>
                        </td>
                        <td>{l.serviceInterest ? <span className="inline-block max-w-[150px] truncate rounded bg-[var(--tcx-surface-2)] px-2 py-0.5 text-[12px] font-medium text-[var(--tcx-text)]">{l.serviceInterest}</span> : <span className="text-[var(--tcx-muted)]">—</span>}</td>
                        <td onClick={(e) => e.stopPropagation()}>
                          {l.status === 'CONVERTED' || !canEdit ? (
                            <LeadStatusBadge status={l.status} />
                          ) : (
                            <Select<LeadStatus>
                              size="small"
                              value={l.status}
                              className="w-[180px]"
                              onChange={(val) => {
                                if (val === 'CONVERTED') {
                                  if (l.status === 'UNQUALIFIED') {
                                    message.warning('Dropped leads cannot be converted to customer');
                                    return;
                                  }
                                  setConvertingLead(l);
                                  setConvertOpen(true);
                                  return;
                                }
                                void moveLeadToStatus(l, val);
                              }}
                              options={[
                                {
                                  value: 'NEW',
                                  label: (
                                    <span className="inline-flex items-center gap-1.5 text-[12px]">
                                      <span className="h-2 w-2 rounded-full" style={{ background: STATUS_COLOR.NEW }} />
                                      {STATUS_LABEL.NEW}
                                    </span>
                                  ),
                                },
                                {
                                  value: 'CONTACTED',
                                  label: (
                                    <span className="inline-flex items-center gap-1.5 text-[12px]">
                                      <span className="h-2 w-2 rounded-full" style={{ background: STATUS_COLOR.CONTACTED }} />
                                      {STATUS_LABEL.CONTACTED}
                                    </span>
                                  ),
                                },
                                {
                                  value: 'NURTURING',
                                  label: (
                                    <span className="inline-flex items-center gap-1.5 text-[12px]">
                                      <span className="h-2 w-2 rounded-full" style={{ background: STATUS_COLOR.NURTURING }} />
                                      {STATUS_LABEL.NURTURING}
                                    </span>
                                  ),
                                },
                                {
                                  value: 'QUALIFIED',
                                  label: (
                                    <span className="inline-flex items-center gap-1.5 text-[12px]">
                                      <span className="h-2 w-2 rounded-full" style={{ background: STATUS_COLOR.QUALIFIED }} />
                                      {STATUS_LABEL.QUALIFIED}
                                    </span>
                                  ),
                                },
                                {
                                  value: 'UNQUALIFIED',
                                  label: (
                                    <span className="inline-flex items-center gap-1.5 text-[12px]">
                                      <span className="h-2 w-2 rounded-full" style={{ background: STATUS_COLOR.UNQUALIFIED }} />
                                      {STATUS_LABEL.UNQUALIFIED}
                                    </span>
                                  ),
                                },
                                {
                                  value: 'CONVERTED',
                                  label: (
                                    <span className="inline-flex items-center gap-1.5 font-medium text-[var(--tcx-primary)] text-[12px]">
                                      <span className="h-2 w-2 rounded-full" style={{ background: STATUS_COLOR.CONVERTED }} />
                                      Convert to Customer…
                                    </span>
                                  ),
                                },
                              ]}
                            />
                          )}
                        </td>
                        <td className="whitespace-nowrap">{formatFollowUpBadge(l.nextFollowUpAt)}</td>
                        <td className="text-[var(--tcx-muted)] max-w-[180px] truncate" title={l.source ?? undefined}>
                          {l.source ?? '—'}
                        </td>
                        <td>
                          {l.owner ? (
                            <span className="inline-flex items-center gap-2 whitespace-nowrap">
                              <UserAvatar name={l.owner.name} size={22} />
                              {l.owner.name.split(/\s+/)[0]}
                            </span>
                          ) : (
                            <span className="text-[var(--tcx-muted)]">Unassigned</span>
                          )}
                        </td>
                        <td className="tcx-right tabular-nums">{inr(l.estimatedValue)}</td>
                        <td className="whitespace-nowrap text-[var(--tcx-muted)]">{fmtDate(l.createdAt)}</td>
                        <td className="tcx-right whitespace-nowrap" onClick={(e) => e.stopPropagation()}>
                          <div className="inline-flex items-center gap-1">
                            <Tooltip title="View details">
                              <Button type="text" size="small" aria-label={`View ${l.name}`} icon={<Icon name="eye" size={14} />} onClick={() => router.push(`/app/leads/${l.id}`)} />
                            </Tooltip>
                            {canEdit ? (
                              <Tooltip title="Edit lead">
                                <Button
                                  type="text"
                                  size="small"
                                  aria-label={`Edit ${l.name}`}
                                  icon={<Icon name="edit" size={14} />}
                                  onClick={() => {
                                    setEditing(l);
                                    setFormOpen(true);
                                  }}
                                />
                              </Tooltip>
                            ) : null}
                            {l.status !== 'CONVERTED' && l.status !== 'UNQUALIFIED' && canEdit ? (
                              <Tooltip title="Convert to Customer">
                                <Button
                                  type="text"
                                  size="small"
                                  aria-label={`Convert ${l.name}`}
                                  icon={<Icon name="userPlus" size={14} />}
                                  className="text-emerald-600 dark:text-emerald-400"
                                  onClick={() => {
                                    setConvertingLead(l);
                                    setConvertOpen(true);
                                  }}
                                />
                              </Tooltip>
                            ) : null}
                            {mayDelete ? (
                              <Tooltip title="Delete lead">
                                <Button
                                  type="text"
                                  size="small"
                                  danger
                                  aria-label={`Delete ${l.name}`}
                                  icon={<Icon name="trash" size={14} />}
                                  onClick={async () => {
                                    if (await deleteLead(l)) {
                                      setReload((n) => n + 1);
                                    }
                                  }}
                                />
                              </Tooltip>
                            ) : null}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <TablePager page={data.page} pageSize={data.pageSize} total={data.total} onPageChange={setPage} onPageSizeChange={setPageSize} />
            </>
          )}
        </div>
      )}

      <LeadFormModal
        open={formOpen}
        lead={editing}
        defaultStatus={defaultCreateStatus}
        currentUserId={user.id}
        people={people}
        onClose={() => setFormOpen(false)}
        onSaved={(saved) => {
          setFormOpen(false);
          setReload((n) => n + 1);
          message.success(editing ? 'Changes saved' : `${saved.name} added`);
          notifyLeadsChanged();
        }}
      />

      <ModuleImportModal open={importOpen} entity="leads" entityTitle="Leads" onClose={() => setImportOpen(false)} onSuccess={() => setReload((n) => n + 1)} />

      {convertingLead ? (
        <LeadConvertModal
          open={convertOpen}
          lead={convertingLead}
          onClose={() => {
            setConvertOpen(false);
            setConvertingLead(null);
          }}
          onConverted={() => {
            setReload((n) => n + 1);
          }}
        />
      ) : null}
    </div>
  );
}
