import { useAuth } from "@/_core/hooks/useAuth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Spinner } from "@/components/ui/spinner";
import { toast } from "sonner";
import { trpc } from "@/lib/trpc";
import { useState } from "react";
import { Users, TrendingUp, Clock, Activity, Plus, Trash2, Edit2 } from "lucide-react";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";

export default function AdminDashboard() {
  const { user, loading: authLoading } = useAuth();
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<any>(null);
  const [formData, setFormData] = useState({
    username: "",
    password: "",
    expirationDate: "",
    maxConnections: "1",
  });

  // Fetch dashboard stats
  const { data: stats, isLoading: statsLoading } = trpc.admin.getDashboardStats.useQuery();

  // Fetch users list
  const { data: users = [], isLoading: usersLoading, refetch: refetchUsers } = trpc.admin.listXtreamUsers.useQuery();

  // Create user mutation
  const createUserMutation = trpc.admin.createXtreamUser.useMutation({
    onSuccess: () => {
      toast.success("Usuário criado com sucesso!");
      setFormData({ username: "", password: "", expirationDate: "", maxConnections: "1" });
      setIsCreateDialogOpen(false);
      refetchUsers();
    },
    onError: (error) => {
      toast.error(error.message || "Erro ao criar usuário");
    },
  });

  // Update user mutation
  const updateUserMutation = trpc.admin.updateXtreamUser.useMutation({
    onSuccess: () => {
      toast.success("Usuário atualizado com sucesso!");
      setFormData({ username: "", password: "", expirationDate: "", maxConnections: "1" });
      setIsEditDialogOpen(false);
      setEditingUser(null);
      refetchUsers();
    },
    onError: (error) => {
      toast.error(error.message || "Erro ao atualizar usuário");
    },
  });

  // Delete user mutation
  const deleteUserMutation = trpc.admin.deleteXtreamUser.useMutation({
    onSuccess: () => {
      toast.success("Usuário deletado com sucesso!");
      refetchUsers();
    },
    onError: (error) => {
      toast.error(error.message || "Erro ao deletar usuário");
    },
  });

  // Check if user is admin
  if (authLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Spinner />
      </div>
    );
  }

  if (user?.role !== "admin") {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Card className="w-full max-w-md">
          <CardHeader>
            <CardTitle>Acesso Negado</CardTitle>
            <CardDescription>Você não tem permissão para acessar o painel administrativo.</CardDescription>
          </CardHeader>
        </Card>
      </div>
    );
  }

  const handleCreateUser = () => {
    if (!formData.username || !formData.password) {
      toast.error("Preencha todos os campos obrigatórios");
      return;
    }

    createUserMutation.mutate({
      username: formData.username,
      password: formData.password,
      expirationDate: formData.expirationDate ? new Date(formData.expirationDate) : undefined,
      maxConnections: parseInt(formData.maxConnections),
    });
  };

  const handleEditUser = (user: any) => {
    setEditingUser(user);
    setFormData({
      username: user.username,
      password: user.password,
      expirationDate: user.expirationDate ? format(new Date(user.expirationDate), "yyyy-MM-dd") : "",
      maxConnections: String(user.maxConnections),
    });
    setIsEditDialogOpen(true);
  };

  const handleUpdateUser = () => {
    if (!formData.username || !formData.password) {
      toast.error("Preencha todos os campos obrigatórios");
      return;
    }

    updateUserMutation.mutate({
      id: editingUser.id,
      username: formData.username,
      password: formData.password,
      expirationDate: formData.expirationDate ? new Date(formData.expirationDate) : undefined,
      maxConnections: parseInt(formData.maxConnections),
      isActive: editingUser.isActive,
    });
  };

  const handleDeleteUser = (userId: number) => {
    if (confirm("Tem certeza que deseja deletar este usuário?")) {
      deleteUserMutation.mutate(userId);
    }
  };

  const isUserExpired = (user: any) => {
    if (!user.expirationDate) return false;
    return new Date(user.expirationDate) < new Date();
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-12">
          <h1 className="text-4xl font-bold text-slate-900 mb-2">Painel Administrativo</h1>
          <p className="text-lg text-slate-600">Gerencie usuários e monitore o sistema</p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-12">
          <Card className="border-0 shadow-lg hover:shadow-xl transition-shadow">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-medium text-slate-600 flex items-center gap-2">
                <Users className="w-4 h-4" />
                Total de Usuários
              </CardTitle>
            </CardHeader>
            <CardContent>
              {statsLoading ? (
                <Spinner />
              ) : (
                <div className="text-3xl font-bold text-slate-900">{stats?.totalUsers || 0}</div>
              )}
            </CardContent>
          </Card>

          <Card className="border-0 shadow-lg hover:shadow-xl transition-shadow">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-medium text-slate-600 flex items-center gap-2">
                <TrendingUp className="w-4 h-4 text-green-600" />
                Usuários Ativos
              </CardTitle>
            </CardHeader>
            <CardContent>
              {statsLoading ? (
                <Spinner />
              ) : (
                <div className="text-3xl font-bold text-green-600">{stats?.activeUsers || 0}</div>
              )}
            </CardContent>
          </Card>

          <Card className="border-0 shadow-lg hover:shadow-xl transition-shadow">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-medium text-slate-600 flex items-center gap-2">
                <Clock className="w-4 h-4 text-orange-600" />
                Usuários Expirados
              </CardTitle>
            </CardHeader>
            <CardContent>
              {statsLoading ? (
                <Spinner />
              ) : (
                <div className="text-3xl font-bold text-orange-600">{stats?.expiredUsers || 0}</div>
              )}
            </CardContent>
          </Card>

          <Card className="border-0 shadow-lg hover:shadow-xl transition-shadow">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-medium text-slate-600 flex items-center gap-2">
                <Activity className="w-4 h-4 text-blue-600" />
                Conexões Ativas
              </CardTitle>
            </CardHeader>
            <CardContent>
              {statsLoading ? (
                <Spinner />
              ) : (
                <div className="text-3xl font-bold text-blue-600">{stats?.totalConnections || 0}</div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Users Management Section */}
        <Card className="border-0 shadow-lg">
          <CardHeader className="pb-6 border-b">
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-2xl">Gerenciar Usuários</CardTitle>
                <CardDescription>Crie, edite ou delete usuários do sistema</CardDescription>
              </div>
              <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
                <DialogTrigger asChild>
                  <Button className="gap-2">
                    <Plus className="w-4 h-4" />
                    Novo Usuário
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-md">
                  <DialogHeader>
                    <DialogTitle>Criar Novo Usuário</DialogTitle>
                    <DialogDescription>Preencha os dados para criar um novo usuário</DialogDescription>
                  </DialogHeader>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="username">Nome de Usuário</Label>
                      <Input
                        id="username"
                        placeholder="usuario123"
                        value={formData.username}
                        onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                      />
                    </div>
                    <div>
                      <Label htmlFor="password">Senha</Label>
                      <Input
                        id="password"
                        type="password"
                        placeholder="••••••••"
                        value={formData.password}
                        onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                      />
                    </div>
                    <div>
                      <Label htmlFor="expirationDate">Data de Expiração (opcional)</Label>
                      <Input
                        id="expirationDate"
                        type="date"
                        value={formData.expirationDate}
                        onChange={(e) => setFormData({ ...formData, expirationDate: e.target.value })}
                      />
                    </div>
                    <div>
                      <Label htmlFor="maxConnections">Limite de Conexões</Label>
                      <Input
                        id="maxConnections"
                        type="number"
                        min="1"
                        value={formData.maxConnections}
                        onChange={(e) => setFormData({ ...formData, maxConnections: e.target.value })}
                      />
                    </div>
                    <Button
                      onClick={handleCreateUser}
                      disabled={createUserMutation.isPending}
                      className="w-full"
                    >
                      {createUserMutation.isPending ? <Spinner /> : "Criar Usuário"}
                    </Button>
                  </div>
                </DialogContent>
              </Dialog>
            </div>
          </CardHeader>

          <CardContent className="pt-6">
            {usersLoading ? (
              <div className="flex justify-center py-8">
                <Spinner />
              </div>
            ) : users.length === 0 ? (
              <div className="text-center py-8 text-slate-500">Nenhum usuário cadastrado</div>
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="border-slate-200">
                      <TableHead>Usuário</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>Expiração</TableHead>
                      <TableHead>Limite Conexões</TableHead>
                      <TableHead className="text-right">Ações</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {users.map((user: any) => (
                      <TableRow key={user.id} className="border-slate-200 hover:bg-slate-50">
                        <TableCell className="font-medium">{user.username}</TableCell>
                        <TableCell>
                          {isUserExpired(user) ? (
                            <Badge variant="destructive">Expirado</Badge>
                          ) : user.isActive ? (
                            <Badge variant="default" className="bg-green-600">
                              Ativo
                            </Badge>
                          ) : (
                            <Badge variant="secondary">Inativo</Badge>
                          )}
                        </TableCell>
                        <TableCell>
                          {user.expirationDate
                            ? format(new Date(user.expirationDate), "dd/MM/yyyy", { locale: ptBR })
                            : "Sem limite"}
                        </TableCell>
                        <TableCell>{user.maxConnections}</TableCell>
                        <TableCell className="text-right">
                          <div className="flex items-center justify-end gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleEditUser(user)}
                            >
                              <Edit2 className="w-4 h-4" />
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleDeleteUser(user.id)}
                              className="text-red-600 hover:text-red-700"
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Edit Dialog */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Editar Usuário</DialogTitle>
            <DialogDescription>Atualize os dados do usuário</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label htmlFor="edit-username">Nome de Usuário</Label>
              <Input
                id="edit-username"
                placeholder="usuario123"
                value={formData.username}
                onChange={(e) => setFormData({ ...formData, username: e.target.value })}
              />
            </div>
            <div>
              <Label htmlFor="edit-password">Senha</Label>
              <Input
                id="edit-password"
                type="password"
                placeholder="••••••••"
                value={formData.password}
                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
              />
            </div>
            <div>
              <Label htmlFor="edit-expirationDate">Data de Expiração (opcional)</Label>
              <Input
                id="edit-expirationDate"
                type="date"
                value={formData.expirationDate}
                onChange={(e) => setFormData({ ...formData, expirationDate: e.target.value })}
              />
            </div>
            <div>
              <Label htmlFor="edit-maxConnections">Limite de Conexões</Label>
              <Input
                id="edit-maxConnections"
                type="number"
                min="1"
                value={formData.maxConnections}
                onChange={(e) => setFormData({ ...formData, maxConnections: e.target.value })}
              />
            </div>
            <Button
              onClick={handleUpdateUser}
              disabled={updateUserMutation.isPending}
              className="w-full"
            >
              {updateUserMutation.isPending ? <Spinner /> : "Atualizar Usuário"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
