'use client';

import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import DataTable, { Column } from '@/components/ui/DataTable';
import Pagination from '@/components/ui/Pagination';
import FilterPanel from '@/components/ui/FilterPanel';
import Toolbar from '@/components/ui/Toolbar';
import Modal from '@/components/ui/CustomModal';
import CommonTimelineModal from '@/components/ui/CommonTimelineModal';
import BankAccountFormModal from '@/components/admin/bank-accounts/BankAccountFormModal';
import { toast } from 'react-hot-toast';
import { ArchiveRestore, History, SquarePen, Trash2, Plus, Power } from 'lucide-react';
import { getApiErrorMessage } from '@/lib/utils/apiError';

// ─── Types ────────────────────────────────────────────────────────────────
interface BankAccount {
  id: number;
  bank_name: string;
  account_title: string;
  account_number: string;
  iban: string | null;
  branch_code: string | null;
  swift_code: string | null;
  is_active: boolean;
  sort_order: number;
  deleted_at: string | null;
  created_at: string;
}

interface PaginationData {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
}

interface TabCounts {
  active: number;
  deleted: number;
}

interface BankAccountsTableProps {
  canCreate: boolean;
  canEdit: boolean;
  canDelete: boolean;
  canBulkDelete: boolean;
  canViewDeleted: boolean;
  canPermanentDelete: boolean;
  canRestore: boolean;
  canBulkRestore: boolean;
  canViewTimeline: boolean;
  initialBankAccounts: { bankAccounts: BankAccount[]; pagination: PaginationData };
  initialCounts: TabCounts;
}

type TabType = 'active' | 'deleted';

interface ActiveFilters {
  search: string;
  status: string;
  startDate: string;
  endDate: string;
}

interface DeletedFilters {
  search: string;
  startDate: string;
  endDate: string;
}

interface ModalConfig {
  isOpen: boolean;
  type: 'danger' | 'warning' | 'info' | 'success';
  title: string;
  message: string;
  confirmText?: string;
  cancelText?: string;
  onConfirm: () => void;
}

const ICON_STROKE = { fill: 'none', stroke: 'currentColor', strokeWidth: 2 } as const;

const EMPTY_ACTIVE_FILTERS: ActiveFilters = { search: '', status: '', startDate: '', endDate: '' };
const EMPTY_DELETED_FILTERS: DeletedFilters = { search: '', startDate: '', endDate: '' };

const MODAL_CLOSED: ModalConfig = {
  isOpen: false, type: 'danger', title: '', message: '', confirmText: 'Confirm', cancelText: 'Cancel', onConfirm: () => {},
};

// ─── API Helpers ──────────────────────────────────────────────────────────
async function fetchBankAccountsApi(
  page: number,
  tab: TabType,
  active: ActiveFilters,
  deleted: DeletedFilters,
  signal: AbortSignal,
) {
  const params = new URLSearchParams({
    page: String(page),
    limit: '10',
    includeDeleted: tab === 'deleted' ? 'true' : 'false',
  });

  if (tab === 'deleted') {
    if (deleted.search.trim()) params.append('search', deleted.search.trim());
    if (deleted.startDate) params.append('deletedStartDate', deleted.startDate);
    if (deleted.endDate) params.append('deletedEndDate', deleted.endDate);
  } else {
    if (active.search.trim()) params.append('search', active.search.trim());
    if (active.status) params.append('status', active.status);
    if (active.startDate) params.append('startDate', active.startDate);
    if (active.endDate) params.append('endDate', active.endDate);
  }

  const res = await fetch(`/api/bank-accounts?${params}`, { cache: 'no-store', signal });
  if (!res.ok) throw new Error('Failed to fetch bank accounts');
  return res.json() as Promise<{ data: { bankAccounts: BankAccount[]; pagination: PaginationData } }>;
}

async function fetchCountsApi(): Promise<TabCounts> {
  const res = await fetch('/api/bank-accounts/counts', { cache: 'no-store' });
  if (!res.ok) throw new Error('Failed to fetch counts');
  const json = await res.json();
  return json.data as TabCounts;
}

