"use client"

import { useState } from "react"
import useSWR from "swr"
import {
  Search,
  MoreHorizontal,
  UserPlus,
  Mail,
  Ban,
  ChevronLeft,
  ChevronRight,
  Trash2,
  Eye,
  Edit,
  Loader2,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { ConfirmDialog } from "@/components/confirm-dialog"
import Link from "next/link"
import { useToast } from "@/hooks/use-toast"

const fetcher = (url: string) => fetch(url).then((res) => res.json())

export default function AdminUsersPage() {
  const { toast } = useToast()
  const { data, error, isLoading, mutate } = useSWR("/api/users", fetcher, {
    dedupingInterval: 60000,
  })
  const users = data?.data || []
  const totalUsers = data?.total || 0

  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [planFilter, setPlanFilter] = useState("all")
  const [selectedUsers, setSelectedUsers] = useState<string[]>([])
  const [showAddUser, setShowAddUser] = useState(false)
  const [showEditUser, setShowEditUser] = useState<any | null>(null)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null)
  const [showBulkDeleteConfirm, setShowBulkDeleteConfirm] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [isSaving, setIsSaving] = useState(false)
  const usersPerPage = 10

  const [formData, setFormData] = useState({
    name: "",
    email: "",
    subscription_type: "free",
  })

  const filteredUsers = users.filter((user: any) => {
    const matchesSearch =
      user.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.email?.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesStatus = statusFilter === "all" || (statusFilter === "active" ? user.is_active : !user.is_active)
    const matchesPlan = planFilter === "all" || user.subscription_type === planFilter
    return matchesSearch && matchesStatus && matchesPlan
  })

  const paginatedUsers = filteredUsers.slice((currentPage - 1) * usersPerPage, currentPage * usersPerPage)
  const totalPages = Math.ceil(filteredUsers.length / usersPerPage)

  const handleSelectUser = (userId: string) => {
    setSelectedUsers((prev) => (prev.includes(userId) ? prev.filter((id) => id !== userId) : [...prev, userId]))
  }

  const handleSelectAll = () => {
    if (selectedUsers.length === paginatedUsers.length) {
      setSelectedUsers([])
    } else {
      setSelectedUsers(paginatedUsers.map((u: any) => u.id))
    }
  }

  const handleAddUser = async () => {
    setIsSaving(true)
    try {
      const res = await fetch("/api/users", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: formData.name,
          email: formData.email,
          password: "password123",
          subscription_type: formData.subscription_type,
        }),
      })
      if (res.ok) {
        toast({ title: "Utilisateur créé avec succès" })
        mutate()
        setShowAddUser(false)
        setFormData({ name: "", email: "", subscription_type: "free" })
      } else {
        const err = await res.json()
        toast({ title: "Erreur", description: err.error, variant: "destructive" })
      }
    } catch (e) {
      toast({ title: "Erreur", description: "Impossible de créer l'utilisateur", variant: "destructive" })
    }
    setIsSaving(false)
  }

  const handleEditUser = async () => {
    if (!showEditUser) return
    setIsSaving(true)
    try {
      const res = await fetch(`/api/users/${showEditUser.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: formData.name,
          email: formData.email,
          subscription_type: formData.subscription_type,
        }),
      })
      if (res.ok) {
        toast({ title: "Utilisateur modifié avec succès" })
        mutate()
        setShowEditUser(null)
        setFormData({ name: "", email: "", subscription_type: "free" })
      } else {
        toast({ title: "Erreur", variant: "destructive" })
      }
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
    setIsSaving(false)
  }

  const handleDeleteUser = async (userId: string) => {
    try {
      const res = await fetch(`/api/users/${userId}`, { method: "DELETE" })
      if (res.ok) {
        toast({ title: "Utilisateur supprimé" })
        mutate()
      }
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
  }

  const handleSuspendUser = async (userId: string, isActive: boolean) => {
    try {
      const res = await fetch(`/api/users/${userId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ is_active: !isActive }),
      })
      if (res.ok) {
        toast({ title: isActive ? "Utilisateur suspendu" : "Utilisateur réactivé" })
        mutate()
      }
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
  }

  const handleBulkDelete = async () => {
    for (const userId of selectedUsers) {
      await fetch(`/api/users/${userId}`, { method: "DELETE" })
    }
    toast({ title: `${selectedUsers.length} utilisateurs supprimés` })
    setSelectedUsers([])
    mutate()
  }

  const getPlanBadge = (plan: string) => {
    switch (plan) {
      case "premium":
        return <Badge className="bg-purple-500/20 text-purple-400 border-0">Premium</Badge>
      case "family":
        return <Badge className="bg-blue-500/20 text-blue-400 border-0">Famille</Badge>
      case "student":
        return <Badge className="bg-green-500/20 text-green-400 border-0">Étudiant</Badge>
      default:
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Gratuit</Badge>
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Utilisateurs</h1>
          <p className="text-zinc-400 text-sm">{totalUsers} utilisateurs au total</p>
        </div>
        <Button onClick={() => setShowAddUser(true)} className="bg-purple-600 hover:bg-purple-700">
          <UserPlus className="w-4 h-4 mr-2" />
          Nouvel utilisateur
        </Button>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
          <Input
            placeholder="Rechercher un utilisateur..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10 bg-zinc-800 border-zinc-700 text-white"
          />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-40 bg-zinc-800 border-zinc-700 text-white">
            <SelectValue placeholder="Statut" />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="all">Tous</SelectItem>
            <SelectItem value="active">Actif</SelectItem>
            <SelectItem value="inactive">Inactif</SelectItem>
          </SelectContent>
        </Select>
        <Select value={planFilter} onValueChange={setPlanFilter}>
          <SelectTrigger className="w-40 bg-zinc-800 border-zinc-700 text-white">
            <SelectValue placeholder="Abonnement" />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="all">Tous</SelectItem>
            <SelectItem value="free">Gratuit</SelectItem>
            <SelectItem value="premium">Premium</SelectItem>
            <SelectItem value="family">Famille</SelectItem>
            <SelectItem value="student">Étudiant</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Bulk Actions */}
      {selectedUsers.length > 0 && (
        <div className="flex items-center gap-4 p-4 bg-zinc-800/50 rounded-lg">
          <span className="text-white text-sm">{selectedUsers.length} sélectionné(s)</span>
          <Button variant="outline" size="sm" onClick={() => setSelectedUsers([])}>
            Désélectionner
          </Button>
          <Button variant="destructive" size="sm" onClick={() => setShowBulkDeleteConfirm(true)}>
            <Trash2 className="w-4 h-4 mr-2" />
            Supprimer
          </Button>
        </div>
      )}

      {/* Users Table */}
      {users.length === 0 ? (
        <div className="text-center py-16 bg-zinc-800/50 rounded-xl border border-zinc-700/50">
          <UserPlus className="w-16 h-16 mx-auto mb-4 text-zinc-600" />
          <h3 className="text-xl font-medium text-white mb-2">Aucun utilisateur</h3>
          <p className="text-zinc-400 mb-6">Commencez par ajouter des utilisateurs</p>
          <Button onClick={() => setShowAddUser(true)} className="bg-purple-600 hover:bg-purple-700">
            <UserPlus className="w-4 h-4 mr-2" />
            Ajouter un utilisateur
          </Button>
        </div>
      ) : (
        <div className="bg-zinc-800/50 rounded-xl border border-zinc-700/50 overflow-hidden">
          <table className="w-full">
            <thead className="bg-zinc-800">
              <tr>
                <th className="p-4 text-left">
                  <input
                    type="checkbox"
                    checked={selectedUsers.length === paginatedUsers.length && paginatedUsers.length > 0}
                    onChange={handleSelectAll}
                    className="rounded bg-zinc-700 border-zinc-600"
                  />
                </th>
                <th className="p-4 text-left text-zinc-400 text-sm font-medium">Utilisateur</th>
                <th className="p-4 text-left text-zinc-400 text-sm font-medium hidden md:table-cell">Abonnement</th>
                <th className="p-4 text-left text-zinc-400 text-sm font-medium hidden lg:table-cell">Statut</th>
                <th className="p-4 text-left text-zinc-400 text-sm font-medium hidden lg:table-cell">Inscrit le</th>
                <th className="p-4 text-right text-zinc-400 text-sm font-medium">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-700/50">
              {paginatedUsers.map((user: any) => (
                <tr key={user.id} className="hover:bg-zinc-800/30">
                  <td className="p-4">
                    <input
                      type="checkbox"
                      checked={selectedUsers.includes(user.id)}
                      onChange={() => handleSelectUser(user.id)}
                      className="rounded bg-zinc-700 border-zinc-600"
                    />
                  </td>
                  <td className="p-4">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-full bg-zinc-700 overflow-hidden">
                        <img
                          src={user.avatar_url || "/placeholder.svg?height=40&width=40&query=user avatar"}
                          alt={user.name}
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <div>
                        <p className="text-white font-medium">{user.name}</p>
                        <p className="text-zinc-400 text-sm">{user.email}</p>
                      </div>
                    </div>
                  </td>
                  <td className="p-4 hidden md:table-cell">{getPlanBadge(user.subscription_type || "free")}</td>
                  <td className="p-4 hidden lg:table-cell">
                    <Badge
                      className={
                        user.is_active
                          ? "bg-green-500/20 text-green-400 border-0"
                          : "bg-red-500/20 text-red-400 border-0"
                      }
                    >
                      {user.is_active ? "Actif" : "Inactif"}
                    </Badge>
                  </td>
                  <td className="p-4 text-zinc-400 text-sm hidden lg:table-cell">
                    {user.created_at ? new Date(user.created_at).toLocaleDateString("fr-FR") : "-"}
                  </td>
                  <td className="p-4 text-right">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="text-zinc-400 hover:text-white">
                          <MoreHorizontal className="w-4 h-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                        <DropdownMenuItem asChild className="text-zinc-300">
                          <Link href={`/admin/users/${user.id}`}>
                            <Eye className="w-4 h-4 mr-2" /> Voir les détails
                          </Link>
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={() => {
                            setFormData({
                              name: user.name,
                              email: user.email,
                              subscription_type: user.subscription_type || "free",
                            })
                            setShowEditUser(user)
                          }}
                          className="text-zinc-300"
                        >
                          <Edit className="w-4 h-4 mr-2" /> Modifier
                        </DropdownMenuItem>
                        <DropdownMenuItem className="text-zinc-300">
                          <Mail className="w-4 h-4 mr-2" /> Envoyer un email
                        </DropdownMenuItem>
                        <DropdownMenuSeparator className="bg-zinc-700" />
                        <DropdownMenuItem
                          onClick={() => handleSuspendUser(user.id, user.is_active)}
                          className="text-yellow-400"
                        >
                          <Ban className="w-4 h-4 mr-2" /> {user.is_active ? "Suspendre" : "Réactiver"}
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => setShowDeleteConfirm(user.id)} className="text-red-400">
                          <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between px-4 py-3 border-t border-zinc-700/50">
              <p className="text-zinc-400 text-sm">
                Affichage de {(currentPage - 1) * usersPerPage + 1} à{" "}
                {Math.min(currentPage * usersPerPage, filteredUsers.length)} sur {filteredUsers.length}
              </p>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="icon"
                  onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                  className="bg-zinc-800 border-zinc-700"
                >
                  <ChevronLeft className="w-4 h-4" />
                </Button>
                <span className="text-white text-sm px-2">
                  {currentPage} / {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="icon"
                  onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages}
                  className="bg-zinc-800 border-zinc-700"
                >
                  <ChevronRight className="w-4 h-4" />
                </Button>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Add User Dialog */}
      <Dialog open={showAddUser} onOpenChange={setShowAddUser}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Nouvel utilisateur</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Ajoutez un nouvel utilisateur à la plateforme
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Nom complet</Label>
              <Input
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="Jean Dupont"
              />
            </div>
            <div className="space-y-2">
              <Label>Email</Label>
              <Input
                type="email"
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="jean@example.com"
              />
            </div>
            <div className="space-y-2">
              <Label>Abonnement</Label>
              <Select
                value={formData.subscription_type}
                onValueChange={(v) => setFormData({ ...formData, subscription_type: v })}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="free">Gratuit</SelectItem>
                  <SelectItem value="premium">Premium</SelectItem>
                  <SelectItem value="family">Famille</SelectItem>
                  <SelectItem value="student">Étudiant</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowAddUser(false)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleAddUser} disabled={isSaving}>
              {isSaving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
              Créer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit User Dialog */}
      <Dialog open={!!showEditUser} onOpenChange={() => setShowEditUser(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Modifier l'utilisateur</DialogTitle>
            <DialogDescription className="text-zinc-400">Modifiez les informations de l'utilisateur</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Nom complet</Label>
              <Input
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
              />
            </div>
            <div className="space-y-2">
              <Label>Email</Label>
              <Input
                type="email"
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
              />
            </div>
            <div className="space-y-2">
              <Label>Abonnement</Label>
              <Select
                value={formData.subscription_type}
                onValueChange={(v) => setFormData({ ...formData, subscription_type: v })}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="free">Gratuit</SelectItem>
                  <SelectItem value="premium">Premium</SelectItem>
                  <SelectItem value="family">Famille</SelectItem>
                  <SelectItem value="student">Étudiant</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowEditUser(null)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleEditUser} disabled={isSaving}>
              {isSaving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
              Sauvegarder
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation */}
      <ConfirmDialog
        open={!!showDeleteConfirm}
        onOpenChange={() => setShowDeleteConfirm(null)}
        title="Supprimer l'utilisateur"
        description="Êtes-vous sûr de vouloir supprimer cet utilisateur ? Cette action est irréversible."
        onConfirm={() => {
          if (showDeleteConfirm) handleDeleteUser(showDeleteConfirm)
          setShowDeleteConfirm(null)
        }}
        confirmText="Supprimer"
        destructive
      />

      {/* Bulk Delete Confirmation */}
      <ConfirmDialog
        open={showBulkDeleteConfirm}
        onOpenChange={setShowBulkDeleteConfirm}
        title="Supprimer les utilisateurs"
        description={`Êtes-vous sûr de vouloir supprimer ${selectedUsers.length} utilisateurs ? Cette action est irréversible.`}
        onConfirm={() => {
          handleBulkDelete()
          setShowBulkDeleteConfirm(false)
        }}
        confirmText="Supprimer"
        destructive
      />
    </div>
  )
}
