'use client';

import { useState } from 'react';
import { DashboardShell } from '@/components/layouts/dashboard-shell';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useUsuarios, useInviteUsuario, useUpdateUsuario, useDeleteUsuario } from '@/lib/hooks/use-usuarios';
import { useAuthStore } from '@/stores/auth-store';
import { Users, UserPlus, Trash2, Shield, Eye, Calculator } from 'lucide-react';
import { cn } from '@/lib/utils';

const roleLabels = {
  admin: { label: 'Administrador', icon: Shield, color: 'text-primary' },
  contador: { label: 'Contador', icon: Calculator, color: 'text-success' },
  visor: { label: 'Visor', icon: Eye, color: 'text-muted-foreground' },
};

export default function UsuariosPage() {
  const { user: currentUser } = useAuthStore();
  const { data: usuarios, isLoading } = useUsuarios();
  const inviteUsuario = useInviteUsuario();
  const updateUsuario = useUpdateUsuario();
  const deleteUsuario = useDeleteUsuario();

  const [showInvite, setShowInvite] = useState(false);
  const [inviteForm, setInviteForm] = useState({ email: '', nombre: '', role: 'visor' as const });

  const handleInvite = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await inviteUsuario.mutateAsync(inviteForm);
      setShowInvite(false);
      setInviteForm({ email: '', nombre: '', role: 'visor' });
    } catch (error: any) {
      alert(error.response?.data?.message || 'Error al invitar usuario');
    }
  };

  const handleToggleActive = (id: string, active: boolean) => {
    updateUsuario.mutate({ id, data: { active: !active } });
  };

  const handleDelete = (id: string) => {
    if (confirm('¿Eliminar este usuario?')) {
      deleteUsuario.mutate(id);
    }
  };

  const isAdmin = currentUser?.role === 'admin';

  return (
    <DashboardShell
      title="Usuarios"
      description="Gestiona los usuarios de tu empresa"
    >
      <div className="space-y-4">
        {/* Header */}
        <div className="flex justify-between items-center">
          <div className="flex items-center gap-2">
            <Users className="h-5 w-5" />
            <span className="font-medium">{usuarios?.length || 0} usuarios</span>
          </div>
          {isAdmin && (
            <Button onClick={() => setShowInvite(true)}>
              <UserPlus className="h-4 w-4 mr-2" />
              Invitar Usuario
            </Button>
          )}
        </div>

        {/* Invite Form */}
        {showInvite && (
          <Card>
            <CardHeader>
              <CardTitle>Invitar Nuevo Usuario</CardTitle>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleInvite} className="space-y-4">
                <div className="grid gap-4 md:grid-cols-3">
                  <div className="space-y-2">
                    <Label htmlFor="email">Email</Label>
                    <Input
                      id="email"
                      type="email"
                      value={inviteForm.email}
                      onChange={e => setInviteForm({ ...inviteForm, email: e.target.value })}
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="nombre">Nombre</Label>
                    <Input
                      id="nombre"
                      value={inviteForm.nombre}
                      onChange={e => setInviteForm({ ...inviteForm, nombre: e.target.value })}
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="role">Rol</Label>
                    <Select
                      value={inviteForm.role}
                      onValueChange={(v: 'admin' | 'contador' | 'visor') => setInviteForm({ ...inviteForm, role: v })}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="admin">Administrador</SelectItem>
                        <SelectItem value="contador">Contador</SelectItem>
                        <SelectItem value="visor">Visor</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <div className="flex gap-2">
                  <Button type="submit" disabled={inviteUsuario.isPending}>
                    {inviteUsuario.isPending ? 'Enviando...' : 'Enviar Invitación'}
                  </Button>
                  <Button type="button" variant="outline" onClick={() => setShowInvite(false)}>
                    Cancelar
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        )}

        {/* Users List */}
        <Card>
          <CardContent className="p-0">
            {isLoading ? (
              <div className="text-center py-8 text-muted-foreground">Cargando...</div>
            ) : (
              <div className="divide-y">
                {usuarios?.map(usuario => {
                  const roleInfo = roleLabels[usuario.role];
                  const RoleIcon = roleInfo.icon;
                  const isCurrentUser = usuario.id === currentUser?.id;

                  return (
                    <div key={usuario.id} className="p-4 flex items-center justify-between">
                      <div className="flex items-center gap-4">
                        <div className={cn(
                          'w-10 h-10 rounded-full flex items-center justify-center',
                          'bg-primary/10 text-primary font-medium'
                        )}>
                          {usuario.nombre.charAt(0).toUpperCase()}
                        </div>
                        <div>
                          <div className="flex items-center gap-2">
                            <span className="font-medium">{usuario.nombre}</span>
                            {isCurrentUser && (
                              <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded">Tú</span>
                            )}
                            {!usuario.active && (
                              <span className="text-xs bg-destructive/10 text-destructive px-2 py-0.5 rounded">Inactivo</span>
                            )}
                          </div>
                          <div className="text-sm text-muted-foreground">{usuario.email}</div>
                        </div>
                      </div>
                      <div className="flex items-center gap-4">
                        <div className={cn('flex items-center gap-1', roleInfo.color)}>
                          <RoleIcon className="h-4 w-4" />
                          <span className="text-sm">{roleInfo.label}</span>
                        </div>
                        {isAdmin && !isCurrentUser && (
                          <div className="flex gap-1">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleToggleActive(usuario.id, usuario.active)}
                            >
                              {usuario.active ? 'Desactivar' : 'Activar'}
                            </Button>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => handleDelete(usuario.id)}
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </DashboardShell>
  );
}