// ─── Main Component ───────────────────────────────────────────────────────
export default function BankAccountsTable({
  canCreate,
  canEdit,
  canDelete,
  canBulkDelete,
  canViewDeleted,
  canPermanentDelete,
  canRestore,
  canBulkRestore,
  canViewTimeline,
  initialBankAccounts,
  initialCounts,
}: BankAccountsTableProps) {
  const [accounts, setAccounts] = useState<BankAccount[]>(initialBankAccounts.bankAccounts);
  const [pagination, setPagination] = useState<PaginationData>(initialBankAccounts.pagination);
  const [counts, setCounts] = useState<TabCounts>(initialCounts);
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<TabType>('active');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [showFilters, setShowFilters] = useState(false);
  const [isMutating, setIsMutating] = useState(false);

  const [timelineModal, setTimelineModal] = useState<{ isOpen: boolean; accountId: string; accountName: string }>({
    isOpen: false, accountId: '', accountName: '',
  });
  const [formModal, setFormModal] = useState<{ isOpen: boolean; account: BankAccount | null }>({
    isOpen: false, account: null,
  });
  const [modal, setModal] = useState<ModalConfig>(MODAL_CLOSED);

  const [activeFilters, setActiveFilters] = useState<ActiveFilters>(EMPTY_ACTIVE_FILTERS);
  const [deletedFilters, setDeletedFilters] = useState<DeletedFilters>(EMPTY_DELETED_FILTERS);
  const [draftActive, setDraftActive] = useState<ActiveFilters>(EMPTY_ACTIVE_FILTERS);
  const [draftDeleted, setDraftDeleted] = useState<DeletedFilters>(EMPTY_DELETED_FILTERS);

  const abortRef = useRef<AbortController | null>(null);
  const accountsRef = useRef(accounts);
  const selectedRef = useRef(selectedIds);

  useEffect(() => { accountsRef.current = accounts; }, [accounts]);
  useEffect(() => { selectedRef.current = selectedIds; }, [selectedIds]);
  useEffect(() => () => abortRef.current?.abort(), []);

  const fetchAccounts = useCallback(
    async (page: number, tab: TabType, committed: { active: ActiveFilters; deleted: DeletedFilters }) => {
      abortRef.current?.abort();
      const ctrl = new AbortController();
      abortRef.current = ctrl;
      setLoading(true);
      try {
        const json = await fetchBankAccountsApi(page, tab, committed.active, committed.deleted, ctrl.signal);
        setAccounts(json.data.bankAccounts);
        setPagination(json.data.pagination);
        setCurrentPage(page);
        setSelectedIds(new Set());
      } catch (err) {
        if ((err as Error).name === 'AbortError') return;
        console.error('Failed to fetch bank accounts:', err);
        toast.error('Failed to load bank accounts');
      } finally {
        if (abortRef.current === ctrl) setLoading(false);
      }
    },
    [],
  );

  const refreshCounts = useCallback(async () => {
    try {
      setCounts(await fetchCountsApi());
    } catch {
      console.warn('Could not refresh bank account counts');
    }
  }, []);

  const refreshAfterMutation = useCallback(
    async (tab: TabType, committed: { active: ActiveFilters; deleted: DeletedFilters }, page: number) => {
      await Promise.all([fetchAccounts(page, tab, committed), refreshCounts()]);
    },
    [fetchAccounts, refreshCounts],
  );

  const closeModal = useCallback(() => { if (!isMutating) setModal(MODAL_CLOSED); }, [isMutating]);
  const openModal = useCallback((config: Omit<ModalConfig, 'isOpen'>) => setModal({ isOpen: true, ...config }), []);

  const handleTimelineClick = useCallback((account: BankAccount) => {
    setTimelineModal({ isOpen: true, accountId: String(account.id), accountName: account.bank_name });
  }, []);

  const handleCreateClick = useCallback(() => setFormModal({ isOpen: true, account: null }), []);
  const handleEditClick = useCallback((account: BankAccount) => setFormModal({ isOpen: true, account }), []);

  const handleToggleActive = useCallback(async (account: BankAccount) => {
    setIsMutating(true);
    try {
      const res = await fetch(`/api/bank-accounts/${account.id}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: !account.is_active }),
      });
      if (res.ok) {
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success(account.is_active ? 'Bank account deactivated' : 'Bank account activated');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to update status'));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsMutating(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleDeleteAccount = useCallback(async (id: number) => {
    setIsMutating(true);
    try {
      const res = await fetch(`/api/bank-accounts/${id}`, { method: 'DELETE' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Bank account deleted successfully');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to delete bank account'));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsMutating(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleRestoreAccount = useCallback(async (id: number) => {
    setIsMutating(true);
    try {
      const res = await fetch(`/api/bank-accounts/${id}/restore`, { method: 'POST' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Bank account restored successfully');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to restore bank account'));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsMutating(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handlePermanentDelete = useCallback(async (id: number) => {
    setIsMutating(true);
    try {
      const res = await fetch(`/api/bank-accounts/${id}/permanent`, { method: 'DELETE' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Bank account permanently deleted');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to delete bank account'));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsMutating(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkDelete = useCallback(async () => {
    setIsMutating(true);
    try {
      const ids = Array.from(selectedRef.current).map(Number);
      const res = await fetch('/api/bank-accounts/bulk', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Bank accounts deleted successfully');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to delete bank accounts'));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsMutating(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkRestore = useCallback(async () => {
    setIsMutating(true);
    try {
      const ids = Array.from(selectedRef.current).map(Number);
      const res = await fetch('/api/bank-accounts/bulk/restore', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Bank accounts restored successfully');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to restore bank accounts'));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsMutating(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkPermanentDelete = useCallback(async () => {
    setIsMutating(true);
    try {
      const ids = Array.from(selectedRef.current).map(Number);
      const res = await fetch('/api/bank-accounts/bulk/permanent', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Bank accounts permanently deleted');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to delete bank accounts'));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsMutating(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleDeleteClick = useCallback((account: BankAccount) => {
    if (activeTab === 'deleted') {
      openModal({
        type: 'danger',
        title: 'Permanent Delete Bank Account',
        message: `Permanently delete "${account.bank_name}"? This cannot be undone.`,
        confirmText: 'Permanently Delete',
        cancelText: 'Cancel',
        onConfirm: () => handlePermanentDelete(account.id),
      });
      return;
    }
    openModal({
      type: 'danger',
      title: 'Delete Bank Account',
      message: `Delete "${account.bank_name}" (${account.account_title})? It will move to deleted items.`,
      confirmText: 'Delete',
      cancelText: 'Cancel',
      onConfirm: () => handleDeleteAccount(account.id),
    });
  }, [activeTab, handleDeleteAccount, handlePermanentDelete, openModal]);

  const handleRestoreClick = useCallback((account: BankAccount) => {
    openModal({
      type: 'info',
      title: 'Restore Bank Account',
      message: `Restore "${account.bank_name}"? It will be reactivated.`,
      confirmText: 'Restore',
      cancelText: 'Cancel',
      onConfirm: () => handleRestoreAccount(account.id),
    });
  }, [handleRestoreAccount, openModal]);

  const showBulkDeleteConfirmation = useCallback(() => {
    if (activeTab === 'deleted') {
      openModal({
        type: 'danger',
        title: 'Permanent Bulk Delete',
        message: `Permanently delete ${selectedRef.current.size} bank account(s)? This cannot be undone.`,
        confirmText: 'Permanently Delete All',
        cancelText: 'Cancel',
        onConfirm: handleBulkPermanentDelete,
      });
      return;
    }
    openModal({
      type: 'danger',
      title: 'Bulk Delete Bank Accounts',
      message: `Delete ${selectedRef.current.size} bank account(s)? They will move to deleted items.`,
      confirmText: 'Delete All',
      cancelText: 'Cancel',
      onConfirm: handleBulkDelete,
    });
  }, [activeTab, handleBulkDelete, handleBulkPermanentDelete, openModal]);

  const showBulkRestoreConfirmation = useCallback(() => {
    openModal({
      type: 'info',
      title: 'Bulk Restore Bank Accounts',
      message: `Restore ${selectedRef.current.size} bank account(s)?`,
      confirmText: 'Restore All',
      cancelText: 'Cancel',
      onConfirm: handleBulkRestore,
    });
  }, [handleBulkRestore, openModal]);

  const handleTabChange = useCallback((tab: TabType) => {
    setActiveTab(tab);
    setShowFilters(false);
    setActiveFilters(EMPTY_ACTIVE_FILTERS);
    setDeletedFilters(EMPTY_DELETED_FILTERS);
    setDraftActive(EMPTY_ACTIVE_FILTERS);
    setDraftDeleted(EMPTY_DELETED_FILTERS);
    fetchAccounts(1, tab, { active: EMPTY_ACTIVE_FILTERS, deleted: EMPTY_DELETED_FILTERS });
  }, [fetchAccounts]);

  const handleToggleFilters = useCallback(() => {
    setShowFilters((prev) => {
      if (!prev) {
        setDraftActive({ ...activeFilters });
        setDraftDeleted({ ...deletedFilters });
      }
      return !prev;
    });
  }, [activeFilters, deletedFilters]);

  const handleApplyFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDeletedFilters(draftDeleted);
      fetchAccounts(1, activeTab, { active: activeFilters, deleted: draftDeleted });
    } else {
      setActiveFilters(draftActive);
      fetchAccounts(1, activeTab, { active: draftActive, deleted: deletedFilters });
    }
  }, [activeTab, draftActive, draftDeleted, activeFilters, deletedFilters, fetchAccounts]);

  const handleResetFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDraftDeleted(EMPTY_DELETED_FILTERS);
      setDeletedFilters(EMPTY_DELETED_FILTERS);
      fetchAccounts(1, activeTab, { active: activeFilters, deleted: EMPTY_DELETED_FILTERS });
    } else {
      setDraftActive(EMPTY_ACTIVE_FILTERS);
      setActiveFilters(EMPTY_ACTIVE_FILTERS);
      fetchAccounts(1, activeTab, { active: EMPTY_ACTIVE_FILTERS, deleted: deletedFilters });
    }
  }, [activeTab, activeFilters, deletedFilters, fetchAccounts]);

  const handlePageChange = useCallback((page: number) => {
    if (page < 1 || page > pagination.totalPages) return;
    fetchAccounts(page, activeTab, { active: activeFilters, deleted: deletedFilters });
  }, [pagination.totalPages, fetchAccounts, activeTab, activeFilters, deletedFilters]);

  const handleSelectAll = useCallback(() => {
    setSelectedIds((prev) =>
      prev.size === accountsRef.current.length ? new Set() : new Set(accountsRef.current.map((a) => String(a.id))),
    );
  }, []);

  const handleSelectAccount = useCallback((id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  }, []);

  const columns = useMemo<Column<BankAccount>[]>(() => {
    const cols: Column<BankAccount>[] = [
      {
        key: 'bank',
        header: 'Bank',
        render: (a) => (
          <div>
            <div className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>{a.bank_name}</div>
            <div className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>{a.account_title}</div>
          </div>
        ),
      },
      {
        key: 'account_number',
        header: 'Account Number',
        render: (a) => <span className="text-sm font-mono" style={{ color: 'var(--color-text)' }}>{a.account_number}</span>,
      },
      {
        key: 'details',
        header: 'IBAN / SWIFT',
        render: (a) => (
          <div className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
            {a.iban && <div>IBAN: {a.iban}</div>}
            {a.swift_code && <div>SWIFT: {a.swift_code}</div>}
            {!a.iban && !a.swift_code && '—'}
          </div>
        ),
      },
      {
        key: 'status',
        header: 'Status',
        render: (a) => (
          a.deleted_at ? (
            <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full"
              style={{ background: 'var(--color-danger-light)', color: 'var(--color-danger)' }}>Deleted</span>
          ) : (
            <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full"
              style={{
                background: a.is_active ? 'var(--color-success-light)' : 'var(--color-surface-alt)',
                color: a.is_active ? 'var(--color-success)' : 'var(--color-text-tertiary)',
              }}>
              {a.is_active ? 'Active' : 'Inactive'}
            </span>
          )
        ),
      },
      {
        key: 'created_at',
        header: 'Added',
        render: (a) => (
          <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
            {new Date(a.created_at).toLocaleDateString()}
          </span>
        ),
      },
    ];

    if (activeTab === 'deleted') {
      cols.push({
        key: 'deleted_at',
        header: 'Deleted At',
        render: (a) => (
          <span style={{ color: 'var(--color-text-tertiary)' }}>
            {a.deleted_at ? new Date(a.deleted_at).toLocaleDateString() : '-'}
          </span>
        ),
      });
    }

    cols.push({
      key: 'actions',
      header: 'Actions',
      className: 'text-right',
      render: (account) => {
        const actions: React.ReactNode[] = [];

        if (canViewTimeline) {
          actions.push(
            <button key="timeline" onClick={() => handleTimelineClick(account)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-text-secondary)' }} title="View Timeline">
              <History size={16} />
            </button>,
          );
        }

        if (activeTab === 'deleted') {
          if (canRestore) actions.push(
            <button key="restore" onClick={() => handleRestoreClick(account)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-success)' }} title="Restore">
              <ArchiveRestore size={16} />
            </button>,
          );
          if (canPermanentDelete) actions.push(
            <button key="perm-del" onClick={() => handleDeleteClick(account)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-danger)' }} title="Permanently Delete">
              <Trash2 size={16} />
            </button>,
          );
        } else {
          if (canEdit) actions.push(
            <button key="toggle" onClick={() => handleToggleActive(account)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: account.is_active ? 'var(--color-success)' : 'var(--color-text-tertiary)' }}
              title={account.is_active ? 'Deactivate' : 'Activate'}>
              <Power size={16} />
            </button>,
          );
          if (canEdit) actions.push(
            <button key="edit" onClick={() => handleEditClick(account)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-info)' }} title="Edit">
              <SquarePen size={16} />
            </button>,
          );
          if (canDelete) actions.push(
            <button key="delete" onClick={() => handleDeleteClick(account)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-danger)' }} title="Delete">
              <Trash2 size={16} />
            </button>,
          );
        }

        return <div className="flex justify-end gap-1">{actions}</div>;
      },
    });

    return cols;
  }, [
    activeTab, canEdit, canDelete, canPermanentDelete, canRestore, canViewTimeline,
    handleEditClick, handleDeleteClick, handleRestoreClick, handleTimelineClick, handleToggleActive,
  ]);

  const filterFields = useMemo(() => {
    if (activeTab === 'deleted') {
      return [
        {
          name: 'deletedSearch', label: 'Search', type: 'text' as const,
          placeholder: 'Search by bank, title, or account number...',
          value: draftDeleted.search,
          onChange: (v: string) => setDraftDeleted((p) => ({ ...p, search: v })),
        },
        {
          name: 'deletedStartDate', label: 'Deleted From', type: 'date' as const,
          value: draftDeleted.startDate,
          onChange: (v: string) => setDraftDeleted((p) => ({ ...p, startDate: v })),
        },
        {
          name: 'deletedEndDate', label: 'Deleted To', type: 'date' as const,
          value: draftDeleted.endDate,
          onChange: (v: string) => setDraftDeleted((p) => ({ ...p, endDate: v })),
        },
      ];
    }

    return [
      {
        name: 'search', label: 'Search', type: 'text' as const,
        placeholder: 'Search by bank, title, or account number...',
        value: draftActive.search,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, search: v })),
      },
      {
        name: 'status', label: 'Status', type: 'select' as const,
        options: [
          { value: '', label: 'All Status' },
          { value: 'active', label: 'Active' },
          { value: 'inactive', label: 'Inactive' },
        ],
        value: draftActive.status,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, status: v })),
      },
      {
        name: 'startDate', label: 'Added From', type: 'date' as const,
        value: draftActive.startDate,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, startDate: v })),
      },
      {
        name: 'endDate', label: 'Added To', type: 'date' as const,
        value: draftActive.endDate,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, endDate: v })),
      },
    ];
  }, [activeTab, draftActive, draftDeleted]);

  const bulkActionBar = useMemo(() => {
    if (selectedIds.size === 0) return null;

    if (activeTab === 'deleted') {
      return (
        <div className="flex gap-2">
          {canBulkRestore && (
            <button onClick={showBulkRestoreConfirmation}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
              style={{ background: 'var(--color-success)', color: 'white' }}>
              <svg width="16" height="16" {...ICON_STROKE}>
                <path d="M3 12a9 9 0 1 0 9-9m0 0v6m0-6h-6" /><path d="M21 12a9 9 0 1 1-9-9" />
              </svg>
              Restore ({selectedIds.size})
            </button>
          )}
          {canPermanentDelete && (
            <button onClick={showBulkDeleteConfirmation}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
              style={{ background: 'var(--color-danger)', color: 'white' }}>
              <svg width="16" height="16" {...ICON_STROKE}>
                <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
              </svg>
              Permanently Delete ({selectedIds.size})
            </button>
          )}
        </div>
      );
    }

    if (canBulkDelete) {
      return (
        <button onClick={showBulkDeleteConfirmation}
          className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
          style={{ background: 'var(--color-danger)', color: 'white' }}>
          <svg width="16" height="16" {...ICON_STROKE}>
            <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
          </svg>
          Delete ({selectedIds.size})
        </button>
      );
    }

    return null;
  }, [selectedIds, activeTab, canBulkDelete, canBulkRestore, canPermanentDelete, showBulkDeleteConfirmation, showBulkRestoreConfirmation]);

  return (
    <div className="space-y-4">
      {canViewDeleted && (
        <div className="flex border-b overflow-x-auto whitespace-nowrap" style={{ borderColor: 'var(--color-border)' }}>
          <button onClick={() => handleTabChange('active')}
            className={`px-4 py-2 text-sm font-medium transition-all border-b-2 ${
              activeTab === 'active' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}>
            Active ({counts.active})
          </button>
          <button onClick={() => handleTabChange('deleted')}
            className={`px-4 py-2 text-sm font-medium transition-all border-b-2 ${
              activeTab === 'deleted' ? 'border-red-500 text-red-600' : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}>
            Deleted ({counts.deleted})
          </button>
        </div>
      )}

      <Toolbar
        leftActions={
          <>
            <button onClick={handleToggleFilters}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all border"
              style={{ borderColor: 'var(--color-border)', color: 'var(--color-text)', background: 'var(--color-surface)' }}>
              <svg width="16" height="16" {...ICON_STROKE}>
                <path d="M3 6h18M6 12h12M10 18h4" />
              </svg>
              {showFilters ? 'Hide Filters' : 'Show Filters'}
            </button>
            {bulkActionBar}
          </>
        }
        rightActions={
          activeTab === 'active' && canCreate ? (
            <button onClick={handleCreateClick}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
              style={{ background: 'var(--color-cta)', color: 'white' }}>
              <Plus size={16} />
              Add Bank Account
            </button>
          ) : undefined
        }
      />

      {showFilters && (
        <FilterPanel
          fields={filterFields}
          onApply={handleApplyFilters}
          onReset={handleResetFilters}
          applyButtonText="Apply Filters"
          resetButtonText="Reset"
        />
      )}

      <DataTable
        columns={columns}
        data={accounts}
        loading={loading}
        selectedIds={selectedIds}
        onSelect={handleSelectAccount}
        onSelectAll={handleSelectAll}
        getRowId={(a) => String(a.id)}
        showCheckbox={activeTab === 'deleted' ? (canPermanentDelete || canBulkRestore) : canBulkDelete}
        emptyMessage={activeTab === 'deleted' ? 'No deleted bank accounts found' : 'No bank accounts found'}
        skeletonRows={10}
      />

      {!loading && pagination.totalPages > 0 && (
        <Pagination
          currentPage={currentPage}
          totalPages={pagination.totalPages}
          totalItems={pagination.total}
          itemsPerPage={pagination.limit}
          onPageChange={handlePageChange}
          showItemsInfo
        />
      )}

      <Modal
        isOpen={modal.isOpen}
        onClose={closeModal}
        onConfirm={modal.onConfirm}
        title={modal.title}
        message={modal.message}
        confirmText={modal.confirmText}
        cancelText={modal.cancelText}
        type={modal.type}
        isLoading={isMutating}
      />

      <BankAccountFormModal
        isOpen={formModal.isOpen}
        account={formModal.account}
        onClose={() => setFormModal({ isOpen: false, account: null })}
        onSaved={() => refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage)}
      />

      <CommonTimelineModal
        isOpen={timelineModal.isOpen}
        onClose={() => setTimelineModal({ isOpen: false, accountId: '', accountName: '' })}
        entityType="bank_account"
        entityId={timelineModal.accountId}
        entityName={timelineModal.accountName}
        title="Bank Account Timeline"
      />
    </div>
  );
}
