// app/components/admin/permissions/PermissionsTable.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 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 Role {
  id: string;
  name: string;
}

interface Permission extends BaseTableItem {
  id: string;
  name: string;
  description: string;
  module: string;
  action: string;
  roles_count: number;
  role_names: Role[];
  created_at: string;
}

interface PermissionsTableProps {
  initialData?: {
    permissions: Permission[];
    modules: string[];
    actions: string[];
    pagination: PaginationData;
  };
}

// Tooltip component for roles
function RolesTooltip({ roles, roles_count }: { roles: Role[]; roles_count: number }) {
  if (roles_count === 0) {
    return (
      <span className="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-var-surface-hover text-var-text-muted">
        No roles
      </span>
    );
  }

  return (
    <div className="relative group">
      <span className="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-var-primary-muted text-var-primary-text cursor-pointer">
        {roles_count} role{roles_count !== 1 ? 's' : ''}
      </span>
      
      <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 hidden group-hover:block z-50">
        <div className="relative">
          <div className="bg-var-surface-raised text-var-text text-xs rounded-lg py-2 px-3 shadow-var-modal border border-var-border">
            <div className="font-semibold mb-1 pb-1 border-b border-var-border">
              Assigned Roles:
            </div>
            <div className="max-h-40 overflow-y-auto">
              {roles && roles.length > 0 ? (
                <ul className="space-y-1">
                  {roles.map((role) => (
                    <li key={role.id} className="flex items-center">
                      <span className="w-2 h-2 bg-var-primary rounded-full mr-2"></span>
                      {role.name}
                    </li>
                  ))}
                </ul>
              ) : (
                <span className="text-var-text-muted">No roles assigned</span>
              )}
            </div>
            <div className="absolute top-full left-1/2 transform -translate-x-1/2 -mt-1">
              <div className="w-2 h-2 bg-var-surface-raised border-r border-b border-var-border rotate-45"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function PermissionsTable({ initialData }: PermissionsTableProps) {
  const router = useRouter();
  const [permissions, setPermissions] = useState<Permission[]>(initialData?.permissions || []);
  const [modules, setModules] = useState<string[]>(initialData?.modules || []);
  const [permissionActions, setPermissionActions] = useState<string[]>(initialData?.actions || []);
  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: '',
    module: '',
    action: ''
  });

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();

  const canCreatePermission = hasPermission(PERMISSIONS.PERMISSIONS_CREATE);
  const canEditPermission = hasPermission(PERMISSIONS.PERMISSIONS_UPDATE);
  const canDeletePermission = hasPermission(PERMISSIONS.PERMISSIONS_DELETE);
  const canBulkDelete = hasPermission(PERMISSIONS.PERMISSIONS_BULK_DELETE);

  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search by name or description...'
    },
    {
      key: 'module',
      label: 'Module',
      type: 'select',
      options: modules.map(module => ({
        value: module,
        label: module.charAt(0).toUpperCase() + module.slice(1).replace(/_/g, ' ')
      }))
    },
    {
      key: 'action',
      label: 'Action',
      type: 'select',
      options: permissionActions.map(action => ({
        value: action,
        label: action.charAt(0).toUpperCase() + action.slice(1)
      }))
    }
  ];

  const fetchPermissions = useCallback(async (page = 1, newFilters = filters) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        ...newFilters
      });

      const response = await fetch(`/api/backend/admin/newpermissions?${params}`);
      const data = await response.json();

      if (response.ok) {
        setPermissions(data.permissions);
        setModules(data.modules);
        setPermissionActions(data.actions);
        setPagination(data.pagination);
      } else {
        toast.error(data.error || 'Failed to fetch permissions');
      }
    } catch {
      toast.error('Failed to fetch permissions');
    } finally {
      setLoading(false);
    }
  }, [filters, pagination.limit]);

  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchPermissions(1, newFilters);
  };

  const handlePageChange = (page: number) => {
    fetchPermissions(page);
  };

  const handleDeleteClick = (permission: Permission) => {
    if (!canDeletePermission) {
      toast.error('You do not have permission to delete permissions');
      return;
    }

    showAlert({
      title: 'Delete Permission',
      message: `Are you sure you want to delete the permission "${permission.name}"? This action cannot be undone and will remove this permission from all roles that have it assigned.`,
      confirmText: 'Delete Permission',
      cancelText: 'Cancel',
      type: 'danger',
      onConfirm: () => deletePermission(permission.id),
    });
  };

  const deletePermission = async (permissionId: string) => {
    try {
      const response = await fetch(`/api/backend/admin/newpermissions/${permissionId}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(data.message || 'Permission deleted successfully');
        fetchPermissions(pagination.page);
      } else {
        if (response.status === 409) {
          toast.error(data.error || 'Cannot delete permission assigned to roles');
        } else {
          toast.error(data.error || 'Failed to delete permission');
        }
      }
    } catch {
      toast.error('Failed to delete permission');
    }
  };

  const handleBulkDelete = async (selectedIds: string[]) => {
    try {
      const response = await fetch('/api/backend/admin/newpermissions/bulk-delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: selectedIds }),
      });

      const data = await response.json();

      if (response.ok) {
        if (data.skipped && data.skipped.length > 0) {
          const skippedNames = data.skipped.map((s: {name: string}) => s.name).join(', ');
          toast.success(
            `${data.deletedCount} permission${data.deletedCount !== 1 ? 's' : ''} deleted, ${data.skipped.length} skipped: ${skippedNames}`
          );
        } else {
          toast.success(data.message);
        }
        fetchPermissions(pagination.page);
      } else {
        toast.error(data.error || 'Bulk delete failed');
      }
    } catch {
      toast.error('Bulk delete failed');
    }
  };

  const bulkActions = [
    ...(canBulkDelete ? [{
      key: 'bulk-delete',
      label: 'Delete selected',
      icon: (
        <svg 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>
      ),
      className: 'bg-var-danger-bg text-var-danger hover:bg-var-danger-bg',
      requiresConfirm: true,
      confirmTitle: 'Delete selected permissions',
      confirmMessage: (count: number) => {
        return `Are you sure you want to delete ${count} permission${count !== 1 ? 's' : ''}? Permissions that are assigned to roles will be skipped automatically. This action cannot be undone.`;
      },
      onClick: handleBulkDelete,
    }] : []),
  ];

  const columns: TableColumn<Permission>[] = [
    {
      key: 'permission',
      label: 'Permission',
      render: (permission) => (
        <div>
          <div className="text-sm font-semibold text-var-text">{permission.name}</div>
          <div className="text-sm text-var-text-muted mt-1">{permission.description}</div>
        </div>
      )
    },
    {
      key: 'module',
      label: 'Module',
      render: (permission) => (
        <span className="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-var-success-bg text-var-success-text capitalize">
          {permission.module.replace(/_/g, ' ')}
        </span>
      )
    },
    {
      key: 'action',
      label: 'Action',
      render: (permission) => (
        <span className="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-var-primary-muted text-var-primary-text capitalize">
          {permission.action}
        </span>
      )
    },
    {
      key: 'roles',
      label: 'Roles',
      render: (permission) => (
        <RolesTooltip roles={permission.role_names} roles_count={permission.roles_count} />
      )
    },
    {
      key: 'created_at',
      label: 'Created',
      render: (permission) => (
        <span className="text-sm text-var-text-muted">
          {new Date(permission.created_at).toLocaleDateString()}
        </span>
      )
    }
  ];

  const actions: TableAction<Permission>[] = [
    ...(canEditPermission ? [{
      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: (permission: Permission) => {
        router.push(`/admin/dashboard/employees/permissions/edit/${permission.id}`);
      },
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'Edit permission'
    }] : []),

    ...(canDeletePermission ? [{
      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: (permission: Permission) => handleDeleteClick(permission),
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
      title: 'Delete permission'
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) fetchPermissions();
  }, [fetchPermissions, initialData]);

  const toggleFilters = () => setFiltersVisible(!filtersVisible);

  return (
    <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
      <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 space-y-4 lg:space-y-0">
          <div>
            <h2 className="text-lg font-semibold text-var-text">System Permissions</h2>
            <p className="text-sm text-var-text-secondary mt-1">
              {pagination.total} permission{pagination.total !== 1 ? 's' : ''} found
            </p>
          </div>
          
          <div className="flex items-center space-x-3">
            <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>

            {canCreatePermission && (
              <Link
                href="/admin/dashboard/employees/permissions/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>
                Add Permission
              </Link>
            )}
          </div>
        </div>

        {filtersVisible && (
          <div className="mt-4">
            <TableFilters
              filters={filterConfigs}
              onFilterChange={handleFilterChange}
              initialValues={filters}
              className="mt-0"
            />
          </div>
        )}
      </div>

      <DataTable
        data={permissions}
        columns={columns}
        actions={actions}
        bulkActions={bulkActions}
        loading={loading}
        emptyMessage="No permissions found"
        emptyDescription="Try adjusting your search or create a new permission"
        onCreateNew={canCreatePermission ? () => {
          router.push('/admin/dashboard/employees/permissions/new');
        } : undefined}
        createNewLabel="Create your first permission →"
        keyExtractor={(permission) => permission.id}
      />

      <TablePagination pagination={pagination} onPageChange={handlePageChange} />
    </div>
  );
}