import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Eye, Check, Pencil } from 'lucide-react';
import { usePlatformUsers } from '../../hooks/usePlatform';
import { verifyUserEmail, PlatformUser } from '../../api/platform';
import { useQueryClient } from '@tanstack/react-query';
import PlatformListing from './components/PlatformListing';
import PlatformListRow from './components/PlatformListRow';
import EditPlatformEntityModal from './components/EditPlatformEntityModal';
import ConfirmationModal from '../../components/ConfirmationModal';

interface PlatformUsersProps {
  onMasquerade: (targetUser: { id: number; username?: string; name?: string; email?: string; role?: string }) => void;
}

const PlatformUsers: React.FC<PlatformUsersProps> = ({ onMasquerade }) => {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState('');
  const [roleFilter, setRoleFilter] = useState<string>('all');
  const { data: users, isLoading, error } = usePlatformUsers();
  const [editingUser, setEditingUser] = useState<PlatformUser | null>(null);
  const [verifyEmailUser, setVerifyEmailUser] = useState<{ id: number; email: string; name: string } | null>(null);
  const [isVerifying, setIsVerifying] = useState(false);

  const filteredUsers = (users || []).filter(u => {
    const isPlatformUser = ['superuser', 'platform_manager', 'platform_sales', 'platform_support'].includes(u.role);
    if (!isPlatformUser) return false;

    const matchesSearch = (u.name || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
      u.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      u.username.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesRole = roleFilter === 'all' || u.role === roleFilter;
    return matchesSearch && matchesRole;
  });

  const getRoleBadgeColor = (role: string) => {
    switch (role) {
      case 'superuser': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
      case 'platform_manager': return 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-300';
      case 'platform_sales': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
      case 'platform_support': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const handleMasquerade = (platformUser: any) => {
    onMasquerade({
      id: platformUser.id,
      username: platformUser.username,
      name: platformUser.full_name || platformUser.username,
      email: platformUser.email,
      role: platformUser.role || 'customer',
    });
  };

  const handleVerifyEmailClick = (userId: number, email: string, name: string) => {
    setVerifyEmailUser({ id: userId, email, name });
  };

  const handleVerifyEmailConfirm = async () => {
    if (!verifyEmailUser) return;

    setIsVerifying(true);
    try {
      await verifyUserEmail(verifyEmailUser.id);
      queryClient.invalidateQueries({ queryKey: ['platform', 'users'] });
      setVerifyEmailUser(null);
    } catch (error) {
      alert(t('errors.generic'));
    } finally {
      setIsVerifying(false);
    }
  };

  const renderRow = (u: PlatformUser) => (
    <PlatformListRow
      key={u.id}
      avatarLetter={(u.name || u.username).charAt(0).toUpperCase()}
      primaryText={u.name || u.username}
      secondaryText={u.business_name}
      badgeText={(u.role || 'customer').replace(/_/g, ' ')}
      badgeColor={getRoleBadgeColor(u.role || 'customer')}
      tertiaryText={
        <>
          {u.email}
          {u.email_verified && <span title="Verified"><Check size={12} className="text-green-500" /></span>}
        </>
      }
      actions={
        <>
          {!u.email_verified && (
            <button
              onClick={() => handleVerifyEmailClick(u.id, u.email, u.name || u.username)}
              className="text-green-600 hover:text-green-500 dark:text-green-400 dark:hover:text-green-300 font-medium text-xs inline-flex items-center gap-1 px-3 py-1 border border-green-200 dark:border-green-800 rounded-lg hover:bg-green-50 dark:hover:bg-green-900/30 transition-colors"
              title={t('platform.verifyEmail')}
            >
              <Check size={14} /> {t('platform.verify')}
            </button>
          )}
          <button
            onClick={() => handleMasquerade(u)}
            className="text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300 font-medium text-xs inline-flex items-center gap-1 px-3 py-1 border border-indigo-200 dark:border-indigo-800 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/30 transition-colors"
            disabled={u.is_superuser}
            title={u.is_superuser ? 'Cannot masquerade as superuser' : `Masquerade as ${u.name || u.username}`}
          >
            <Eye size={14} /> {t('platform.masquerade')}
          </button>
          <button
            onClick={() => setEditingUser(u)}
            className="text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300 font-medium text-xs inline-flex items-center gap-1 px-3 py-1 border border-indigo-200 dark:border-indigo-800 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/30 transition-colors"
            title={t('common.edit')}
          >
            <Pencil size={14} /> {t('common.edit')}
          </button>
        </>
      }
    />
  );

  return (
    <>
      <PlatformListing
        title={t('platform.userDirectory')}
        description={t('platform.userDirectoryDescription')}
        isLoading={isLoading}
        error={error}
        data={filteredUsers}
        renderRow={renderRow}
        columns={[t('platform.user'), t('platform.role'), t('platform.email'), t('common.actions')]}
        searchPlaceholder={t('platform.searchUsers')}
        searchTerm={searchTerm}
        onSearchChange={setSearchTerm}
        filterOptions={[
          { value: 'all', label: t('platform.allRoles') },
          { value: 'superuser', label: t('platform.roles.superuser') },
          { value: 'platform_manager', label: t('platform.roles.platformManager') },
          { value: 'platform_sales', label: t('platform.roles.platformSales') },
          { value: 'platform_support', label: t('platform.roles.platformSupport') },
        ]}
        filterValue={roleFilter}
        onFilterChange={setRoleFilter}
        emptyMessage={t('platform.noUsersFound')}
      />
      <EditPlatformEntityModal
        entity={editingUser}
        type="user"
        isOpen={!!editingUser}
        onClose={() => setEditingUser(null)}
      />
      <ConfirmationModal
        isOpen={!!verifyEmailUser}
        onClose={() => setVerifyEmailUser(null)}
        onConfirm={handleVerifyEmailConfirm}
        title={t('platform.verifyEmail')}
        message={
          <div className="space-y-3">
            <p>{t('platform.confirmVerifyEmailMessage')}</p>
            {verifyEmailUser && (
              <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-3">
                <p className="font-medium text-gray-900 dark:text-white">{verifyEmailUser.name}</p>
                <p className="text-sm text-gray-500 dark:text-gray-400">{verifyEmailUser.email}</p>
              </div>
            )}
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {t('platform.verifyEmailNote')}
            </p>
          </div>
        }
        confirmText={t('platform.verify')}
        cancelText={t('common.cancel')}
        variant="success"
        isLoading={isVerifying}
      />
    </>
  );
};

export default PlatformUsers;