// src/components/admin/menus/MenusTable.tsx

'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';
import { toast } from 'react-hot-toast';
import { ArchiveRestore, History, SquarePen, Trash2, ListTree } from 'lucide-react';
import { getApiErrorMessage } from '@/lib/utils/apiError';

// ─── Types ────────────────────────────────────────────────────────────────────

interface Menu {
  id: string;
  location: string;
  is_active: boolean;
  items_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 MenusTableProps {
  canEdit: boolean;
  canDelete: boolean;
  canViewDeleted: boolean;
  canPermanentDelete: boolean;
  canRestore: boolean;
  canViewTimeline: boolean;
  canReorder: boolean;
  initialMenus: {
    menus: Menu[];
    pagination: PaginationData;
  };
  initialCounts: TabCounts;
}

type TabType = 'active' | 'deleted';

interface ActiveFilters {
  search: string;
  location: 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;
}

interface TimelineModalState {
  isOpen: boolean;
  entityId: string;
  entityName: string;
}

// ─── Constants ────────────────────────────────────────────────────────────────

const ICON_STROKE = { fill: 'none', stroke: 'currentColor', strokeWidth: 2 } as const;

const EMPTY_ACTIVE_FILTERS: ActiveFilters = { search: '', location: '', 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: () => {},
};

const TIMELINE_MODAL_CLOSED: TimelineModalState = { isOpen: false, entityId: '', entityName: '' };

// ─── API Helpers ──────────────────────────────────────────────────────────────

async function fetchMenusApi(
  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.location) params.append('location', active.location);
    if (active.startDate) params.append('startDate', active.startDate);
    if (active.endDate) params.append('endDate', active.endDate);
  }

  const res = await fetch(`/api/menus?${params}`, { cache: 'no-store', signal });
  if (!res.ok) throw new Error('Failed to fetch menus');
  return res.json() as Promise<{ data: { menus: Menu[]; pagination: PaginationData } }>;
}

