/**
 * Platform Staff Management Page
 * Allows superusers to manage platform staff (platform_manager, platform_support)
 * with full editing capabilities including permissions
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Users,
  Search,
  Plus,
  Pencil,
  Shield,
  Mail,
  Calendar,
  CheckCircle,
  XCircle,
  Loader2,
} from 'lucide-react';
import { usePlatformUsers } from '../../hooks/usePlatform';
import { useCurrentUser } from '../../hooks/useAuth';
import EditPlatformUserModal from './components/EditPlatformUserModal';

interface PlatformUser {
  id: number;
  username: string;
  email: string;
  first_name: string;
  last_name: string;
  full_name?: string;
  role: string;
  is_active: boolean;
  is_superuser: boolean;
  permissions: {
    can_approve_plugins?: boolean;
    can_whitelist_urls?: boolean;
    [key: string]: any;
  };
  created_at: string;
  last_login?: string;
}

const PlatformStaff: React.FC = () => {
  const { t } = useTranslation();
  const { data: currentUser } = useCurrentUser();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedUser, setSelectedUser] = useState<PlatformUser | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);

  const { data: allUsers, isLoading, error } = usePlatformUsers();

  // Filter to only show platform staff (not superusers, not business users)
  const platformStaff = (allUsers || []).filter(
    (u: any) => u.role === 'platform_manager' || u.role === 'platform_support'
  );

  const filteredStaff = platformStaff.filter((u: any) => {
    const searchLower = searchTerm.toLowerCase();
    return (
      (u.full_name || u.username || '').toLowerCase().includes(searchLower) ||
      u.email.toLowerCase().includes(searchLower) ||
      u.username.toLowerCase().includes(searchLower)
    );
  });

  const canEditUser = (user: PlatformUser) => {
    if (!currentUser) {
      return false;
    }

    const currentRole = currentUser.role.toLowerCase();
    const targetRole = user.role.toLowerCase();

    // Superusers can edit anyone
    if (currentRole === 'superuser') {
      return true;
    }
    // Platform managers can only edit platform_support users, not other managers or superusers
    if (currentRole === 'platform_manager') {
      return targetRole === 'platform_support';
    }
    // All others cannot edit
    return false;
  };

  const handleEdit = (user: any) => {
    if (!canEditUser(user)) {
      return; // Silently ignore if user cannot be edited
    }
    setSelectedUser(user);
    setIsEditModalOpen(true);
  };

  const getRoleBadge = (role: string) => {
    if (role === 'platform_manager') {
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-300">
          <Shield className="w-3 h-3 mr-1" />
          Platform Manager
        </span>
      );
    }
    if (role === 'platform_support') {
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300">
          <Mail className="w-3 h-3 mr-1" />
          Platform Support
        </span>
      );
    }
    return null;
  };

  const formatDate = (dateString?: string) => {
    if (!dateString) return 'Never';
    return new Date(dateString).toLocaleDateString(undefined, {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-indigo-600 dark:text-indigo-400" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
        <div className="flex items-center gap-2 text-red-700 dark:text-red-400">
          <XCircle className="w-5 h-5" />
          <span>Failed to load platform staff</span>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="mb-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
              <Users className="w-7 h-7" />
              Platform Staff
            </h1>
            <p className="mt-2 text-gray-600 dark:text-gray-400">
              Manage platform managers and support staff
            </p>
          </div>
          <button
            className="flex items-center gap-2 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-colors"
            onClick={() => {
              // TODO: Implement create new staff member
              alert('Create new staff member - coming soon');
            }}
          >
            <Plus className="w-4 h-4" />
            Add Staff Member
          </button>
        </div>
      </div>

      {/* Search */}
      <div className="mb-6">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
          <input
            type="text"
            placeholder="Search staff by name, email, or username..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:text-white"
          />
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
          <div className="text-sm text-gray-500 dark:text-gray-400">Total Staff</div>
          <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
            {platformStaff.length}
          </div>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
          <div className="text-sm text-gray-500 dark:text-gray-400">Platform Managers</div>
          <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
            {platformStaff.filter((u: any) => u.role === 'platform_manager').length}
          </div>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
          <div className="text-sm text-gray-500 dark:text-gray-400">Support Staff</div>
          <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
            {platformStaff.filter((u: any) => u.role === 'platform_support').length}
          </div>
        </div>
      </div>

      {/* Staff List */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700">
            <tr>
              <th className="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                Staff Member
              </th>
              <th className="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                Role
              </th>
              <th className="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                Permissions
              </th>
              <th className="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                Status
              </th>
              <th className="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                Last Login
              </th>
              <th className="px-6 py-4 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                Actions
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
            {filteredStaff.map((user: any) => (
              <tr
                key={user.id}
                className="hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
              >
                {/* Staff Member */}
                <td className="px-6 py-4">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white font-semibold">
                      {(user.full_name || user.username).charAt(0).toUpperCase()}
                    </div>
                    <div>
                      <div className="font-medium text-gray-900 dark:text-white">
                        {user.full_name || user.username}
                      </div>
                      <div className="text-xs text-gray-500 dark:text-gray-400 font-mono">
                        {user.email}
                      </div>
                    </div>
                  </div>
                </td>

                {/* Role */}
                <td className="px-6 py-4">{getRoleBadge(user.role)}</td>

                {/* Permissions */}
                <td className="px-6 py-4">
                  <div className="flex flex-wrap gap-1">
                    {user.permissions?.can_approve_plugins && (
                      <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300">
                        Plugin Approver
                      </span>
                    )}
                    {user.permissions?.can_whitelist_urls && (
                      <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300">
                        URL Whitelister
                      </span>
                    )}
                    {!user.permissions?.can_approve_plugins && !user.permissions?.can_whitelist_urls && (
                      <span className="text-xs text-gray-400 dark:text-gray-500">
                        No special permissions
                      </span>
                    )}
                  </div>
                </td>

                {/* Status */}
                <td className="px-6 py-4">
                  {user.is_active ? (
                    <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300">
                      <CheckCircle className="w-3 h-3 mr-1" />
                      Active
                    </span>
                  ) : (
                    <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300">
                      <XCircle className="w-3 h-3 mr-1" />
                      Inactive
                    </span>
                  )}
                </td>

                {/* Last Login */}
                <td className="px-6 py-4">
                  <div className="flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400">
                    <Calendar className="w-3 h-3" />
                    {formatDate(user.last_login)}
                  </div>
                </td>

                {/* Actions */}
                <td className="px-6 py-4 text-right">
                  <button
                    onClick={() => handleEdit(user)}
                    disabled={!canEditUser(user)}
                    className="inline-flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-indigo-600 hover:text-indigo-700 dark:text-indigo-400 dark:hover:text-indigo-300 border border-indigo-200 dark:border-indigo-800 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/30 transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent"
                  >
                    <Pencil className="w-3.5 h-3.5" />
                    Edit
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        {/* Empty State */}
        {filteredStaff.length === 0 && (
          <div className="p-12 text-center">
            <Users className="w-12 h-12 mx-auto text-gray-400 dark:text-gray-600 mb-4" />
            <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
              No staff members found
            </h3>
            <p className="text-gray-500 dark:text-gray-400">
              {searchTerm
                ? 'Try adjusting your search criteria'
                : 'Add your first platform staff member to get started'}
            </p>
          </div>
        )}
      </div>

      {/* Edit Modal */}
      {selectedUser && (
        <EditPlatformUserModal
          isOpen={isEditModalOpen}
          onClose={() => {
            setIsEditModalOpen(false);
            setSelectedUser(null);
          }}
          user={selectedUser}
        />
      )}
    </div>
  );
};

export default PlatformStaff;
