'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';

const { RangePicker } = DatePicker;
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 { DEAL_VIEWS, DEALS_CHANGED_EVENT, STAGE_META, dealsApi, notifyDealsChanged, type Deal, type DealPage, type DealSort, type DealStage, type DealTabView } from '../../lib/deals';
import { notifyAccountsChanged } from '../../lib/accounts';
import { inr, inrFull, leadsApi, type DirectoryUser } from '../../lib/leads';
import type { AuthUser } from '../../context/AuthContext';
import { DealPulse, DealStageBadge, DealStatsStrip, useDeleteDeal } from './DealBits';
import { DealFormModal } from './DealFormModal';
import { DealLossModal } from './DealLossModal';
import { ModuleImportModal } from '../crm/ModuleImportModal';
import { dataOpsApi } from '../../lib/data-ops';
import { useCrmOptions } from '../../lib/options';

const COLUMNS: Array<{ key: DealSort; label: string }> = [
  { key: 'title', label: 'Deal' },
  { key: 'stage', label: 'Stage' },
  { key: 'stageChangedAt', label: 'Pulse' },
  { key: 'amount', label: 'Value' },
  { key: 'closeDate', label: 'Close date' },
  { key: 'createdAt', label: 'Created' },
  { key: 'owner', label: 'Owner' },
];

