// app/components/admin/users/UsersTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import Image from 'next/image';
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';
import { useRouter } from 'next/navigation';

interface User extends BaseTableItem {
  id: string;
  email: string;
  first_name: string;
  last_name: string;
  display_name: string;
  avatar_url: string;
  phone: string;
  is_active: boolean;
  email_verified: boolean;
  two_factor_enabled: boolean;
  last_login_at: string | null;
  failed_login_attempts: number;
  created_at: string;
  updated_at: string;
}

interface UsersTableProps {
  initialData?: {
    users: User[];
    pagination: PaginationData;
  };
}

export default function UsersTable({ initialData }: UsersTableProps) {
  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: '',
    status: '',
    email_verified: ''
  });

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();

  const router = useRouter();

  const canCreateUser = hasPermission(PERMISSIONS.USERS_CREATE);
  const canEditUser = hasPermission(PERMISSIONS.USERS_UPDATE);
  const canDeleteUser = hasPermission(PERMISSIONS.USERS_DELETE);
  const canToggleStatus = hasPermission(PERMISSIONS.USERS_UPDATE);
  const canBulkDelete = hasPermission(PERMISSIONS.USERS_BULK_DELETE);

  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search by name or email...'
    },
    {
      key: 'status',
      label: 'Account Status',
      type: 'select',
      options: [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'Inactive' }
      ]
    },
    {
      key: 'email_verified',
      label: 'Email Status',
      type: 'select',
      options: [
        { value: 'verified', label: 'Verified' },
        { value: 'unverified', label: 'Unverified' }
      ]
    }
  ];

  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/users?${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 users');
        } 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 user status');
      return;
    }

    try {
      const response = await fetch(`/api/backend/admin/users/${userId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: !currentStatus }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(`User ${!currentStatus ? 'activated' : 'deactivated'} successfully`);
        fetchUsers(pagination.page);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to update users');
        } else {
          toast.error(data.error || 'Failed to update user status');
        }
      }
    } catch {
      toast.error('Failed to update user status');
    }
  };

  const handleDeleteClick = (user: User) => {
    if (!canDeleteUser) {
      toast.error('You do not have permission to delete users');
      return;
    }

    showAlert({
      title: 'Delete User',
      message: `Are you sure you want to delete "${user.display_name || user.email}"? This action cannot be undone.`,
      confirmText: 'Delete User',
      cancelText: 'Cancel',
      onConfirm: () => deleteUser(user.id),
    });
  };

  const handleEditPage = (userId: string) => {
    if (!canEditUser) {
      toast.error('You do not have permission to edit users');
      return;
    }
    router.push(`/admin/dashboard/users/edit/${userId}`);
  };

  const deleteUser = async (userId: string) => {
    try {
      const response = await fetch(`/api/backend/admin/users/${userId}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('User deleted successfully');
        fetchUsers(pagination.page);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to delete users');
        } else {
          toast.error(data.error || 'Failed to delete user');
        }
      }
    } catch {
      toast.error('Failed to delete user');
    }
  };

  const handleBulkDelete = async (selectedIds: string[]) => {
    try {
      const response = await fetch('/api/backend/admin/users/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?.length > 0) {
          toast.success(`${data.deletedCount} user${data.deletedCount !== 1 ? 's' : ''} deleted, ${data.skipped.length} skipped`);
        } else {
          toast.success(`${data.deletedCount} user${data.deletedCount !== 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 users',
      confirmMessage: (count: number) =>
        `Are you sure you want to delete ${count} user${count !== 1 ? 's' : ''}? This action cannot be undone.`,
      onClick: handleBulkDelete,
    }] : []),
  ];

  const getUserAvatar = (user: User) => {
    if (user.avatar_url) {
      return (
        <Image
          src={user.avatar_url}
          alt={user.display_name || user.email}
          className="w-8 h-8 rounded-full object-cover border-2 border-var-surface shadow-var-card"
          width={32}
          height={32}
        />
      );
    }
    
    const initials = user.display_name 
      ? user.display_name.charAt(0).toUpperCase()
      : user.email.charAt(0).toUpperCase();
    
    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">
        {initials}
      </div>
    );
  };

  const getFullName = (user: User) => {
    if (user.display_name) return user.display_name;
    if (user.first_name && user.last_name) return `${user.first_name} ${user.last_name}`;
    if (user.first_name) return user.first_name;
    return '—';
  };

  const columns: TableColumn<User>[] = [
    {
      key: 'user',
      label: 'User',
      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">{getFullName(user)}</div>
            <div className="text-xs text-var-text-muted">{user.email}</div>
          </div>
        </div>
      )
    },
    {
      key: 'phone',
      label: 'Phone',
      render: (user) => <span className="text-sm text-var-text-muted">{user.phone || '—'}</span>
    },
    {
      key: 'verification',
      label: 'Verification',
      render: (user) => (
        <div className="flex flex-col gap-1">
          {user.email_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">✓ Email Verified</span>
          ) : (
            <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-warning-bg text-var-warning-text">⚠ Email Unverified</span>
          )}
          {user.two_factor_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 Enabled</span>
          )}
        </div>
      )
    },
    {
      key: 'status',
      label: 'Status',
      render: (user) => (
        <div className="flex items-center space-x-2">
          <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>
      )
    },
    {
      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).toLocaleString() : 'Never'}
        </span>
      )
    },
    {
      key: 'created_at',
      label: 'Joined',
      render: (user) => (
        <span className="text-sm text-var-text-muted">
          {new Date(user.created_at).toLocaleDateString()}
        </span>
      )
    }
  ];

  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) => handleEditPage(user.id),
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'Edit user'
    }] : []),

    ...(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) => toggleUserStatus(user.id, user.is_active),
      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 user' : 'Activate user'
    }] : []),

    ...(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 user'
    }] : [])
  ];

  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">User Management</h2>
            <p className="text-sm text-var-text-secondary mt-1">
              {pagination.total} user{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/users/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 User
              </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 users found"
        emptyDescription="Try adjusting your search or filters"
        onCreateNew={canCreateUser ? () => router.push('/admin/dashboard/users/new') : undefined}
        createNewLabel="Create your first user →"
        keyExtractor={(user) => user.id}
      />

      <TablePagination pagination={pagination} onPageChange={handlePageChange} />
    </div>
  );
}