'use client';

import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import { useRouter } from 'next/navigation';
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'; // ✅ Changed to CommonTimelineModal
import { useCurrencyStore } from '@/store/currencyStore';
import { toast } from 'react-hot-toast';
import { ArchiveRestore, History, SquarePen, Trash2, Check, X } from 'lucide-react';
import { getApiErrorMessage } from '@/lib/utils/apiError';

// ─── Types ────────────────────────────────────────────────────────────────
interface Coupon {
  id: string;
  code: string;
  name: string;
  type: string;
  value: number;
  min_order_amount: number;
  max_discount: number | null;
  usage_limit: number | null;
  usage_limit_per_user: number;
  valid_from: string;
  valid_until: string;
  assignment_type: string;
  is_active: number | boolean;
  is_offer: number | boolean;
  is_featured: number | boolean;
  applicable_types: string;
  applicable_count: 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 CouponsTableProps {
  canEdit: boolean;
  canDelete: boolean;
  canBulkDelete: boolean;
  canViewDeleted: boolean;
  canPermanentDelete: boolean;
  canRestore: boolean;
  canBulkRestore: boolean;
  canViewTimeline: boolean;
  initialCoupons: { coupons: Coupon[]; pagination: PaginationData };
  initialCounts: TabCounts;
}

type TabType = 'active' | 'deleted';

interface ActiveFilters {
  search: string;
  type: string;
  status: string;
  assignment_type: 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;
}

// ─── Constants ────────────────────────────────────────────────────────────
const ICON_STROKE = { fill: 'none', stroke: 'currentColor', strokeWidth: 2 } as const;

const EMPTY_ACTIVE_FILTERS: ActiveFilters = {
  search: '',
  type: '',
  status: '',
  assignment_type: '',
  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 fetchCouponsApi(
  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.type) params.append('type', active.type);
    if (active.status) params.append('status', active.status);
    if (active.assignment_type) params.append('assignment_type', active.assignment_type);
    if (active.startDate) params.append('startDate', active.startDate);
    if (active.endDate) params.append('endDate', active.endDate);
  }

  const res = await fetch(`/api/coupons?${params}`, { cache: 'no-store', signal });
  if (!res.ok) throw new Error('Failed to fetch coupons');
  return res.json() as Promise<{ data: { coupons: Coupon[]; pagination: PaginationData } }>;
}

async function fetchCountsApi(): Promise<TabCounts> {
  const res = await fetch('/api/coupons/counts', { cache: 'no-store' });
  if (!res.ok) throw new Error('Failed to fetch counts');
  const json = await res.json();
  return json.data as TabCounts;
}

// ─── Badge Components ─────────────────────────────────────────────────────
function CouponTypeBadge({ type }: { type: string }) {
  const isPercentage = type === 'percentage';
  const currencySymbol = useCurrencyStore((s) => s.symbol);
  return (
    <span
      className="inline-flex px-2 py-1 text-xs font-medium rounded-full"
      style={{
        background: isPercentage ? 'var(--color-info-light)' : 'var(--color-success-light)',
        color: isPercentage ? 'var(--color-info)' : 'var(--color-success)',
      }}
    >
      {isPercentage ? '% Percent' : `${currencySymbol} Fixed`}
    </span>
  );
}

function StatusBadge({ coupon }: { coupon: Coupon }) {
  if (coupon.deleted_at) {
    return (
      <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>
    );
  }

  const now = new Date();
  const validUntil = new Date(coupon.valid_until);
  const validFrom = new Date(coupon.valid_from);

  if (!coupon.is_active) {
    return (
      <span
        className="inline-flex px-2 py-1 text-xs font-medium rounded-full"
        style={{ background: 'var(--color-warning-light)', color: 'var(--color-warning)' }}
      >
        Inactive
      </span>
    );
  }

  if (now > validUntil) {
    return (
      <span
        className="inline-flex px-2 py-1 text-xs font-medium rounded-full"
        style={{ background: 'var(--color-danger-light)', color: 'var(--color-danger)' }}
      >
        Expired
      </span>
    );
  }

  if (now < validFrom) {
    return (
      <span
        className="inline-flex px-2 py-1 text-xs font-medium rounded-full"
        style={{ background: 'var(--color-surface-alt)', color: 'var(--color-text-tertiary)' }}
      >
        Scheduled
      </span>
    );
  }

  return (
    <span
      className="inline-flex px-2 py-1 text-xs font-medium rounded-full"
      style={{ background: 'var(--color-success-light)', color: 'var(--color-success)' }}
    >
      Active
    </span>
  );
}

