// app/components/admin/sidebars/SidebarsTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { usePermissions } from '@/hooks/usePermissions';
import { PERMISSIONS } from '@/lib/permissions';
import { useAlert } from '@/contexts/AlertContext';
import { sidebarWidgetRegistry } from '@/lib/page-builder/sidebar-widget-registry';
import { SidebarWidget } from '@/lib/page-builder/container-types';
import DataTable from '@/app/components/admin/CommonComponents/DataTable';
import TablePagination from '@/app/components/admin/CommonComponents/TablePagination';
import TableFilters from '@/app/components/admin/CommonComponents/TableFilters';
import { BaseTableItem, FilterConfig, FilterValues, PaginationData, TableColumn, TableAction } from '@/types/admin-table';

interface Sidebar extends BaseTableItem {
  id: string;
  name: string;
  description: string;
  widgets: SidebarWidget[];
  status: boolean;
  created_at: string;
  updated_at: string;
}

interface SidebarsTableProps {
  initialData?: {
    sidebars: Sidebar[];
    pagination: PaginationData;
  };
}

// Widget pills component
function WidgetPills({ widgets }: { widgets: SidebarWidget[] }) {
  if (!widgets || widgets.length === 0) {
    return <span className="text-xs text-var-text-muted italic">No widgets</span>;
  }

  return (
    <div className="flex flex-wrap gap-1">
      {widgets.slice(0, 3).map((w, i) => {
        const cfg = sidebarWidgetRegistry[w.type];
        return (
          <span 
            key={i} 
            className="inline-flex items-center gap-1 px-2 py-0.5 bg-var-primary-muted text-var-primary-text text-xs rounded-full border border-var-primary"
          >
            <span>{cfg?.icon}</span>
            <span>{cfg?.label ?? w.type}</span>
          </span>
        );
      })}
      {widgets.length > 3 && (
        <span className="inline-flex items-center px-2 py-0.5 bg-var-surface-hover text-var-text-muted text-xs rounded-full">
          +{widgets.length - 3} more
        </span>
      )}
    </div>
  );
}