export function DealsListView({ user }: { user: AuthUser }) {
  const router = useRouter();
  const { message } = App.useApp();
  const { dealStages } = useCrmOptions();
  const stageValues = useMemo(() => dealStages.map((s) => s.value), [dealStages]);
  const stageProbability = (stage: DealStage) => dealStages.find((s) => s.value === stage)?.probability ?? 0;
  const [layoutMode, setLayoutMode] = useState<'table' | 'board'>('table');
  const [showFilters, setShowFilters] = useState(false);
  const [view, setView] = useState<DealTabView>('all');
  const [search, setSearch] = useState('');
  const [q, setQ] = useState('');
  const [stage, setStage] = useState<DealStage | undefined>();
  const [ownerId, setOwnerId] = useState<string | undefined>();
  const [createdRange, setCreatedRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null] | null>(null);
  const [closeDateRange, setCloseDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null] | null>(null);
  const [sort, setSort] = useState<{ key: DealSort; dir: 'asc' | 'desc' }>({
    key: 'createdAt',
    dir: 'desc',
  });
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  const [data, setData] = useState<DealPage | null>(null);
  const [people, setPeople] = useState<DirectoryUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [reload, setReload] = useState(0);

  const [dragId, setDragId] = useState<string | null>(null);
  const [overStage, setOverStage] = useState<DealStage | null>(null);
  const [flashId, setFlashId] = useState<string | null>(null);
  const [defaultStage, setDefaultStage] = useState<DealStage>('QUALIFICATION');
  const [lossDeal, setLossDeal] = useState<Deal | null>(null);

  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<Deal | null>(null);

  const { can } = usePermissions();
  const canCreate = can('deals', 'create');
  const canEdit = can('deals', 'update');
  const mayDelete = can('deals', 'delete');
  const canExport = can('data_ops', 'export');
  const canImport = can('data_ops', 'create');
  const [exporting, setExporting] = useState(false);
  const [importModalOpen, setImportModalOpen] = useState(false);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const sp = new URLSearchParams(window.location.search);
      if (sp.get('mode') === 'board' || sp.get('view') === 'board') {
        void Promise.resolve().then(() => setLayoutMode('board'));
      }
    }
  }, []);

  const getActiveFilters = useCallback(() => {
    const createdFrom = createdRange?.[0] ? createdRange[0].startOf('day').toISOString() : undefined;
    const createdTo = createdRange?.[1] ? createdRange[1].endOf('day').toISOString() : undefined;
    const closeDateFrom = closeDateRange?.[0] ? closeDateRange[0].startOf('day').toISOString() : undefined;
    const closeDateTo = closeDateRange?.[1] ? closeDateRange[1].endOf('day').toISOString() : undefined;
    return {
      view,
      q,
      stage,
      ownerId,
      createdFrom,
      createdTo,
      closeDateFrom,
      closeDateTo,
    };
  }, [view, q, stage, ownerId, createdRange, closeDateRange]);

  const handleExport = async () => {
    setExporting(true);
    try {
      await dataOpsApi.exportExcel('deals', getActiveFilters());
      message.success('Deals 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('deals', getActiveFilters());
      message.success('Deals PDF report downloaded successfully');
    } catch (err) {
      message.error((err as Error).message || 'PDF export failed');
    } finally {
      setExporting(false);
    }
  };

  useEffect(() => {
    const id = setTimeout(() => {
      const trimmed = search.trim();
      setQ((prev) => {
        if (prev !== trimmed) setPage(1);
        return trimmed;
      });
    }, 250);
    return () => clearTimeout(id);
  }, [search]);

  useEffect(() => {
    let active = true;
    const load = async () => {
      setLoading(true);
      setError(null);
      try {
        const createdFrom = createdRange?.[0] ? createdRange[0].startOf('day').toISOString() : undefined;
        const createdTo = createdRange?.[1] ? createdRange[1].endOf('day').toISOString() : undefined;
        const closeDateFrom = closeDateRange?.[0] ? closeDateRange[0].startOf('day').toISOString() : undefined;
        const closeDateTo = closeDateRange?.[1] ? closeDateRange[1].endOf('day').toISOString() : undefined;
        const isBoard = layoutMode === 'board';
        const res = await dealsApi.list({
          view: isBoard ? 'board' : view,
          q: q || undefined,
          stage: isBoard ? undefined : stage,
          ownerId,
          createdFrom,
          createdTo,
          closeDateFrom,
          closeDateTo,
          sort: isBoard ? 'stageChangedAt' : sort.key,
          dir: isBoard ? 'desc' : sort.dir,
          page: isBoard ? 1 : page,
          pageSize: isBoard ? 200 : pageSize,
        });
        if (!active) return;
        setData(res);
      } catch (err) {
        if (!active) return;
        setError(err instanceof ApiError ? err.message : 'Deals could not be loaded. Try again.');
      } finally {
        if (active) setLoading(false);
      }
    };
    void load();
    return () => {
      active = false;
    };
  }, [view, q, stage, ownerId, createdRange, closeDateRange, sort, page, pageSize, reload, layoutMode]);

  useEffect(() => {
    const refresh = () => setReload((n) => n + 1);
    window.addEventListener(DEALS_CHANGED_EVENT, refresh);
    return () => window.removeEventListener(DEALS_CHANGED_EVENT, refresh);
  }, []);

  useEffect(() => {
    leadsApi
      .directory()
      .then(setPeople)
      .catch(() => setPeople([]));
  }, []);

  const refreshAll = useCallback(() => {
    setReload((n) => n + 1);
  }, []);

  const deleteDeal = useDeleteDeal(refreshAll);

  const toggleSort = (key: DealSort) => {
    setPage(1);
    setSort((prev) => (prev.key === key ? { key, dir: prev.dir === 'asc' ? 'desc' : 'asc' } : { key, dir: key === 'amount' ? 'desc' : 'asc' }));
  };

  const moveDealToStage = async (deal: Deal, toStage: DealStage) => {
    if (deal.stage === toStage) return;
    if (toStage === 'CLOSED_LOST') {
      setLossDeal(deal);
      return;
    }

    const previousStage = deal.stage;
    setData((prev) =>
      prev
        ? {
            ...prev,
            items: prev.items.map((d) =>
              d.id === deal.id
                ? {
                    ...d,
                    stage: toStage,
                    probability: stageProbability(toStage),
                    weightedAmount: Math.round((d.amount * stageProbability(toStage)) / 100),
                    daysInStage: 0,
                  }
                : d,
            ),
          }
        : null,
    );
    setFlashId(deal.id);
    setTimeout(() => setFlashId((cur) => (cur === deal.id ? null : cur)), 900);

    try {
      await dealsApi.moveStage(deal.id, { stage: toStage });
      notifyDealsChanged();
      notifyAccountsChanged();
      message.success(`Moved ${deal.title} to ${STAGE_META[toStage].label}`);
      refreshAll();
    } catch (err) {
      setData((prev) =>
        prev
          ? {
              ...prev,
              items: prev.items.map((d) => (d.id === deal.id ? { ...d, stage: previousStage } : d)),
            }
          : null,
      );
      message.error(err instanceof ApiError ? err.message : 'Stage could not be updated.');
    }
  };

  const clearFilters = useCallback(() => {
    setSearch('');
    setQ('');
    setStage(undefined);
    setOwnerId(undefined);
    setCreatedRange(null);
    setCloseDateRange(null);
    setPage(1);
  }, []);

  const activeFilterCount = [Boolean(stage), Boolean(ownerId), Boolean(createdRange), Boolean(closeDateRange)].filter(Boolean).length;
  const filtered = activeFilterCount > 0 || Boolean(q);

  const tabs = useMemo(
    () =>
      DEAL_VIEWS.map((t) => ({
        key: t.key,
        label: t.label,
        count: data?.counts[t.key] ?? 0,
      })),
    [data],
  );

  const items = useMemo(() => data?.items ?? [], [data]);
  const total = data?.total ?? 0;

  const maxStageTotal = useMemo(() => {
    const totals = stageValues.map((st) => items.filter((d) => d.stage === st).reduce((acc, d) => acc + d.amount, 0));
    return Math.max(1, ...totals);
  }, [items, stageValues]);

  return (
    <div>
      <PageHeader eyebrow="Sales" title="Deals" subtitle="Track active revenue opportunities, stage velocity, and closed deals across your sales pipeline." />

      <DealStatsStrip stats={data?.stats ?? null} />

      {layoutMode === 'table' ? (
        <FilterTabsBar
          tabs={tabs}
          activeKey={view}
          onChange={(key) => {
            setView(key as DealTabView);
            setPage(1);
          }}
        />
      ) : null}

      {/* Standard CRM Toolbar matching Leads */}
      <div className="mb-4 flex flex-wrap items-center gap-2.5">
        <Input allowClear prefix={<Icon name="search" size={15} />} placeholder="Search deals, customers..." aria-label="Search deals" 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" />

        {/* View Toggle */}
        <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} /> },
          ]}
        />

        {/* Export dropdown */}
        <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={() => setImportModalOpen(true)}>
            Import
          </Button>
        </Tooltip>

        {canCreate ? (
          <Button
            type="primary"
            icon={<Icon name="plus" size={16} />}
            onClick={() => {
              setEditing(null);
              setDefaultStage('QUALIFICATION');
              setFormOpen(true);
            }}
          >
            New deal
          </Button>
        ) : null}
      </div>

      {/* Filter Panel */}
      {showFilters ? (
        <div className="tcx-surface-card p-4 mb-4">
          <div className="flex items-center justify-between mb-3">
            <span className="text-[11.5px] font-bold text-[var(--tcx-muted)] uppercase tracking-wider">Filter Deals</span>
            {filtered ? (
              <Button type="text" size="small" onClick={clearFilters} className="text-[12px] h-6 px-1">
                Clear all
              </Button>
            ) : null}
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
            <div>
              <label className="block text-[11px] font-medium text-[var(--tcx-muted)] mb-1">Stage</label>
              <Select
                aria-label="Stage"
                placeholder="All Stages"
                allowClear
                value={stage}
                onChange={(val) => {
                  setStage(val);
                  setPage(1);
                }}
                className="w-full"
                options={dealStages.map((st) => ({
                  value: st.value,
                  label: STAGE_META[st.value]?.label ?? st.label,
                }))}
              />
            </div>
            <div>
              <label className="block text-[11px] font-medium text-[var(--tcx-muted)] mb-1">Owner</label>
              <Select
                aria-label="Owner"
                placeholder="All Owners"
                allowClear
                showSearch
                optionFilterProp="label"
                value={ownerId}
                onChange={(val) => {
                  setOwnerId(val);
                  setPage(1);
                }}
                className="w-full"
                options={people.map((p) => ({ value: p.id, label: p.name }))}
              />
            </div>
            <div>
              <label className="block text-[11px] font-medium text-[var(--tcx-muted)] mb-1">Created Date</label>
              <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>
              <label className="block text-[11px] font-medium text-[var(--tcx-muted)] mb-1">Close Date</label>
              <RangePicker
                placeholder={['Close from', 'Close to']}
                value={closeDateRange}
                onChange={(dates) => {
                  setCloseDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null] | null);
                  setPage(1);
                }}
                className="w-full"
              />
            </div>
          </div>
        </div>
      ) : null}

      {layoutMode === 'board' ? (
        /* KANBAN BOARD VIEW */
        error ? (
          <Alert type="error" showIcon title={error} />
        ) : loading && items.length === 0 ? (
          <div className="tcx-surface-card p-6">
            <Skeleton active paragraph={{ rows: 8 }} />
          </div>
        ) : (
          <div className="tcx-kanban">
            {stageValues.map((st, stageIdx) => {
              const meta = STAGE_META[st];
              const columnDeals = items.filter((d) => d.stage === st);
              const columnSum = columnDeals.reduce((acc, d) => acc + d.amount, 0);
              const pct = Math.min(100, Math.round((columnSum / maxStageTotal) * 100));

              return (
                <section key={st} className="tcx-kcol" aria-label={`${meta.label} stage`}>
                  <div className="tcx-kcol-head">
                    <div className="tcx-kcol-title">
                      <i className="tcx-kcol-dot" style={{ background: meta.color }} aria-hidden="true" />
                      <span>{meta.label}</span>
                      <span className="tcx-kcol-count">{columnDeals.length}</span>
                      {canCreate ? (
                        <Button
                          size="small"
                          type="text"
                          className="!ml-auto"
                          aria-label={`Add deal to ${meta.label}`}
                          icon={<Icon name="plus" size={13} />}
                          onClick={() => {
                            setEditing(null);
                            setDefaultStage(st);
                            setFormOpen(true);
                          }}
                        />
                      ) : null}
                    </div>
                    <div className="tcx-kcol-sum">
                      <b>{inr(columnSum)}</b>
                    </div>
                    <div className="tcx-kcol-prog" aria-hidden="true">
                      <i
                        style={{
                          width: `${columnDeals.length ? Math.max(8, pct) : 0}%`,
                          background: meta.color,
                        }}
                      />
                    </div>
                  </div>

                  <div
                    className={`tcx-kcol-body ${overStage === st ? 'over' : ''}`}
                    onDragOver={(e) => {
                      if (!dragId) return;
                      e.preventDefault();
                      e.dataTransfer.dropEffect = 'move';
                      if (overStage !== st) setOverStage(st);
                    }}
                    onDragLeave={(e) => {
                      if (!e.currentTarget.contains(e.relatedTarget as Node)) {
                        setOverStage((cur) => (cur === st ? null : cur));
                      }
                    }}
                    onDrop={(e) => {
                      e.preventDefault();
                      const droppedId = e.dataTransfer.getData('text/plain') || dragId;
                      setOverStage(null);
                      setDragId(null);
                      if (!droppedId) return;
                      const found = items.find((d) => d.id === droppedId);
                      if (found) void moveDealToStage(found, st);
                    }}
                  >
                    {columnDeals.length === 0 ? (
                      <div className="tcx-kcol-empty">Drop a deal here</div>
                    ) : (
                      columnDeals.map((deal) => (
                        <div
                          key={deal.id}
                          role="button"
                          tabIndex={0}
                          draggable={canEdit}
                          onDragStart={(e) => {
                            setDragId(deal.id);
                            e.dataTransfer.effectAllowed = 'move';
                            e.dataTransfer.setData('text/plain', deal.id);
                          }}
                          onDragEnd={() => {
                            setDragId(null);
                            setOverStage(null);
                          }}
                          onClick={() => router.push(`/app/deals/${deal.id}`)}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter' || e.key === ' ') {
                              e.preventDefault();
                              router.push(`/app/deals/${deal.id}`);
                              return;
                            }
                            if (e.shiftKey && (e.key === 'ArrowRight' || e.key === 'ArrowLeft')) {
                              e.preventDefault();
                              const nextIdx = e.key === 'ArrowRight' ? Math.min(stageValues.length - 1, stageIdx + 1) : Math.max(0, stageIdx - 1);
                              const nextStage = stageValues[nextIdx];
                              if (nextStage && nextStage !== deal.stage) {
                                void moveDealToStage(deal, nextStage);
                              }
                            }
                          }}
                          className={`tcx-kcard text-left ${dragId === deal.id ? 'dragging' : ''} ${flashId === deal.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)]">{deal.title}</div>
                              <div className="mt-0.5 truncate text-[12px] text-[var(--tcx-muted)]">{deal.account.name}</div>
                            </div>
                            <span className="shrink-0 font-mono text-[11px] text-[var(--tcx-muted)]">{deal.dealNumber}</span>
                          </div>

                          <div className="flex items-center justify-between gap-2">
                            <span className="tcx-kcard-amt">{inr(deal.amount)}</span>
                            <DealPulse stage={deal.stage} daysInStage={deal.daysInStage} short />
                          </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">
                              {deal.owner ? (
                                <>
                                  <UserAvatar name={deal.owner.name} size={18} />
                                  <span className="truncate">{deal.owner.name}</span>
                                </>
                              ) : (
                                'Unassigned'
                              )}
                            </span>
                            <span className="shrink-0">{deal.closedAt ? `Closed ${fmtDate(deal.closedAt)}` : deal.closeDate ? fmtDate(deal.closeDate) : 'No close date'}</span>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </section>
              );
            })}
          </div>
        )
      ) : (
        /* TABLE VIEW */
        <div className="tcx-surface-card overflow-hidden">
          {error ? (
            <div className="p-5">
              <Alert type="error" showIcon title={error} />
            </div>
          ) : loading && !data ? (
            <div className="p-6">
              <Skeleton active paragraph={{ rows: 7 }} />
            </div>
          ) : items.length === 0 ? (
            <div className="py-14">
              {filtered ? (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={
                    <span>
                      <b className="block text-[var(--tcx-text)]">No deals match</b>
                      Try a different search term, or clear the filters to see everything.
                    </span>
                  }
                >
                  <Button onClick={clearFilters}>Clear filters</Button>
                </Empty>
              ) : (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={
                    <span>
                      <b className="block text-[var(--tcx-text)]">No deals in this view yet</b>
                      Create your first deal to track revenue and sales progress.
                    </span>
                  }
                >
                  <Button
                    type="primary"
                    onClick={() => {
                      setEditing(null);
                      setDefaultStage('QUALIFICATION');
                      setFormOpen(true);
                    }}
                  >
                    Create your first deal
                  </Button>
                </Empty>
              )}
            </div>
          ) : (
            <div className="tcx-table-scroll" aria-busy={loading}>
              <table className={`tcx-table ${loading ? 'opacity-60' : ''}`}>
                <thead>
                  <tr>
                    {COLUMNS.map((col) => {
                      const active = sort.key === col.key;
                      return (
                        <th key={col.key} aria-sort={active ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'}>
                          <button type="button" className="tcx-th-sort" onClick={() => toggleSort(col.key)}>
                            {col.label}
                            {active ? <Icon name="chevronDown" size={12} className={sort.dir === 'asc' ? 'rotate-180' : ''} /> : null}
                          </button>
                        </th>
                      );
                    })}
                    <th className="text-right">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {items.map((deal) => (
                    <tr
                      key={deal.id}
                      className="tcx-row-click cursor-pointer"
                      tabIndex={0}
                      onClick={() => router.push(`/app/deals/${deal.id}`)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') router.push(`/app/deals/${deal.id}`);
                      }}
                    >
                      <td>
                        <div className="min-w-0">
                          <div className="flex items-center gap-2">
                            <Link href={`/app/deals/${deal.id}`} onClick={(e) => e.stopPropagation()} className="truncate font-semibold text-[var(--tcx-text)] hover:text-[var(--tcx-primary)]">
                              {deal.title}
                            </Link>
                            <span className="shrink-0 font-mono text-[11.5px] text-[var(--tcx-muted)]">{deal.dealNumber}</span>
                          </div>
                          <div className="mt-0.5 truncate text-[12.5px] text-[var(--tcx-muted)]">
                            <Link href={`/app/customers/${deal.account.id}`} onClick={(e) => e.stopPropagation()} className="hover:text-[var(--tcx-primary)]">
                              {deal.account.name}
                            </Link>
                            {deal.contact ? ` · ${deal.contact.name}` : ''}
                          </div>
                        </div>
                      </td>
                      <td>
                        <DealStageBadge stage={deal.stage} />
                      </td>
                      <td>
                        <DealPulse stage={deal.stage} daysInStage={deal.daysInStage} short />
                      </td>
                      <td className="tabular-nums font-semibold text-[var(--tcx-text)]">{inrFull(deal.amount)}</td>
                      <td className="whitespace-nowrap text-[var(--tcx-text-2)]">{deal.closedAt ? `Closed ${fmtDate(deal.closedAt)}` : deal.closeDate ? fmtDate(deal.closeDate) : '—'}</td>
                      <td className="whitespace-nowrap text-[var(--tcx-muted)]">{deal.createdAt ? fmtDate(deal.createdAt) : '—'}</td>
                      <td>
                        {deal.owner ? (
                          <span className="inline-flex items-center gap-2 whitespace-nowrap">
                            <UserAvatar name={deal.owner.name} size={22} />
                            <span className="text-[var(--tcx-text-2)]">{deal.owner.name}</span>
                          </span>
                        ) : (
                          <span className="text-[var(--tcx-muted)]">Unassigned</span>
                        )}
                      </td>
                      <td className="text-right" onClick={(e) => e.stopPropagation()}>
                        <div className="inline-flex items-center gap-1">
                          <Tooltip title="View details">
                            <Button size="small" type="text" aria-label={`View ${deal.title}`} icon={<Icon name="eye" size={14} />} onClick={() => router.push(`/app/deals/${deal.id}`)} />
                          </Tooltip>
                          {canEdit ? (
                            <Tooltip title="Edit deal">
                              <Button
                                size="small"
                                type="text"
                                aria-label={`Edit ${deal.title}`}
                                icon={<Icon name="edit" size={14} />}
                                onClick={() => {
                                  setEditing(deal);
                                  setFormOpen(true);
                                }}
                              />
                            </Tooltip>
                          ) : null}
                          {mayDelete ? (
                            <Tooltip title="Delete deal">
                              <Button size="small" type="text" danger aria-label={`Delete ${deal.title}`} icon={<Icon name="trash" size={14} />} onClick={() => void deleteDeal(deal)} />
                            </Tooltip>
                          ) : null}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>

              <TablePager page={page} pageSize={pageSize} total={total} onPageChange={setPage} onPageSizeChange={setPageSize} />
            </div>
          )}
        </div>
      )}

      <DealFormModal
        open={formOpen}
        deal={editing}
        defaultStage={defaultStage}
        currentUserId={user.id}
        people={people}
        onClose={() => setFormOpen(false)}
        onSaved={(saved) => {
          setFormOpen(false);
          notifyDealsChanged();
          refreshAll();
          message.success(editing ? `${saved.title} updated` : `${saved.title} (${saved.dealNumber}) created`);
        }}
      />

      <DealLossModal
        open={Boolean(lossDeal)}
        deal={lossDeal}
        onClose={() => setLossDeal(null)}
        onSaved={() => {
          const title = lossDeal?.title;
          setLossDeal(null);
          refreshAll();
          if (title) message.success(`Moved ${title} to Closed lost`);
        }}
      />

      <ModuleImportModal
        open={importModalOpen}
        entity="deals"
        entityTitle="Deals"
        onClose={() => setImportModalOpen(false)}
        onSuccess={() => {
          refreshAll();
          notifyDealsChanged();
        }}
      />
    </div>
  );
}