function ApplicableBadge({ applicableTypes }: { applicableTypes: string }) {
  const types = applicableTypes?.split(',').map((t) => t.trim()) || [];
  const labels: Record<string, string> = { all: 'All', category: 'Categories', product: 'Products' };

  return (
    <div className="flex flex-wrap gap-1">
      {types.map((type) => (
        <span
          key={type}
          className="inline-flex px-2 py-0.5 text-xs font-medium rounded-full"
          style={{ background: 'var(--color-cta-light)', color: 'var(--color-cta)' }}
        >
          {labels[type] || type}
        </span>
      ))}
    </div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────
export default function CouponsTable({
  canEdit,
  canDelete,
  canBulkDelete,
  canViewDeleted,
  canPermanentDelete,
  canRestore,
  canBulkRestore,
  canViewTimeline,
  initialCoupons,
  initialCounts,
}: CouponsTableProps) {
  const router = useRouter();
  const formatAmount = useCurrencyStore((s) => s.formatAmount);

  // ── Core State ──────────────────────────────────────────────────────
  const [coupons, setCoupons] = useState<Coupon[]>(initialCoupons.coupons);
  const [pagination, setPagination] = useState<PaginationData>(initialCoupons.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 [isDeleting, setIsDeleting] = useState(false);

  // ── Timeline state ──────────────────────────────────────────────────────
  // ✅ Changed to match Categories pattern
  const [timelineModal, setTimelineModal] = useState<{
    isOpen: boolean;
    couponId: string;
    couponName: string;
  }>({
    isOpen: false,
    couponId: '',
    couponName: '',
  });

  // ── Modal States ────────────────────────────────────────────────────
  const [modal, setModal] = useState<ModalConfig>(MODAL_CLOSED);

  // ── Filters ─────────────────────────────────────────────────────────
  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);

  // ── Refs ────────────────────────────────────────────────────────────
  const abortRef = useRef<AbortController | null>(null);
  const couponsRef = useRef(coupons);
  const selectedRef = useRef(selectedIds);

  useEffect(() => { couponsRef.current = coupons; }, [coupons]);
  useEffect(() => { selectedRef.current = selectedIds; }, [selectedIds]);
  useEffect(() => () => abortRef.current?.abort(), []);

  // ── Fetch Functions ─────────────────────────────────────────────────
  const fetchCoupons = 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 fetchCouponsApi(page, tab, committed.active, committed.deleted, ctrl.signal);
        setCoupons(json.data.coupons);
        setPagination(json.data.pagination);
        setCurrentPage(page);
        setSelectedIds(new Set());
      } catch (err) {
        if ((err as Error).name === 'AbortError') return;
        console.error('Failed to fetch coupons:', err);
        toast.error('Failed to load coupons');
      } finally {
        if (abortRef.current === ctrl) setLoading(false);
      }
    },
    []
  );

  const refreshCounts = useCallback(async () => {
    try {
      const updated = await fetchCountsApi();
      setCounts(updated);
    } catch {
      console.warn('Could not refresh coupon counts');
    }
  }, []);

  const refreshAfterMutation = useCallback(
    async (
      tab: TabType,
      committed: { active: ActiveFilters; deleted: DeletedFilters },
      page: number
    ) => {
      await Promise.all([fetchCoupons(page, tab, committed), refreshCounts()]);
    },
    [fetchCoupons, refreshCounts]
  );

  // ── Modal Helpers ───────────────────────────────────────────────────
  const closeModal = useCallback(() => {
    if (!isDeleting) setModal(MODAL_CLOSED);
  }, [isDeleting]);

  const openModal = useCallback((config: Omit<ModalConfig, 'isOpen'>) => {
    setModal({ isOpen: true, ...config });
  }, []);

  // ── Timeline handlers ─────────────────────────────────────────────────────
  // ✅ Simplified to match Categories pattern
  const handleTimelineClick = useCallback((coupon: Coupon) => {
    setTimelineModal({
      isOpen: true,
      couponId: coupon.id,
      couponName: coupon.name || coupon.code,
    });
  }, []);

  // ── CRUD Operations ─────────────────────────────────────────────────

  const handleStatusChange = useCallback(async (id: string, action: 'activate' | 'deactivate') => {
    setIsDeleting(true);
    try {
      const newStatus = action === 'activate' ? 1 : 0;
      const res = await fetch(`/api/coupons/${id}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: newStatus }),
      });
      
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success(`Coupon ${action}d successfully`);
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, `Failed to ${action} coupon`));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleEditClick = useCallback((id: string) => {
    router.push(`/admin/dashboard/coupons/edit/${id}`);
  }, [router]);

  const handleDeleteCoupon = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/coupons/${id}`, { method: 'DELETE' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Coupon deleted successfully');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to delete coupon'));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleRestoreCoupon = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/coupons/${id}/restore`, { method: 'POST' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Coupon restored successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to restore coupon');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handlePermanentDelete = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/coupons/${id}/permanent`, { method: 'DELETE' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Coupon permanently deleted');
      } else {
        toast.error((await res.json()).message || 'Failed to delete coupon');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkDelete = useCallback(async () => {
    setIsDeleting(true);
    try {
      const res = await fetch('/api/coupons/bulk', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: Array.from(selectedRef.current) }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Coupons deleted successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to delete coupons');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkRestore = useCallback(async () => {
    setIsDeleting(true);
    try {
      const res = await fetch('/api/coupons/bulk/restore', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: Array.from(selectedRef.current) }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Coupons restored successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to restore coupons');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkPermanentDelete = useCallback(async () => {
    setIsDeleting(true);
    try {
      const res = await fetch('/api/coupons/bulk/permanent', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: Array.from(selectedRef.current) }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Coupons permanently deleted');
      } else {
        toast.error((await res.json()).message || 'Failed to delete coupons');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  // ── Action handlers ───────────────────────────────────────────────────────

  const handleDeleteClick = useCallback((coupon: Coupon) => {
    if (activeTab === 'deleted') {
      openModal({
        type: 'danger',
        title: 'Permanent Delete Coupon',
        message: `Are you sure you want to permanently delete "${coupon.code}"? This cannot be undone.`,
        confirmText: 'Permanently Delete',
        cancelText: 'Cancel',
        onConfirm: () => handlePermanentDelete(coupon.id),
      });
      return;
    }

    openModal({
      type: 'danger',
      title: 'Delete Coupon',
      message: `Are you sure you want to delete "${coupon.code}"? It will move to deleted items.`,
      confirmText: 'Delete',
      cancelText: 'Cancel',
      onConfirm: () => handleDeleteCoupon(coupon.id),
    });
  }, [activeTab, handleDeleteCoupon, handlePermanentDelete, openModal]);

  const handleRestoreClick = useCallback((coupon: Coupon) => {
    openModal({
      type: 'info',
      title: 'Restore Coupon',
      message: `Restore "${coupon.code}"?`,
      confirmText: 'Restore',
      cancelText: 'Cancel',
      onConfirm: () => handleRestoreCoupon(coupon.id),
    });
  }, [handleRestoreCoupon, openModal]);

  const handleActivateClick = useCallback((coupon: Coupon) => {
    openModal({
      type: 'success',
      title: 'Activate Coupon',
      message: `Activate "${coupon.code}"?`,
      confirmText: 'Activate',
      cancelText: 'Cancel',
      onConfirm: () => handleStatusChange(coupon.id, 'activate'),
    });
  }, [handleStatusChange, openModal]);

  const handleDeactivateClick = useCallback((coupon: Coupon) => {
    openModal({
      type: 'warning',
      title: 'Deactivate Coupon',
      message: `Deactivate "${coupon.code}"?`,
      confirmText: 'Deactivate',
      cancelText: 'Cancel',
      onConfirm: () => handleStatusChange(coupon.id, 'deactivate'),
    });
  }, [handleStatusChange, openModal]);

  // ── Bulk actions ──────────────────────────────────────────────────────────

  const showBulkDeleteConfirmation = useCallback(() => {
    if (activeTab === 'deleted') {
      openModal({
        type: 'danger',
        title: 'Permanent Bulk Delete',
        message: `Permanently delete ${selectedRef.current.size} coupon(s)? This cannot be undone.`,
        confirmText: 'Permanently Delete All',
        cancelText: 'Cancel',
        onConfirm: handleBulkPermanentDelete,
      });
      return;
    }

    openModal({
      type: 'danger',
      title: 'Bulk Delete Coupons',
      message: `Delete ${selectedRef.current.size} coupon(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 Coupons',
      message: `Restore ${selectedRef.current.size} coupon(s)?`,
      confirmText: 'Restore All',
      cancelText: 'Cancel',
      onConfirm: handleBulkRestore,
    });
  }, [handleBulkRestore, openModal]);

  // ── Tab Change ──────────────────────────────────────────────────────
  const handleTabChange = useCallback((tab: TabType) => {
    setActiveTab(tab);
    setShowFilters(false);
    const freshActive = EMPTY_ACTIVE_FILTERS;
    const freshDeleted = EMPTY_DELETED_FILTERS;
    setActiveFilters(freshActive);
    setDeletedFilters(freshDeleted);
    setDraftActive(freshActive);
    setDraftDeleted(freshDeleted);
    fetchCoupons(1, tab, { active: freshActive, deleted: freshDeleted });
  }, [fetchCoupons]);

  // ── Filter Handlers ─────────────────────────────────────────────────
  const handleToggleFilters = useCallback(() => {
    setShowFilters((prev) => {
      if (!prev) {
        setDraftActive({ ...activeFilters });
        setDraftDeleted({ ...deletedFilters });
      }
      return !prev;
    });
  }, [activeFilters, deletedFilters]);

  const handleApplyFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDeletedFilters(draftDeleted);
      fetchCoupons(1, activeTab, { active: activeFilters, deleted: draftDeleted });
    } else {
      setActiveFilters(draftActive);
      fetchCoupons(1, activeTab, { active: draftActive, deleted: deletedFilters });
    }
  }, [activeTab, draftActive, draftDeleted, activeFilters, deletedFilters, fetchCoupons]);

  const handleResetFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDraftDeleted(EMPTY_DELETED_FILTERS);
      setDeletedFilters(EMPTY_DELETED_FILTERS);
      fetchCoupons(1, activeTab, { active: activeFilters, deleted: EMPTY_DELETED_FILTERS });
    } else {
      setDraftActive(EMPTY_ACTIVE_FILTERS);
      setActiveFilters(EMPTY_ACTIVE_FILTERS);
      fetchCoupons(1, activeTab, { active: EMPTY_ACTIVE_FILTERS, deleted: deletedFilters });
    }
  }, [activeTab, activeFilters, deletedFilters, fetchCoupons]);

  // ── Pagination ──────────────────────────────────────────────────────
  const handlePageChange = useCallback((page: number) => {
    if (page < 1 || page > pagination.totalPages) return;
    fetchCoupons(page, activeTab, { active: activeFilters, deleted: deletedFilters });
  }, [pagination.totalPages, fetchCoupons, activeTab, activeFilters, deletedFilters]);

  // ── Selection ───────────────────────────────────────────────────────
  const handleSelectAll = useCallback(() => {
    setSelectedIds((prev) =>
      prev.size === couponsRef.current.length
        ? new Set()
        : new Set(couponsRef.current.map((r) => r.id))
    );
  }, []);

  const handleSelectCoupon = useCallback((id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) { next.delete(id); } else { next.add(id); }
      return next;
    });
  }, []);

  // ── Columns ─────────────────────────────────────────────────────────
  const columns = useMemo<Column<Coupon>[]>(() => {
    const cols: Column<Coupon>[] = [
      {
        key: 'code',
        header: 'Coupon',
        render: (c) => (
          <div>
            <div
              className="font-mono font-bold text-sm"
              style={{ color: 'var(--color-cta)' }}
            >
              {c.code}
            </div>
            <div className="text-xs" style={{ color: 'var(--color-text-secondary)' }}>
              {c.name}
            </div>
          </div>
        ),
      },
      {
        key: 'discount',
        header: 'Discount',
        render: (c) => (
          <div className="flex items-center gap-2">
            <CouponTypeBadge type={c.type} />
            <span className="font-semibold text-sm" style={{ color: 'var(--color-text)' }}>
              {c.type === 'percentage' ? `${c.value}%` : formatAmount(c.value)}
            </span>
          </div>
        ),
      },
      {
        key: 'applicable',
        header: 'Applies To',
        render: (c) => <ApplicableBadge applicableTypes={c.applicable_types} />,
      },
      {
        key: 'validity',
        header: 'Validity',
        render: (c) => (
          <div className="text-xs">
            <div style={{ color: 'var(--color-text-secondary)' }}>
              From: {new Date(c.valid_from).toLocaleDateString()}
            </div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>
              To: {new Date(c.valid_until).toLocaleDateString()}
            </div>
          </div>
        ),
      },
      {
        key: 'status',
        header: 'Status',
        render: (coupon) => (
          <div>
            <StatusBadge coupon={coupon} />
            <div className="flex flex-wrap gap-1 mt-1">
              {Boolean(coupon.is_offer) && (
                <span className="inline-flex px-1.5 py-0.5 text-xs font-medium rounded-full"
                  style={{ background: '#FEF3C7', color: '#D97706' }}>
                  🏷️ Offer
                </span>
              )}
              {Boolean(coupon.is_featured) && (
                <span className="inline-flex px-1.5 py-0.5 text-xs font-medium rounded-full"
                  style={{ background: '#D1FAE5', color: '#059669' }}>
                  ⭐ Featured
                </span>
              )}
            </div>
          </div>
        ),
      },
    ];

    if (activeTab === 'deleted') {
      cols.push({
        key: 'deleted_at',
        header: 'Deleted At',
        render: (c) => (
          <span style={{ color: 'var(--color-text-tertiary)' }}>
            {c.deleted_at ? new Date(c.deleted_at).toLocaleDateString() : '-'}
          </span>
        ),
      });
    }

    cols.push({
      key: 'actions',
      header: 'Actions',
      className: 'text-right',
      render: (coupon) => {
        const actions: React.ReactNode[] = [];

        // Timeline button
        if (canViewTimeline) {
          actions.push(
            <button
              key="timeline"
              onClick={() => handleTimelineClick(coupon)}
              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(coupon)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-success)' }}
              title="Restore Coupon"
            >
              <ArchiveRestore size={16} />
            </button>,
          );
          if (canPermanentDelete) actions.push(
            <button
              key="perm-del"
              onClick={() => handleDeleteClick(coupon)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-danger)' }}
              title="Permanently Delete"
            >
              <Trash2 size={16} />
            </button>,
          );
        } else {
          // Activate/Deactivate buttons
          if (coupon.is_active) {
            actions.push(
              <button
                key="deactivate"
                onClick={() => handleDeactivateClick(coupon)}
                className="p-1 rounded hover:bg-surface-alt transition-colors"
                style={{ color: 'var(--color-warning)' }}
                title="Deactivate Coupon"
              >
                <X size={16} />
              </button>
            );
          } else if (!coupon.deleted_at) {
            actions.push(
              <button
                key="activate"
                onClick={() => handleActivateClick(coupon)}
                className="p-1 rounded hover:bg-surface-alt transition-colors"
                style={{ color: 'var(--color-success)' }}
                title="Activate Coupon"
              >
                <Check size={16} />
              </button>
            );
          }

          if (canEdit) actions.push(
            <button
              key="edit"
              onClick={() => handleEditClick(coupon.id)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-info)' }}
              title="Edit Coupon"
            >
              <SquarePen size={16} />
            </button>,
          );

          if (canDelete) {
            actions.push(
              <button
                key="delete"
                onClick={() => handleDeleteClick(coupon)}
                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-2">{actions}</div>;
      },
    });

    return cols;
  }, [
    activeTab, canEdit, canDelete, canPermanentDelete, canRestore,
    canViewTimeline,
    handleEditClick, handleDeleteClick, handleRestoreClick,
    handleTimelineClick, handleActivateClick, handleDeactivateClick,
    formatAmount,
  ]);

  // ── Filter Fields ───────────────────────────────────────────────────
  const filterFields = useMemo(() => {
    if (activeTab === 'deleted') {
      return [
        {
          name: 'deletedSearch',
          label: 'Search',
          type: 'text' as const,
          placeholder: 'Search by code or name...',
          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 code or name...',
        value: draftActive.search,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, search: v })),
      },
      {
        name: 'type',
        label: 'Type',
        type: 'select' as const,
        options: [
          { value: '', label: 'All Types' },
          { value: 'percentage', label: 'Percentage' },
          { value: 'fixed', label: 'Fixed Amount' },
        ],
        value: draftActive.type,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, type: v })),
      },
      {
        name: 'status',
        label: 'Status',
        type: 'select' as const,
        options: [
          { value: '', label: 'All Status' },
          { value: 'active', label: 'Active' },
          { value: 'inactive', label: 'Inactive' },
          { value: 'expired', label: 'Expired' },
        ],
        value: draftActive.status,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, status: v })),
      },
      {
        name: 'startDate',
        label: 'Created From',
        type: 'date' as const,
        value: draftActive.startDate,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, startDate: v })),
      },
      {
        name: 'endDate',
        label: 'Created To',
        type: 'date' as const,
        value: draftActive.endDate,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, endDate: v })),
      },
    ];
  }, [activeTab, draftActive, draftDeleted]);

  // ── Bulk Action Bar ─────────────────────────────────────────────────
  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,
  ]);

  // ── Render ──────────────────────────────────────────────────────────
  return (
    <div className="space-y-4">
      {/* Tabs */}
      {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 Coupons ({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 Coupons ({counts.deleted})
          </button>
        </div>
      )}

      {/* Toolbar */}
      <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}
          </>
        }
      />

      {/* Filter Panel */}
      {showFilters && (
        <FilterPanel
          fields={filterFields}
          onApply={handleApplyFilters}
          onReset={handleResetFilters}
          applyButtonText="Apply Filters"
          resetButtonText="Reset"
        />
      )}

      {/* Data Table */}
      <DataTable
        columns={columns}
        data={coupons}
        loading={loading}
        selectedIds={selectedIds}
        onSelect={handleSelectCoupon}
        onSelectAll={handleSelectAll}
        getRowId={(c) => c.id}
        showCheckbox={
          activeTab === 'deleted'
            ? canPermanentDelete || canBulkRestore
            : canBulkDelete
        }
        emptyMessage={
          activeTab === 'deleted' ? 'No deleted coupons found' : 'No coupons found'
        }
        skeletonRows={10}
      />

      {/* Pagination */}
      {!loading && pagination.totalPages > 0 && (
        <Pagination
          currentPage={currentPage}
          totalPages={pagination.totalPages}
          totalItems={pagination.total}
          itemsPerPage={pagination.limit}
          onPageChange={handlePageChange}
          showItemsInfo
        />
      )}

      {/* Confirmation Modal */}
      <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={isDeleting}
      />

      {/* ✅ Timeline Modal - Using CommonTimelineModal like Categories */}
      <CommonTimelineModal
        isOpen={timelineModal.isOpen}
        onClose={() => setTimelineModal({ isOpen: false, couponId: '', couponName: '' })}
        entityType="coupon"
        entityId={timelineModal.couponId}
        entityName={timelineModal.couponName}
        title="Coupon Timeline"
      />
    </div>
  );
}