"use client";

import { useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from "@/components/ui/table";
import { 
  DropdownMenu, 
  DropdownMenuContent, 
  DropdownMenuItem, 
  DropdownMenuLabel, 
  DropdownMenuSeparator, 
  DropdownMenuTrigger 
} from "@/components/ui/dropdown-menu";
import { 
  PlusCircle, 
  Search, 
  MoreHorizontal, 
  Pencil, 
  Trash2, 
  Shield,
  UserCog
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";

export default function AdminUsersPage() {
  const [searchQuery, setSearchQuery] = useState("");

  // Mock data for users
  const users = [
    {
      id: 1,
      name: "Jean Dupont",
      email: "jean.dupont@example.com",
      role: "user",
      status: "active",
      lastLogin: "2025-05-15T14:32:00",
      projects: 3,
    },
    {
      id: 2,
      name: "Marie Martin",
      email: "marie.martin@example.com",
      role: "admin",
      status: "active",
      lastLogin: "2025-05-15T13:45:00",
      projects: 5,
    },
    {
      id: 3,
      name: "Pierre Durand",
      email: "pierre.durand@example.com",
      role: "user",
      status: "inactive",
      lastLogin: "2025-05-10T11:20:00",
      projects: 1,
    },
    {
      id: 4,
      name: "Sophie Lefebvre",
      email: "sophie.lefebvre@example.com",
      role: "user",
      status: "active",
      lastLogin: "2025-05-15T10:15:00",
      projects: 2,
    },
    {
      id: 5,
      name: "Thomas Bernard",
      email: "thomas.bernard@example.com",
      role: "admin",
      status: "active",
      lastLogin: "2025-05-14T16:30:00",
      projects: 0,
    },
  ];

  // Filter users based on search query
  const filteredUsers = users.filter(
    (user) =>
      user.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.role.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleDeleteUser = (userId: number) => {
    toast.success(`Utilisateur #${userId} supprimé avec succès`);
  };

  const handleChangeRole = (userId: number, newRole: string) => {
    toast.success(`Rôle de l'utilisateur #${userId} changé en ${newRole}`);
  };

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <h1 className="text-2xl sm:text-3xl font-bold">Gestion des utilisateurs</h1>
        <Button asChild className="w-full sm:w-auto">
          <Link href="/admin/users/new">
            <PlusCircle className="mr-2 h-4 w-4" />
            Nouvel utilisateur
          </Link>
        </Button>
      </div>

      <div className="flex items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            type="search"
            placeholder="Rechercher des utilisateurs..."
            className="pl-8"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
      </div>

      {/* Mobile card view */}
      <div className="grid gap-4 sm:hidden">
        {filteredUsers.length === 0 ? (
          <div className="rounded-md border p-6 text-center text-muted-foreground">
            Aucun utilisateur trouvé.
          </div>
        ) : (
          filteredUsers.map((user) => (
            <div key={user.id} className="rounded-md border p-4">
              <div className="flex items-center justify-between">
                <div className="flex flex-col">
                  <span className="font-medium">{user.name}</span>
                  <span className="text-sm text-muted-foreground">{user.email}</span>
                </div>
                <Badge variant={user.role === "admin" ? "default" : "outline"}>
                  {user.role === "admin" ? (
                    <Shield className="mr-1 h-3 w-3" />
                  ) : null}
                  {user.role === "admin" ? "Admin" : "Utilisateur"}
                </Badge>
              </div>
              <div className="mt-2 grid grid-cols-2 gap-2 text-sm">
                <div>
                  <span className="text-muted-foreground">Statut: </span>
                  <Badge variant={user.status === "active" ? "secondary" : "destructive"} className="ml-1">
                    {user.status === "active" ? "Actif" : "Inactif"}
                  </Badge>
                </div>
                <div>
                  <span className="text-muted-foreground">Projets: </span>
                  <span>{user.projects}</span>
                </div>
                <div className="col-span-2">
                  <span className="text-muted-foreground">Dernière connexion: </span>
                  <span>
                    {new Date(user.lastLogin).toLocaleString("fr-FR", {
                      dateStyle: "medium",
                      timeStyle: "short",
                    })}
                  </span>
                </div>
              </div>
              <div className="mt-4 flex justify-end gap-2">
                <Button variant="outline" size="sm" asChild>
                  <Link href={`/admin/users/${user.id}`}>
                    <UserCog className="mr-2 h-4 w-4" />
                    Gérer
                  </Link>
                </Button>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" size="sm">
                      <MoreHorizontal className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuLabel>Actions</DropdownMenuLabel>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem asChild>
                      <Link href={`/admin/users/${user.id}/edit`}>
                        <Pencil className="mr-2 h-4 w-4" />
                        Modifier
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      onClick={() => handleChangeRole(user.id, user.role === "admin" ? "user" : "admin")}
                    >
                      <Shield className="mr-2 h-4 w-4" />
                      {user.role === "admin" ? "Retirer les droits admin" : "Promouvoir admin"}
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      onClick={() => handleDeleteUser(user.id)}
                      className="text-destructive focus:text-destructive"
                    >
                      <Trash2 className="mr-2 h-4 w-4" />
                      Supprimer
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            </div>
          ))
        )}
      </div>

      {/* Desktop table view */}
      <div className="rounded-md border hidden sm:block overflow-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Nom</TableHead>
              <TableHead>Email</TableHead>
              <TableHead>Rôle</TableHead>
              <TableHead>Statut</TableHead>
              <TableHead>Dernière connexion</TableHead>
              <TableHead>Projets</TableHead>
              <TableHead className="w-[100px]">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredUsers.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="h-24 text-center">
                  Aucun utilisateur trouvé.
                </TableCell>
              </TableRow>
            ) : (
              filteredUsers.map((user) => (
                <TableRow key={user.id}>
                  <TableCell className="font-medium">{user.name}</TableCell>
                  <TableCell>{user.email}</TableCell>
                  <TableCell>
                    <Badge variant={user.role === "admin" ? "default" : "outline"}>
                      {user.role === "admin" ? (
                        <Shield className="mr-1 h-3 w-3" />
                      ) : null}
                      {user.role === "admin" ? "Admin" : "Utilisateur"}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <Badge variant={user.status === "active" ? "secondary" : "destructive"}>
                      {user.status === "active" ? "Actif" : "Inactif"}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {new Date(user.lastLogin).toLocaleString("fr-FR", {
                      dateStyle: "medium",
                      timeStyle: "short",
                    })}
                  </TableCell>
                  <TableCell>{user.projects}</TableCell>
                  <TableCell>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon">
                          <MoreHorizontal className="h-4 w-4" />
                          <span className="sr-only">Actions</span>
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuLabel>Actions</DropdownMenuLabel>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem asChild>
                          <Link href={`/admin/users/${user.id}/edit`} className="flex items-center">
                            <Pencil className="mr-2 h-4 w-4" />
                            <span>Modifier</span>
                          </Link>
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={() => handleChangeRole(user.id, user.role === "admin" ? "user" : "admin")}
                          className="flex items-center"
                        >
                          <Shield className="mr-2 h-4 w-4" />
                          <span>{user.role === "admin" ? "Retirer les droits admin" : "Promouvoir admin"}</span>
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={() => handleDeleteUser(user.id)}
                          className="text-destructive focus:text-destructive flex items-center"
                        >
                          <Trash2 className="mr-2 h-4 w-4" />
                          <span>Supprimer</span>
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