async function fetchCountsApi(): Promise<TabCounts> {
  const res = await fetch('/api/menus/counts', { cache: 'no-store' });
  if (!res.ok) throw new Error('Failed to fetch counts');
  const json = await res.json();
  return json.data as TabCounts;
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function StatusBadge({ menu }: { menu: Menu }) {
  if (menu.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>
    );
  }
  if (!menu.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>
    );
  }
  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>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function MenusTable({
  canEdit,
  canDelete,
  canViewDeleted,
  canRestore,
  canViewTimeline,
  initialMenus,
  initialCounts,
}: MenusTableProps) {
  const router = useRouter();

  // ── Core state ────────────────────────────────────────────────────────────
  const [menus, setMenus] = useState<Menu[]>(initialMenus.menus);
  const [pagination, setPagination] = useState<PaginationData>(initialMenus.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);
  const [modal, setModal] = useState<ModalConfig>(MODAL_CLOSED);

  // ── Timeline state ──────────────────────────────────────────────────────
  const [timelineModal, setTimelineModal] = useState<TimelineModalState>(TIMELINE_MODAL_CLOSED);

  // ── Committed filters ─────────────────────────────────────────────────────
  const [activeFilters, setActiveFilters] = useState<ActiveFilters>(EMPTY_ACTIVE_FILTERS);
  const [deletedFilters, setDeletedFilters] = useState<DeletedFilters>(EMPTY_DELETED_FILTERS);

  // ── Draft 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 menusRef = useRef(menus);
  const selectedRef = useRef(selectedIds);

  useEffect(() => { menusRef.current = menus; }, [menus]);
  useEffect(() => { selectedRef.current = selectedIds; }, [selectedIds]);
  useEffect(() => () => abortRef.current?.abort(), []);

  // ── Fetch functions ──────────────────────────────────────────────────────
  const fetchMenus = 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 fetchMenusApi(page, tab, committed.active, committed.deleted, ctrl.signal);
      setMenus(json.data.menus);
      setPagination(json.data.pagination);
      setCurrentPage(page);
      setSelectedIds(new Set());
    } catch (err) {
      if ((err as Error).name === 'AbortError') return;
      console.error('Failed to fetch menus:', err);
      toast.error('Failed to load menus');
    } finally {
      if (abortRef.current === ctrl) setLoading(false);
    }
  }, []);

  const refreshCounts = useCallback(async () => {
    try {
      const updated = await fetchCountsApi();
      setCounts(updated);
    } catch {
      console.warn('Could not refresh menu counts');
    }
  }, []);

  const refreshAfterMutation = useCallback(async (
    tab: TabType,
    committed: { active: ActiveFilters; deleted: DeletedFilters },
    page: number,
  ) => {
    await Promise.all([
      fetchMenus(page, tab, committed),
      refreshCounts(),
    ]);
  }, [fetchMenus, 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 ─────────────────────────────────────────────────────
  const handleTimelineClick = useCallback((menu: Menu) => {
    setTimelineModal({ isOpen: true, entityId: menu.id, entityName: menu.location });
  }, []);

  const handleTimelineClose = useCallback(() => {
    setTimelineModal(TIMELINE_MODAL_CLOSED);
  }, []);

  // ─── CRUD operations ───────────────────────────────────────────────────────

  const handleRestoreMenu = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/menus/${id}/restore`, { method: 'POST' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Menu restored successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to restore menu');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleDeleteMenu = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/menus/${id}`, { method: 'DELETE' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Menu deleted successfully');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to delete menu'));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  // ── Action handlers ───────────────────────────────────────────────────────

  const handleEditClick = useCallback((id: string) => {
    router.push(`/admin/dashboard/menus/${id}`);
  }, [router]);

  const handleDeleteClick = useCallback((menu: Menu) => {
    openModal({
      type: 'danger',
      title: 'Delete Menu',
      message: `Are you sure you want to delete the menu "${menu.location}"? All menu items will also be deleted.`,
      confirmText: 'Delete',
      cancelText: 'Cancel',
      onConfirm: () => handleDeleteMenu(menu.id),
    });
  }, [handleDeleteMenu, openModal]);

  const handleRestoreClick = useCallback((menu: Menu) => {
    openModal({
      type: 'info',
      title: 'Restore Menu',
      message: `Restore menu "${menu.location}"?`,
      confirmText: 'Restore',
      cancelText: 'Cancel',
      onConfirm: () => handleRestoreMenu(menu.id),
    });
  }, [handleRestoreMenu, 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);
    fetchMenus(1, tab, { active: freshActive, deleted: freshDeleted });
  }, [fetchMenus]);

  // ── Filter panel ──────────────────────────────────────────────────────────
  const handleToggleFilters = useCallback(() => {
    setShowFilters(prev => {
      if (!prev) {
        setDraftActive({ ...activeFilters });
        setDraftDeleted({ ...deletedFilters });
      }
      return !prev;
    });
  }, [activeFilters, deletedFilters]);

  const handleApplyFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDeletedFilters(draftDeleted);
      fetchMenus(1, activeTab, { active: activeFilters, deleted: draftDeleted });
    } else {
      setActiveFilters(draftActive);
      fetchMenus(1, activeTab, { active: draftActive, deleted: deletedFilters });
    }
  }, [activeTab, draftActive, draftDeleted, activeFilters, deletedFilters, fetchMenus]);

  const handleResetFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDraftDeleted(EMPTY_DELETED_FILTERS);
      setDeletedFilters(EMPTY_DELETED_FILTERS);
      fetchMenus(1, activeTab, { active: activeFilters, deleted: EMPTY_DELETED_FILTERS });
    } else {
      setDraftActive(EMPTY_ACTIVE_FILTERS);
      setActiveFilters(EMPTY_ACTIVE_FILTERS);
      fetchMenus(1, activeTab, { active: EMPTY_ACTIVE_FILTERS, deleted: deletedFilters });
    }
  }, [activeTab, activeFilters, deletedFilters, fetchMenus]);

  // ── Pagination ────────────────────────────────────────────────────────────
  const handlePageChange = useCallback((page: number) => {
    if (page < 1 || page > pagination.totalPages) return;
    fetchMenus(page, activeTab, { active: activeFilters, deleted: deletedFilters });
  }, [pagination.totalPages, fetchMenus, activeTab, activeFilters, deletedFilters]);

  // ── Selection ─────────────────────────────────────────────────────────────
  const handleSelectAll = useCallback(() => {
    setSelectedIds(prev =>
      prev.size === menusRef.current.length
        ? new Set()
        : new Set(menusRef.current.map(r => r.id)),
    );
  }, []);

  const handleSelectMenu = 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<Menu>[]>(() => {
    const cols: Column<Menu>[] = [
      {
        key: 'location',
        header: 'Location',
        render: (menu) => (
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{
              background: 'var(--color-cta-light)',
              color: 'var(--color-cta)',
            }}>
              <ListTree size={16} />
            </div>
            <div>
              <div className="font-medium" style={{ color: 'var(--color-text)' }}>
                {menu.location}
              </div>
              <div className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                ID: {menu.id.substring(0, 8)}...
              </div>
            </div>
          </div>
        ),
      },
      {
        key: 'items',
        header: 'Items',
        render: (menu) => (
          <span className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
            {menu.items_count} items
          </span>
        ),
      },
      {
        key: 'status',
        header: 'Status',
        render: (menu) => <StatusBadge menu={menu} />,
      },
      {
        key: 'created_at',
        header: 'Created At',
        render: (menu) => (
          <span style={{ color: 'var(--color-text-tertiary)' }}>
            {new Date(menu.created_at).toLocaleDateString()}
          </span>
        ),
      },
    ];

    if (activeTab === 'deleted') {
      cols.push({
        key: 'deleted_at',
        header: 'Deleted At',
        render: (menu) => (
          <span style={{ color: 'var(--color-text-tertiary)' }}>
            {menu.deleted_at ? new Date(menu.deleted_at).toLocaleDateString() : '-'}
          </span>
        ),
      });
    }

    cols.push({
      key: 'actions',
      header: 'Actions',
      className: 'text-right',
      render: (menu) => {
        const actions: React.ReactNode[] = [];

        // Timeline button
        if (canViewTimeline) {
          actions.push(
            <button
              key="timeline"
              onClick={() => handleTimelineClick(menu)}
              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(menu)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-success)' }}
              title="Restore Menu"
            >
              <ArchiveRestore size={16} />
            </button>,
          );
        } else {
          if (canEdit) actions.push(
            <button
              key="edit"
              onClick={() => handleEditClick(menu.id)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-info)' }}
              title="Edit Menu"
            >
              <SquarePen size={16} />
            </button>,
          );

          if (canDelete) {
            actions.push(
              <button
                key="delete"
                onClick={() => handleDeleteClick(menu)}
                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, canRestore,
    canViewTimeline,
    handleEditClick, handleDeleteClick, handleRestoreClick,
    handleTimelineClick,
  ]);

  // ── Filter fields ─────────────────────────────────────────────────────────
  const filterFields = useMemo(() => {
    if (activeTab === 'deleted') {
      return [
        {
          name: 'deletedSearch',
          label: 'Search',
          type: 'text' as const,
          placeholder: 'Search by location...',
          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 location...',
        value: draftActive.search,
        onChange: (v: string) => setDraftActive(p => ({ ...p, search: v })),
      },
      {
        name: 'location',
        label: 'Location',
        type: 'text' as const,
        placeholder: 'Filter by location...',
        value: draftActive.location,
        onChange: (v: string) => setDraftActive(p => ({ ...p, location: 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]);

  // ── Render ────────────────────────────────────────────────────────────────
  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 hover:border-gray-300'
            }`}
          >
            Active Menus ({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 hover:border-gray-300'
            }`}
          >
            Deleted Menus ({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>
          </>
        }
      />

      {showFilters && (
        <FilterPanel
          fields={filterFields}
          onApply={handleApplyFilters}
          onReset={handleResetFilters}
          applyButtonText="Apply Filters"
          resetButtonText="Reset"
        />
      )}

      <DataTable
        columns={columns}
        data={menus}
        loading={loading}
        selectedIds={selectedIds}
        onSelect={handleSelectMenu}
        onSelectAll={handleSelectAll}
        getRowId={(menu) => menu.id}
        showCheckbox={false}
        emptyMessage={activeTab === 'deleted' ? 'No deleted menus found' : 'No menus found'}
        skeletonRows={5}
      />

      {!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 */}
      <CommonTimelineModal
        isOpen={timelineModal.isOpen}
        onClose={handleTimelineClose}
        entityType="menu"
        entityId={timelineModal.entityId}
        entityName={timelineModal.entityName}
      />
    </div>
  );
}