"use client"

import { useState } from "react"
import { AlertTriangle, Flag, CheckCircle, XCircle, Eye, MessageSquare, Clock, Search, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import useSWR, { mutate } from "swr"

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

export default function AdminModerationPage() {
  const { data, isLoading, error } = useSWR("/api/admin/moderation", fetcher)

  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [selectedReport, setSelectedReport] = useState<any | null>(null)
  const [showActionDialog, setShowActionDialog] = useState(false)
  const [actionNote, setActionNote] = useState("")
  const [selectedAction, setSelectedAction] = useState("dismiss")

  const contentReports = data?.reports || []
  const pendingContent = data?.pendingContent || []

  const filteredContentReports = contentReports.filter((report: any) => {
    const matchesSearch =
      report.reason?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      report.type?.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesStatus = statusFilter === "all" || report.status === statusFilter
    return matchesSearch && matchesStatus
  })

  const getPriorityBadge = (priority: string) => {
    switch (priority) {
      case "high":
        return <Badge className="bg-red-500/20 text-red-400 border-0">Haute</Badge>
      case "medium":
        return <Badge className="bg-yellow-500/20 text-yellow-400 border-0">Moyenne</Badge>
      default:
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Basse</Badge>
    }
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "pending":
        return <Badge className="bg-yellow-500/20 text-yellow-400 border-0">En attente</Badge>
      case "reviewed":
        return <Badge className="bg-blue-500/20 text-blue-400 border-0">Examiné</Badge>
      case "resolved":
        return <Badge className="bg-green-500/20 text-green-400 border-0">Résolu</Badge>
      default:
        return <Badge>{status}</Badge>
    }
  }

  const handleApproveReport = async (id: string) => {
    await fetch(`/api/admin/moderation/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: "resolved", action: "approve" }),
    })
    mutate("/api/admin/moderation")
  }

  const handleRejectReport = async (id: string) => {
    await fetch(`/api/admin/moderation/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: "resolved", action: "reject" }),
    })
    mutate("/api/admin/moderation")
  }

  const handleApplyAction = async () => {
    if (selectedReport) {
      await fetch(`/api/admin/moderation/${selectedReport.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: "resolved", action: selectedAction, note: actionNote }),
      })
      mutate("/api/admin/moderation")
    }
    setShowActionDialog(false)
    setSelectedReport(null)
    setActionNote("")
  }

  const pendingCount = contentReports.filter((r: any) => r.status === "pending").length

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

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <p className="text-red-400">Erreur lors du chargement des données</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-white">Modération</h1>
        <p className="text-zinc-400 text-sm">Gérez les signalements et la modération du contenu</p>
      </div>

      {/* Stats */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">En attente</CardTitle>
            <Clock className="w-4 h-4 text-yellow-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{pendingCount}</div>
            <p className="text-xs text-zinc-400">signalements à traiter</p>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">Contenu en attente</CardTitle>
            <AlertTriangle className="w-4 h-4 text-red-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{pendingContent.length}</div>
            <p className="text-xs text-zinc-400">à valider</p>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">Total signalements</CardTitle>
            <CheckCircle className="w-4 h-4 text-green-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{contentReports.length}</div>
            <p className="text-xs text-zinc-400">signalements</p>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">Résolus</CardTitle>
            <Clock className="w-4 h-4 text-blue-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">
              {contentReports.filter((r: any) => r.status === "resolved").length}
            </div>
            <p className="text-xs text-zinc-400">traités</p>
          </CardContent>
        </Card>
      </div>

      {/* Tabs */}
      <Tabs defaultValue="content" className="space-y-4">
        <TabsList className="bg-zinc-800/50 border border-zinc-700">
          <TabsTrigger value="content" className="data-[state=active]:bg-purple-600">
            Signalements ({contentReports.length})
          </TabsTrigger>
          <TabsTrigger value="pending" className="data-[state=active]:bg-purple-600">
            En attente de validation ({pendingContent.length})
          </TabsTrigger>
        </TabsList>

        <TabsContent value="content" className="space-y-4">
          {/* Filters */}
          <div className="flex flex-col gap-4 sm:flex-row">
            <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..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-full sm:w-40 bg-zinc-800/50 border-zinc-700 text-white">
                <SelectValue placeholder="Statut" />
              </SelectTrigger>
              <SelectContent className="bg-zinc-800 border-zinc-700">
                <SelectItem value="all">Tous</SelectItem>
                <SelectItem value="pending">En attente</SelectItem>
                <SelectItem value="reviewed">Examiné</SelectItem>
                <SelectItem value="resolved">Résolu</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Content Reports */}
          <div className="space-y-3">
            {filteredContentReports.length > 0 ? (
              filteredContentReports.map((report: any) => (
                <div
                  key={report.id}
                  className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4 hover:bg-zinc-800/50 transition-colors"
                >
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex items-start gap-4">
                      <div className="w-10 h-10 bg-red-500/20 rounded-lg flex items-center justify-center flex-shrink-0">
                        <Flag className="w-5 h-5 text-red-400" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2 flex-wrap">
                          <h3 className="font-medium text-white">{report.reason || "Signalement"}</h3>
                          <Badge variant="outline" className="border-zinc-600 text-zinc-300 text-xs">
                            {report.type}
                          </Badge>
                        </div>
                        <p className="text-sm text-zinc-400 mt-1">Signalé par {report.reporter}</p>
                        <p className="text-xs text-zinc-500 mt-1">{report.createdAt}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      {getStatusBadge(report.status)}
                      {report.status === "pending" && (
                        <div className="flex gap-1">
                          <Button
                            size="sm"
                            variant="ghost"
                            className="text-zinc-400 hover:text-white"
                            onClick={() => {
                              setSelectedReport(report)
                              setShowActionDialog(true)
                            }}
                          >
                            <Eye className="w-4 h-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            className="text-green-400 hover:text-green-300"
                            onClick={() => handleApproveReport(report.id)}
                          >
                            <CheckCircle className="w-4 h-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            className="text-red-400 hover:text-red-300"
                            onClick={() => handleRejectReport(report.id)}
                          >
                            <XCircle className="w-4 h-4" />
                          </Button>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className="p-8 text-center text-zinc-400">Aucun signalement</div>
            )}
          </div>
        </TabsContent>

        <TabsContent value="pending" className="space-y-4">
          {/* Pending Content */}
          <div className="space-y-3">
            {pendingContent.length > 0 ? (
              pendingContent.map((content: any) => (
                <div
                  key={content.id}
                  className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4 hover:bg-zinc-800/50 transition-colors"
                >
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex items-start gap-4">
                      <div className="w-10 h-10 bg-yellow-500/20 rounded-lg flex items-center justify-center flex-shrink-0">
                        <MessageSquare className="w-5 h-5 text-yellow-400" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <h3 className="font-medium text-white">{content.title}</h3>
                          <Badge variant="outline" className="border-zinc-600 text-zinc-300 text-xs">
                            {content.type}
                          </Badge>
                        </div>
                        <p className="text-sm text-zinc-400 mt-1">Par {content.artist}</p>
                        <p className="text-xs text-zinc-500 mt-1">{content.submittedAt}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Button size="sm" variant="ghost" className="text-green-400 hover:text-green-300">
                        Approuver
                      </Button>
                      <Button size="sm" variant="ghost" className="text-red-400 hover:text-red-300">
                        Rejeter
                      </Button>
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className="p-8 text-center text-zinc-400">Aucun contenu en attente</div>
            )}
          </div>
        </TabsContent>
      </Tabs>

      {/* Action Dialog */}
      <Dialog open={showActionDialog} onOpenChange={setShowActionDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Examiner le signalement</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Prenez une décision concernant ce signalement
            </DialogDescription>
          </DialogHeader>
          {selectedReport && (
            <div className="space-y-4 py-4">
              <div className="bg-zinc-800/50 rounded-lg p-4">
                <h4 className="font-medium text-white">{selectedReport.reason}</h4>
                <p className="text-sm text-zinc-400 mt-1">Type: {selectedReport.type}</p>
              </div>
              <div className="space-y-2">
                <Label>Note de modération</Label>
                <Textarea
                  value={actionNote}
                  onChange={(e) => setActionNote(e.target.value)}
                  className="bg-zinc-800 border-zinc-700 min-h-20"
                  placeholder="Ajoutez une note sur votre décision..."
                />
              </div>
              <div className="space-y-2">
                <Label>Action</Label>
                <Select value={selectedAction} onValueChange={setSelectedAction}>
                  <SelectTrigger className="bg-zinc-800 border-zinc-700">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-zinc-800 border-zinc-700">
                    <SelectItem value="dismiss">Rejeter le signalement</SelectItem>
                    <SelectItem value="warn">Avertir l'utilisateur</SelectItem>
                    <SelectItem value="remove">Supprimer le contenu</SelectItem>
                    <SelectItem value="ban">Bannir l'utilisateur</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowActionDialog(false)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleApplyAction}>
              Appliquer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