export default function SidebarsTable({ initialData }: SidebarsTableProps) {
  const router = useRouter();
  const [sidebars, setSidebars] = useState<Sidebar[]>(initialData?.sidebars || []);
  const [loading, setLoading] = useState(false);
  const [filtersVisible, setFiltersVisible] = useState(false);
  const [pagination, setPagination] = useState<PaginationData>(
    initialData?.pagination || { page: 1, limit: 10, total: 0, pages: 0 }
  );
  const [filters, setFilters] = useState<FilterValues>({ 
    search: '', 
    status: '' 
  });

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();

  const canCreate = hasPermission(PERMISSIONS.SIDEBARS_CREATE);
  const canEdit   = hasPermission(PERMISSIONS.SIDEBARS_UPDATE);
  const canDelete = hasPermission(PERMISSIONS.SIDEBARS_DELETE);

  // Filter configuration
  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search sidebars...'
    },
    {
      key: 'status',
      label: 'Status',
      type: 'select',
      options: [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'Inactive' }
      ]
    }
  ];

  const fetchSidebars = useCallback(async (page = 1, newFilters = filters) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        ...newFilters,
      });
      const res = await fetch(`/api/backend/admin/sidebars?${params}`);
      const data = await res.json();
      if (res.ok) {
        setSidebars(data.sidebars);
        setPagination(data.pagination);
      } else {
        toast.error(data.error || 'Failed to fetch sidebars');
      }
    } catch {
      toast.error('Failed to fetch sidebars');
    } finally {
      setLoading(false);
    }
  }, [filters, pagination.limit]);

  // Handle filter changes
  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchSidebars(1, newFilters);
  };

  // Handle page change
  const handlePageChange = (page: number) => {
    fetchSidebars(page);
  };

  const toggleStatus = async (sidebarId: string, current: boolean) => {
    if (!canEdit) { 
      toast.error('No permission'); 
      return; 
    }
    try {
      const res = await fetch(`/api/backend/admin/sidebars/${sidebarId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: !current }),
      });
      const data = await res.json();
      if (res.ok) {
        toast.success(data.message || `Sidebar ${!current ? 'activated' : 'deactivated'} successfully`);
        fetchSidebars(pagination.page);
      } else {
        toast.error(data.error || 'Failed to update status');
      }
    } catch {
      toast.error('Failed to update status');
    }
  };

  const handleDeleteClick = (sidebar: Sidebar) => {
    if (!canDelete) { 
      toast.error('No permission'); 
      return; 
    }
    showAlert({
      title: 'Delete Sidebar',
      message: `Are you sure you want to delete "${sidebar.name}"? Any containers using this sidebar will fall back to showing no sidebar.`,
      confirmText: 'Delete Sidebar',
      cancelText: 'Cancel',
      onConfirm: () => deleteSidebar(sidebar.id),
    });
  };

  const deleteSidebar = async (id: string) => {
    try {
      const res = await fetch(`/api/backend/admin/sidebars/${id}`, { 
        method: 'DELETE' 
      });
      const data = await res.json();
      if (res.ok) {
        toast.success('Sidebar deleted successfully');
        fetchSidebars(pagination.page);
      } else {
        toast.error(data.error || 'Failed to delete sidebar');
      }
    } catch {
      toast.error('Failed to delete sidebar');
    }
  };

  // Table columns configuration
  const columns: TableColumn<Sidebar>[] = [
    {
      key: 'sidebar',
      label: 'Sidebar',
      render: (sidebar) => (
        <div>
          <p className="text-sm font-semibold text-var-text">{sidebar.name}</p>
          {sidebar.description && (
            <p className="text-xs text-var-text-muted mt-0.5 truncate max-w-55">{sidebar.description}</p>
          )}
          <code className="text-xs font-mono text-var-text-muted">{sidebar.id}</code>
        </div>
      )
    },
    {
      key: 'widgets',
      label: 'Widgets',
      render: (sidebar) => (
        <div className="flex items-center gap-2">
          <span className="text-xs font-medium text-var-text-muted shrink-0">
            {sidebar.widgets?.length ?? 0} widget{(sidebar.widgets?.length ?? 0) !== 1 ? 's' : ''}
          </span>
          <div><WidgetPills widgets={sidebar.widgets} /></div>
        </div>
      )
    },
    {
      key: 'status',
      label: 'Status',
      render: (sidebar) => (
        <div className="flex items-center gap-2">
          <div className={`w-2 h-2 rounded-full ${sidebar.status ? 'bg-var-success' : 'bg-var-danger'}`} />
          <span className={`text-sm font-medium ${sidebar.status ? 'text-var-success-text' : 'text-var-danger-text'}`}>
            {sidebar.status ? 'Active' : 'Inactive'}
          </span>
        </div>
      )
    },
    {
      key: 'updated_at',
      label: 'Updated',
      render: (sidebar) => (
        <span className="text-sm text-var-text-muted whitespace-nowrap">
          {new Date(sidebar.updated_at).toLocaleDateString()}
        </span>
      )
    }
  ];

  // Table actions configuration
  const actions: TableAction<Sidebar>[] = [
    // Edit button
    ...(canEdit ? [{
      key: 'edit',
      icon: (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
        </svg>
      ),
      onClick: (sidebar: Sidebar) => {
        router.push(`/admin/dashboard/sidebars/edit/${sidebar.id}`);
      },
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'Edit sidebar'
    }] : []),

    // Status Toggle Button
    ...(canEdit ? [{
      key: 'toggle-status',
      icon: (sidebar: Sidebar) => (
        sidebar.status ? (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        ) : (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        )
      ),
      onClick: (sidebar: Sidebar) => toggleStatus(sidebar.id, sidebar.status),
      className: (sidebar: Sidebar) => 
        sidebar.status
          ? 'text-var-warning hover:text-var-warning-text hover:bg-var-warning-bg'
          : 'text-var-success hover:text-var-success-text hover:bg-var-success-bg',
      title: (sidebar: Sidebar) => 
        sidebar.status ? 'Deactivate sidebar' : 'Activate sidebar'
    }] : []),

    // Delete button
    ...(canDelete ? [{
      key: 'delete',
      icon: (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
        </svg>
      ),
      onClick: (sidebar: Sidebar) => handleDeleteClick(sidebar),
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
      title: 'Delete sidebar'
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) fetchSidebars();
  }, [fetchSidebars, initialData]);

  const toggleFilters = () => {
    setFiltersVisible(!filtersVisible);
  };

  return (
    <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
      {/* Header */}
      <div className="px-6 py-4 border-b border-var-border bg-var-surface-hover/50">
        <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
          <div>
            <h2 className="text-lg font-semibold text-var-text">Sidebar Library</h2>
            <p className="text-sm text-var-text-secondary mt-1">
              {pagination.total} sidebar{pagination.total !== 1 ? 's' : ''} · Create once, reuse everywhere
            </p>
          </div>
          
          <div className="flex items-center gap-3">
            {/* Filter Toggle Button */}
            <button
              onClick={toggleFilters}
              className="inline-flex items-center px-3 py-2 bg-var-surface border border-var-border text-var-text-secondary font-medium rounded-xl hover:bg-var-surface-hover hover:text-var-text transition-all duration-200 shadow-var-button"
              title={filtersVisible ? "Hide filters" : "Show filters"}
            >
              <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
              </svg>
              {filtersVisible ? 'Hide Filters' : 'Show Filters'}
            </button>

            {canCreate && (
              <Link
                href="/admin/dashboard/sidebars/new"
                className="inline-flex items-center px-4 py-2 bg-var-primary text-white font-medium rounded-xl hover:bg-var-primary-hover transition-all duration-200 shadow-var-button hover:shadow-var-card"
              >
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                </svg>
                New Sidebar
              </Link>
            )}
          </div>
        </div>

        {/* Filters - Conditionally rendered */}
        {filtersVisible && (
          <div className="mt-4">
            <TableFilters
              filters={filterConfigs}
              onFilterChange={handleFilterChange}
              initialValues={filters}
              className="mt-0"
            />
          </div>
        )}
      </div>

      {/* Table */}
      <DataTable
        data={sidebars}
        columns={columns}
        actions={actions}
        loading={loading}
        emptyMessage="No sidebars yet"
        emptyDescription="Create a sidebar template and reuse it across pages"
        onCreateNew={canCreate ? () => {
          router.push('/admin/dashboard/sidebars/new');
        } : undefined}
        createNewLabel="Create your first sidebar →"
        keyExtractor={(sidebar) => sidebar.id}
      />

      {/* Pagination */}
      <TablePagination
        pagination={pagination}
        onPageChange={handlePageChange}
      />
    </div>
  );
}