// app/components/admin/employees/EmployeesTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import Image from 'next/image';
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 User extends BaseTableItem {
  id: string;
  email: string;
  first_name: string;
  last_name: string;
  phone?: string;
  is_active: boolean;
  is_verified: boolean;
  is_2fa_enabled?: boolean;
  avatar_url?: string;
  last_login_at?: string;
  created_at: string;
  failed_code_attempts?: number;
  code_lock_until?: string;
  is_account_locked?: boolean;
  lock_expiry?: string;
  roles: Array<{
    id: string;
    name: string;
    description: string;
  }>;
}

interface UsersTableProps {
  initialData?: {
    users: User[];
    pagination: PaginationData;
    filters: {
      roles: string[];
    };
  };
}

export default function EmployeesTable({ initialData }: UsersTableProps) {
  const router = useRouter();
  const [users, setUsers] = useState<User[]>(initialData?.users || []);
  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: '',
    role: '',
    status: '',
    account_locked: ''
  });

  const { hasPermission, loading: permissionsLoading } = usePermissions();
  const { showAlert } = useAlert();

  const canCreateUser = !permissionsLoading && hasPermission(PERMISSIONS.EMPLOYEES_CREATE);
  const canEditUser = !permissionsLoading && hasPermission(PERMISSIONS.EMPLOYEES_UPDATE);
  const canDeleteUser = !permissionsLoading && hasPermission(PERMISSIONS.EMPLOYEES_DELETE);
  const canToggleStatus = !permissionsLoading && hasPermission(PERMISSIONS.EMPLOYEES_UPDATE);
  const canUnlockAccount = !permissionsLoading && hasPermission(PERMISSIONS.EMPLOYEES_UPDATE);
  const canBulkDelete = !permissionsLoading && hasPermission(PERMISSIONS.EMPLOYEES_BULK_DELETE);

  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search by name or email...'
    },
    {
      key: 'role',
      label: 'Role',
      type: 'select',
      options: (initialData?.filters.roles || []).map(role => ({ 
        value: role, 
        label: role 
      }))
    },
    {
      key: 'status',
      label: 'Status',
      type: 'select',
      options: [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'Inactive' },
        { value: 'verified', label: 'Verified' },
        { value: 'unverified', label: 'Unverified' }
      ]
    },
    {
      key: 'account_locked',
      label: 'Account Lock',
      type: 'select',
      options: [
        { value: 'locked', label: 'Locked Accounts' },
        { value: 'unlocked', label: 'Unlocked Accounts' }
      ]
    }
  ];

  const fetchUsers = 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/employees?${params}`);
      const data = await response.json();

      if (response.ok) {
        setUsers(data.users);
        setPagination(data.pagination);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to view Employees');
        } else {
          toast.error(data.error || 'Failed to fetch users');
        }
      }
    } catch {
      toast.error('Failed to fetch users');
    } finally {
      setLoading(false);
    }
  }, [filters, pagination.limit]);

  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchUsers(1, newFilters);
  };

  const handlePageChange = (page: number) => {
    fetchUsers(page);
  };

  const toggleUserStatus = async (userId: string, currentStatus: boolean) => {
    if (!canToggleStatus) {
      toast.error('You do not have permission to update Employee status');
      return;
    }

    try {
      const response = await fetch(`/api/backend/admin/employees/${userId}/approve`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: !currentStatus }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(`Employee ${!currentStatus ? 'activated' : 'deactivated'} successfully`);
        fetchUsers(pagination.page);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to update Employees');
        } else {
          toast.error(data.error || 'Failed to update Employee status');
        }
      }
    } catch {
      toast.error('Failed to update Employee status');
    }
  };

  const handleUnlockAccount = async (user: User) => {
    if (!canUnlockAccount) {
      toast.error('You do not have permission to unlock accounts');
      return;
    }

    showAlert({
      title: 'Unlock Account',
      message: `Are you sure you want to unlock "${user.first_name} ${user.last_name}"'s account?`,
      confirmText: 'Unlock Account',
      cancelText: 'Cancel',
      onConfirm: () => unlockAccount(user.id),
    });
  };

  const unlockAccount = async (userId: string) => {
    try {
      const response = await fetch(`/api/backend/admin/employees/${userId}/unlock`, {
        method: 'POST',
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Account unlocked successfully');
        fetchUsers(pagination.page);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to unlock accounts');
        } else {
          toast.error(data.error || 'Failed to unlock account');
        }
      }
    } catch {
      toast.error('Failed to unlock account');
    }
  };

  const handleDeleteClick = (user: User) => {
    if (!canDeleteUser) {
      toast.error('You do not have permission to delete Employees');
      return;
    }

    showAlert({
      title: 'Delete Employee',
      message: `Are you sure you want to delete "${user.first_name} ${user.last_name}"? This action cannot be undone.`,
      confirmText: 'Delete Employee',
      cancelText: 'Cancel',
      onConfirm: () => deleteUser(user.id),
    });
  };

  const deleteUser = async (userId: string) => {
    try {
      const response = await fetch(`/api/backend/admin/employees/${userId}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Employee deleted successfully');
        fetchUsers(pagination.page);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to delete Employees');
        } else {
          toast.error(data.error || 'Failed to delete Employee');
        }
      }
    } catch {
      toast.error('Failed to delete Employee');
    }
  };

  const handleRevokeAllSessions = async (user: User) => {
    showAlert({
      title: 'Revoke All Sessions',
      message: `This will immediately sign "${user.first_name} ${user.last_name}" out of all devices. Continue?`,
      confirmText: 'Revoke All Sessions',
      cancelText: 'Cancel',
      onConfirm: async () => {
        const response = await fetch(
          `/api/backend/admin/employees/${user.id}/revoke-sessions`,
          { method: 'POST' }
        );
        const data = await response.json();
        if (response.ok) {
          toast.success(data.message);
          fetchUsers(pagination.page);
        } else {
          toast.error(data.error || 'Failed to revoke sessions');
        }
      },
    });
  };

  const handleStatusToggleClick = (user: User) => {
    if (!canToggleStatus) {
      toast.error('You do not have permission to update Employee status');
      return;
    }

    if (user.is_active) {
      showAlert({
        title: 'Deactivate Employee',
        message: `Are you sure you want to deactivate "${user.first_name} ${user.last_name}"? They will not be able to access the system.`,
        confirmText: 'Deactivate',
        cancelText: 'Keep Active',
        onConfirm: () => toggleUserStatus(user.id, user.is_active),
      });
    } else {
      toggleUserStatus(user.id, user.is_active);
    }
  };

  const isAccountLocked = (user: User): boolean => {
    if (user.is_account_locked !== undefined) return user.is_account_locked;
    if (user.code_lock_until) {
      const lockExpiry = new Date(user.code_lock_until);
      return lockExpiry > new Date();
    }
    return false;
  };

  const formatLockExpiry = (user: User): string => {
    if (!isAccountLocked(user)) return '';
    if (user.lock_expiry) {
      const lockExpiry = new Date(user.lock_expiry);
      const now = new Date();
      const diffMs = lockExpiry.getTime() - now.getTime();
      const diffMins = Math.max(0, Math.ceil(diffMs / (1000 * 60)));
      if (diffMins > 60) {
        const hours = Math.floor(diffMins / 60);
        const remainingMins = diffMins % 60;
        return `${hours}h ${remainingMins}m`;
      }
      return `${diffMins}m`;
    }
    return 'Locked';
  };

  const getUserAvatar = (user: User) => {
    if (user.avatar_url) {
      return (
        <Image
          src={user.avatar_url}
          alt={`${user.first_name} ${user.last_name}`}
          className="w-8 h-8 rounded-full object-cover border-2 border-var-surface shadow-var-card"
          width={32}
          height={32}
        />
      );
    }
    return (
      <div className="w-8 h-8 bg-var-primary rounded-full flex items-center justify-center text-white text-sm font-bold shadow-var-card">
        {user.first_name?.[0]}{user.last_name?.[0]}
      </div>
    );
  };

  const getUnlockIcon = () => (
    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z" />
    </svg>
  );

  const columns: TableColumn<User>[] = [
    {
      key: 'employee',
      label: 'Employee',
      render: (user) => (
        <div className="flex items-center">
          <div className="relative">{getUserAvatar(user)}</div>
          <div className="ml-4">
            <div className="text-sm font-medium text-var-text">
              {user.first_name} {user.last_name}
            </div>
            <div className="text-sm text-var-text-muted">{user.email}</div>
          </div>
        </div>
      )
    },
    {
      key: 'roles',
      label: 'Roles',
      render: (user) => (
        <div className="flex flex-wrap gap-1">
          {user.roles.filter(r => r.name).map((role) => (
            <span
              key={role.id}
              className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-var-primary-muted text-var-primary-text"
            >
              {role.name}
            </span>
          ))}
          {user.roles.filter(r => r.name).length === 0 && (
            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-var-surface-hover text-var-text-muted">
              No roles
            </span>
          )}
        </div>
      )
    },
    {
      key: 'status',
      label: 'Status',
      render: (user) => (
        <div className="flex items-center space-x-2 flex-wrap gap-1">
          <div className="flex items-center space-x-1">
            <div className={`w-2 h-2 rounded-full ${user.is_active ? 'bg-var-success' : 'bg-var-danger'}`} />
            <span className={`text-sm font-medium ${user.is_active ? 'text-var-success-text' : 'text-var-danger-text'}`}>
              {user.is_active ? 'Active' : 'Inactive'}
            </span>
          </div>
          {user.is_verified && (
            <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-success-bg text-var-success-text">
              Verified
            </span>
          )}
          {user.is_2fa_enabled && (
            <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-info-bg text-var-info-text">
              2FA
            </span>
          )}
        </div>
      )
    },
    {
      key: 'account_lock',
      label: 'Account Lock',
      render: (user) => {
        const accountLocked = isAccountLocked(user);
        return (
          <div>
            <div className="flex items-center space-x-2">
              <div className={`w-2 h-2 rounded-full ${accountLocked ? 'bg-var-danger' : 'bg-var-success'}`} />
              <span className={`text-sm font-medium ${accountLocked ? 'text-var-danger-text' : 'text-var-success-text'}`}>
                {accountLocked ? 'Locked' : 'Unlocked'}
              </span>
              {accountLocked && formatLockExpiry(user) && (
                <span className="text-xs text-var-text-muted">({formatLockExpiry(user)})</span>
              )}
            </div>
            {accountLocked && user.failed_code_attempts && user.failed_code_attempts > 0 && (
              <div className="text-xs text-var-text-muted mt-1">
                {user.failed_code_attempts} failed attempt(s)
              </div>
            )}
          </div>
        );
      }
    },
    {
      key: 'last_login',
      label: 'Last Login',
      render: (user) => (
        <span className="text-sm text-var-text-muted">
          {user.last_login_at 
            ? new Date(user.last_login_at).toLocaleDateString()
            : 'Never'
          }
        </span>
      )
    },
    {
      key: 'created_at',
      label: 'Created',
      render: (user) => (
        <span className="text-sm text-var-text-muted">
          {new Date(user.created_at).toLocaleDateString()}
        </span>
      )
    }
  ];

  const handleBulkDelete = async (selectedIds: string[]) => {
    try {
      const response = await fetch('/api/backend/admin/employees/bulk-delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: selectedIds }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(`${selectedIds.length} employee${selectedIds.length !== 1 ? 's' : ''} deleted`);
        fetchUsers(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 employees',
      confirmMessage: (count: number) =>
        `Are you sure you want to delete ${count} employee${count !== 1 ? 's' : ''}? This action cannot be undone.`,
      onClick: handleBulkDelete,
    }] : []),
  ];

  const actions: TableAction<User>[] = [
    ...(canEditUser ? [{
      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: (user: User) => router.push(`/admin/dashboard/employees/edit/${user.id}`),
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'Edit employee'
    }] : []),

    ...(canUnlockAccount ? [{
      key: 'unlock',
      icon: getUnlockIcon(),
      onClick: (user: User) => handleUnlockAccount(user),
      condition: (user: User) => isAccountLocked(user),
      className: 'text-var-success hover:text-var-success-text hover:bg-var-success-bg',
      title: 'Unlock account'
    }] : []),

    ...(canToggleStatus ? [{
      key: 'toggle-status',
      icon: (user: User) => (
        user.is_active ? (
          <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: (user: User) => handleStatusToggleClick(user),
      className: (user: User) => 
        user.is_active
          ? '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: (user: User) => user.is_active ? 'Deactivate employee' : 'Activate employee'
    }] : []),

    ...(canEditUser ? [{
      key: 'revoke-sessions',
      icon: (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
            d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
        </svg>
      ),
      onClick: (user: User) => handleRevokeAllSessions(user),
      className: 'text-var-warning hover:text-var-warning-text hover:bg-var-warning-bg',
      title: 'Revoke all sessions',
    }] : []),

    ...(canDeleteUser ? [{
      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: (user: User) => handleDeleteClick(user),
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
      title: 'Delete employee'
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) fetchUsers();
  }, [fetchUsers, 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">Employee Management</h2>
            <p className="text-sm text-var-text-secondary mt-1">
              {pagination.total} Employee{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>

            {canCreateUser && (
              <Link
                href="/admin/dashboard/employees/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 Employee
              </Link>
            )}
          </div>
        </div>

        {filtersVisible && (
          <div className="mt-4">
            <TableFilters
              filters={filterConfigs}
              onFilterChange={handleFilterChange}
              initialValues={filters}
              className="mt-0"
            />
          </div>
        )}
      </div>

      <DataTable
        data={users}
        columns={columns}
        actions={actions}
        bulkActions={bulkActions}
        loading={loading}
        emptyMessage="No Employee found"
        emptyDescription="Try adjusting your search or filters"
        onCreateNew={canCreateUser ? () => router.push('/admin/dashboard/employees/new') : undefined}
        createNewLabel="Create your first employee →"
        keyExtractor={(user) => user.id}
      />

      <TablePagination pagination={pagination} onPageChange={handlePageChange} />
    </div>
  );
}