import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { 
  Search, 
  Plus, 
  Edit, 
  Trash2, 
  Eye, 
  UserPlus,
  Shield,
  Users,
  Car,
  UtensilsCrossed,
  Hotel,
  MapPin,
  CheckCircle,
  XCircle,
  AlertTriangle
} from 'lucide-react';
import { toast } from 'sonner';

interface UsersTabProps {
  users: any[];
  isAdmin: boolean;
  isSuperAdmin: boolean;
  loadUsers: (page?: number, limit?: number, role?: string) => void;
  createUser?: (userData: any) => Promise<{ success: boolean; error?: string }>;
  updateUser?: (id: string, userData: any) => Promise<{ success: boolean; error?: string }>;
  deleteUser?: (id: string) => Promise<{ success: boolean; error?: string }>;
}

const UsersTab: React.FC<UsersTabProps> = ({ 
  users, 
  isAdmin, 
  isSuperAdmin, 
  loadUsers
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [roleFilter, setRoleFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [mockUsers, setMockUsers] = useState([
    {
      id: '1',
      name: 'Super Admin',
      email: 'superadmin@karibeo.com',
      role: 'super_admin',
      status: 'active',
      verified: true,
      lastLogin: '2024-01-15 10:30:00',
      avatar: '/api/placeholder/40/40',
      createdAt: '2023-01-01'
    },
    {
      id: '2', 
      name: 'Admin User',
      email: 'admin@karibeo.com',
      role: 'admin',
      status: 'active',
      verified: true,
      lastLogin: '2024-01-14 15:45:00',
      avatar: '/api/placeholder/40/40',
      createdAt: '2023-02-01'
    },
    {
      id: '3',
      name: 'Juan Pérez',
      email: 'juan.perez@karibeo.com',
      role: 'tourist',
      status: 'active',
      verified: true,
      lastLogin: '2024-01-13 09:15:00',
      avatar: '/api/placeholder/40/40',
      createdAt: '2023-03-15'
    }
  ]);

  useEffect(() => {
    loadUsers(1, 50, roleFilter === 'all' ? undefined : roleFilter);
  }, [roleFilter]);

  const handleCreateUser = async (formData: any) => {
    const newUser = {
      id: (mockUsers.length + 1).toString(),
      name: formData.name,
      email: formData.email,
      role: formData.role,
      status: 'active',
      verified: false,
      lastLogin: 'Nunca',
      avatar: '/api/placeholder/40/40',
      createdAt: new Date().toISOString().split('T')[0]
    };

    setMockUsers([...mockUsers, newUser]);
    setShowCreateModal(false);
    toast.success('Usuario creado exitosamente');
  };

  const handleDeleteUser = async (userId: string) => {
    setMockUsers(mockUsers.filter(user => user.id !== userId));
    toast.success('Usuario eliminado exitosamente');
  };

  const getRoleName = (role: any): string => (typeof role === 'string' ? role : role?.name || '');

  const filteredUsers = (users.length > 0 ? users : mockUsers).filter(user => {
    const matchesSearch = user.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         user.email?.toLowerCase().includes(searchTerm.toLowerCase());
    const normalizedRole = getRoleName(user.role);
    const matchesRole = roleFilter === 'all' || normalizedRole === roleFilter;
    const matchesStatus = statusFilter === 'all' || user.status === statusFilter;
    
    return matchesSearch && matchesRole && matchesStatus;
  });

  const getRoleIcon = (role: string) => {
    const iconMap = {
      'super_admin': Shield,
      'admin': Shield,
      'tourist': Users,
      'guide': MapPin,
      'hotel': Hotel,
      'taxi': Car,
      'restaurant': UtensilsCrossed
    };
    const Icon = iconMap[role as keyof typeof iconMap] || Users;
    return <Icon className="w-4 h-4" />;
  };

  const getRoleBadgeColor = (role: string) => {
    const colorMap = {
      'super_admin': 'bg-purple-100 text-purple-800',
      'admin': 'bg-blue-100 text-blue-800',
      'tourist': 'bg-green-100 text-green-800',
      'guide': 'bg-yellow-100 text-yellow-800',
      'hotel': 'bg-indigo-100 text-indigo-800',
      'taxi': 'bg-red-100 text-red-800',
      'restaurant': 'bg-orange-100 text-orange-800'
    };
    return colorMap[role as keyof typeof colorMap] || 'bg-gray-100 text-gray-800';
  };

  const getStatusIcon = (status: string, verified: boolean) => {
    if (status === 'active' && verified) return <CheckCircle className="w-4 h-4 text-green-500" />;
    if (status === 'active' && !verified) return <AlertTriangle className="w-4 h-4 text-yellow-500" />;
    return <XCircle className="w-4 h-4 text-red-500" />;
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">Gestión de Usuarios</h2>
          <p className="text-gray-600">Administra usuarios, roles y permisos del sistema</p>
        </div>
        <Dialog open={showCreateModal} onOpenChange={setShowCreateModal}>
          <DialogTrigger asChild>
            <Button>
              <UserPlus className="w-4 h-4 mr-2" />
              Nuevo Usuario
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Crear Nuevo Usuario</DialogTitle>
            </DialogHeader>
            <UserForm 
              onSubmit={handleCreateUser}
              onCancel={() => setShowCreateModal(false)}
              isSuperAdmin={isSuperAdmin}
            />
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardContent className="pt-6">
          <div className="flex flex-wrap gap-4">
            <div className="flex-1 min-w-64">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  placeholder="Buscar por nombre o email..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>
            <Select value={roleFilter} onValueChange={setRoleFilter}>
              <SelectTrigger className="w-48">
                <SelectValue placeholder="Filtrar por rol" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todos los roles</SelectItem>
                <SelectItem value="super_admin">Super Admin</SelectItem>
                <SelectItem value="admin">Admin</SelectItem>
                <SelectItem value="tourist">Turista</SelectItem>
                <SelectItem value="guide">Guía</SelectItem>
                <SelectItem value="hotel">Hotel</SelectItem>
                <SelectItem value="taxi">Taxi</SelectItem>
                <SelectItem value="restaurant">Restaurante</SelectItem>
              </SelectContent>
            </Select>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-48">
                <SelectValue placeholder="Filtrar por estado" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todos los estados</SelectItem>
                <SelectItem value="active">Activo</SelectItem>
                <SelectItem value="pending">Pendiente</SelectItem>
                <SelectItem value="suspended">Suspendido</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Lista de Usuarios ({filteredUsers.length})</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b">
                  <th className="text-left py-3 px-4 font-medium text-gray-700">Usuario</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-700">Rol</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-700">Estado</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-700">Última Conexión</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-700">Registrado</th>
                  <th className="text-right py-3 px-4 font-medium text-gray-700">Acciones</th>
                </tr>
              </thead>
              <tbody>
                {filteredUsers.map((user) => (
                  <tr key={user.id} className="border-b hover:bg-gray-50">
                    <td className="py-3 px-4">
                      <div className="flex items-center space-x-3">
                        <Avatar>
                          <AvatarImage src={user.avatar} />
                          <AvatarFallback>
                            {user.name?.split(' ').map((n: string) => n[0]).join('').toUpperCase()}
                          </AvatarFallback>
                        </Avatar>
                        <div>
                          <div className="font-medium text-gray-900">{user.name}</div>
                          <div className="text-sm text-gray-600">{user.email}</div>
                        </div>
                      </div>
                    </td>
                    <td className="py-3 px-4">
                      <Badge className={getRoleBadgeColor(getRoleName(user.role))}>
                        {getRoleIcon(getRoleName(user.role))}
                        <span className="ml-1 capitalize">{getRoleName(user.role).replace('_', ' ')}</span>
                      </Badge>
                    </td>
                    <td className="py-3 px-4">
                      <div className="flex items-center space-x-2">
                        {getStatusIcon(user.status, user.verified)}
                        <span className="capitalize">{user.status}</span>
                        {!user.verified && <span className="text-xs text-yellow-600">(No verificado)</span>}
                      </div>
                    </td>
                    <td className="py-3 px-4 text-sm text-gray-600">
                      {user.lastLogin === 'Nunca' ? 'Nunca' : new Date(user.lastLogin).toLocaleDateString()}
                    </td>
                    <td className="py-3 px-4 text-sm text-gray-600">
                      {new Date(user.createdAt).toLocaleDateString()}
                    </td>
                    <td className="py-3 px-4">
                      <div className="flex items-center justify-end space-x-2">
                        <Button variant="ghost" size="sm">
                          <Eye className="w-4 h-4" />
                        </Button>
                        <Button variant="ghost" size="sm">
                          <Edit className="w-4 h-4" />
                        </Button>
                        {isSuperAdmin && getRoleName(user.role) !== 'super_admin' && (
                          <Button 
                            variant="ghost" 
                            size="sm"
                            onClick={() => handleDeleteUser(user.id)}
                          >
                            <Trash2 className="w-4 h-4 text-red-500" />
                          </Button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

const UserForm = ({ 
  onSubmit, 
  onCancel, 
  user = null, 
  isSuperAdmin = false 
}: { 
  onSubmit: (data: any) => void;
  onCancel: () => void;
  user?: any;
  isSuperAdmin: boolean;
}) => {
  const [formData, setFormData] = useState({
    name: user?.name || '',
    email: user?.email || '',
    role: (typeof user?.role === 'string' ? user?.role : user?.role?.name) || 'tourist',
    phone: user?.profile?.phone || '',
    address: user?.profile?.address || '',
    status: user?.status || 'active'
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(formData);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <Label htmlFor="name">Nombre Completo</Label>
          <Input
            id="name"
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            required
          />
        </div>
        <div>
          <Label htmlFor="email">Email</Label>
          <Input
            id="email"
            type="email"
            value={formData.email}
            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
            required
          />
        </div>
        <div>
          <Label htmlFor="role">Rol</Label>
          <Select value={formData.role} onValueChange={(value) => setFormData({ ...formData, role: value })}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="tourist">Turista</SelectItem>
              <SelectItem value="guide">Guía Turístico</SelectItem>
              <SelectItem value="hotel">Hotel</SelectItem>
              <SelectItem value="taxi">Taxista</SelectItem>
              <SelectItem value="restaurant">Restaurante</SelectItem>
              {isSuperAdmin && (
                <>
                  <SelectItem value="admin">Administrador</SelectItem>
                  <SelectItem value="super_admin">Super Administrador</SelectItem>
                </>
              )}
            </SelectContent>
          </Select>
        </div>
        <div>
          <Label htmlFor="phone">Teléfono</Label>
          <Input
            id="phone"
            value={formData.phone}
            onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
          />
        </div>
        <div className="md:col-span-2">
          <Label htmlFor="address">Dirección</Label>
          <Input
            id="address"
            value={formData.address}
            onChange={(e) => setFormData({ ...formData, address: e.target.value })}
          />
        </div>
      </div>
      <div className="flex justify-end space-x-2 pt-4">
        <Button type="button" variant="outline" onClick={onCancel}>
          Cancelar
        </Button>
        <Button type="submit">
          {user ? 'Actualizar' : 'Crear'} Usuario
        </Button>
      </div>
    </form>
  );
};

export default UsersTab;