"use client"

import { useState } from "react"
import { Shield, CheckCircle, XCircle, Clock, Search, ExternalLink } from "lucide-react"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog"
import { Textarea } from "@/components/ui/textarea"
import { useAuth } from "@/components/auth-provider"
import { useToast } from "@/hooks/use-toast"
import useSWR from "swr"

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

export default function AdminVerificationPage() {
  const { user } = useAuth()
  const { toast } = useToast()
  const [activeTab, setActiveTab] = useState("pending")
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedRequest, setSelectedRequest] = useState<any>(null)
  const [rejectDialogOpen, setRejectDialogOpen] = useState(false)
  const [rejectionReason, setRejectionReason] = useState("")
  const [processing, setProcessing] = useState(false)

  const { data, mutate, isLoading } = useSWR(`/api/admin/verification?status=${activeTab}`, fetcher)

  const requests = data?.requests || []
  const filteredRequests = requests.filter((req: any) =>
    req.artist_name?.toLowerCase().includes(searchQuery.toLowerCase()),
  )

  const approvedThisMonth = data?.stats?.approvedThisMonth || 0
  const rejectedThisMonth = data?.stats?.rejectedThisMonth || 0

  const handleApprove = async (request: any) => {
    setProcessing(true)
    try {
      const response = await fetch("/api/admin/verification", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          request_id: request.id,
          action: "approve",
          admin_id: user?.id,
        }),
      })

      if (!response.ok) throw new Error("Failed to approve")

      toast({
        title: "Artiste verifie",
        description: `${request.artist_name} a ete verifie avec succes.`,
      })

      mutate()
      setSelectedRequest(null)
    } catch (error) {
      toast({
        title: "Erreur",
        description: "Erreur lors de l'approbation",
        variant: "destructive",
      })
    } finally {
      setProcessing(false)
    }
  }

  const handleReject = async () => {
    if (!selectedRequest) return
    setProcessing(true)
    try {
      const response = await fetch("/api/admin/verification", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          request_id: selectedRequest.id,
          action: "reject",
          rejection_reason: rejectionReason,
          admin_id: user?.id,
        }),
      })

      if (!response.ok) throw new Error("Failed to reject")

      toast({
        title: "Demande refusee",
        description: `La demande de ${selectedRequest.artist_name} a ete refusee.`,
      })

      mutate()
      setRejectDialogOpen(false)
      setSelectedRequest(null)
      setRejectionReason("")
    } catch (error) {
      toast({
        title: "Erreur",
        description: "Erreur lors du refus",
        variant: "destructive",
      })
    } finally {
      setProcessing(false)
    }
  }

  const formatDate = (date: string) => {
    return new Date(date).toLocaleDateString("fr-FR", {
      day: "numeric",
      month: "short",
      year: "numeric",
    })
  }

  const formatNumber = (num: number) => {
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
    if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
    return num?.toString() || "0"
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-2">
            <Shield className="w-6 h-6 text-purple-400" />
            Demandes de verification
          </h1>
          <p className="text-zinc-400">Gerez les demandes de verification des artistes</p>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4 flex items-center gap-4">
            <div className="p-3 bg-yellow-500/10 rounded-lg">
              <Clock className="w-6 h-6 text-yellow-400" />
            </div>
            <div>
              <p className="text-zinc-400 text-sm">En attente</p>
              <p className="text-2xl font-bold text-white">{data?.total || 0}</p>
            </div>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4 flex items-center gap-4">
            <div className="p-3 bg-green-500/10 rounded-lg">
              <CheckCircle className="w-6 h-6 text-green-400" />
            </div>
            <div>
              <p className="text-zinc-400 text-sm">Approuvees ce mois</p>
              <p className="text-2xl font-bold text-white">{approvedThisMonth}</p>
            </div>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4 flex items-center gap-4">
            <div className="p-3 bg-red-500/10 rounded-lg">
              <XCircle className="w-6 h-6 text-red-400" />
            </div>
            <div>
              <p className="text-zinc-400 text-sm">Refusees ce mois</p>
              <p className="text-2xl font-bold text-white">{rejectedThisMonth}</p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Tabs and Search */}
      <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="bg-zinc-800">
            <TabsTrigger value="pending">En attente</TabsTrigger>
            <TabsTrigger value="approved">Approuvees</TabsTrigger>
            <TabsTrigger value="rejected">Refusees</TabsTrigger>
            <TabsTrigger value="all">Toutes</TabsTrigger>
          </TabsList>
        </Tabs>
        <div className="relative w-full sm:w-64">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-zinc-500 w-4 h-4" />
          <Input
            placeholder="Rechercher un artiste..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10 bg-zinc-800 border-zinc-700 text-white"
          />
        </div>
      </div>

      {/* Requests List */}
      <Card className="bg-zinc-800/50 border-zinc-700">
        <CardContent className="p-0">
          {isLoading ? (
            <div className="p-8 text-center text-zinc-400">Chargement...</div>
          ) : filteredRequests.length === 0 ? (
            <div className="p-8 text-center text-zinc-400">
              Aucune demande {activeTab === "pending" ? "en attente" : "trouvee"}
            </div>
          ) : (
            <div className="divide-y divide-zinc-700">
              {filteredRequests.map((request: any) => (
                <div key={request.id} className="p-4 hover:bg-zinc-800/50 transition-colors">
                  <div className="flex items-center justify-between gap-4">
                    <div
                      className="flex items-center gap-4 flex-1 cursor-pointer"
                      onClick={() => setSelectedRequest(request)}
                    >
                      <Avatar className="w-12 h-12">
                        <AvatarImage src={request.artist_avatar || "/placeholder.svg"} />
                        <AvatarFallback className="bg-purple-600">{request.artist_name?.[0] || "A"}</AvatarFallback>
                      </Avatar>
                      <div className="flex-1">
                        <p className="text-white font-medium">{request.artist_name}</p>
                        <div className="flex items-center gap-3 text-sm text-zinc-400">
                          <span>{formatNumber(request.total_followers)} followers</span>
                          <span>{formatNumber(request.total_streams)} streams</span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      {request.status === "pending" && (
                        <div className="flex items-center gap-2">
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={(e) => {
                              e.stopPropagation()
                              setSelectedRequest(request)
                              setRejectDialogOpen(true)
                            }}
                            disabled={processing}
                            className="border-red-500/50 text-red-400 hover:bg-red-500/10 hover:border-red-500"
                          >
                            <XCircle className="w-4 h-4 mr-1" />
                            Refuser
                          </Button>
                          <Button
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation()
                              handleApprove(request)
                            }}
                            disabled={processing}
                            className="bg-green-600 hover:bg-green-700 text-white"
                          >
                            <CheckCircle className="w-4 h-4 mr-1" />
                            Approuver
                          </Button>
                        </div>
                      )}
                      <Badge
                        variant="outline"
                        className={
                          request.status === "pending"
                            ? "border-yellow-500 text-yellow-400"
                            : request.status === "approved"
                              ? "border-green-500 text-green-400"
                              : "border-red-500 text-red-400"
                        }
                      >
                        {request.status === "pending"
                          ? "En attente"
                          : request.status === "approved"
                            ? "Approuvee"
                            : "Refusee"}
                      </Badge>
                      <span className="text-zinc-500 text-sm">{formatDate(request.created_at)}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Request Details Dialog */}
      <Dialog open={!!selectedRequest && !rejectDialogOpen} onOpenChange={() => setSelectedRequest(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Shield className="w-5 h-5 text-purple-400" />
              Demande de verification
            </DialogTitle>
          </DialogHeader>

          {selectedRequest && (
            <div className="space-y-6">
              {/* Artist Info */}
              <div className="flex items-center gap-4 p-4 bg-zinc-800/50 rounded-lg">
                <Avatar className="w-16 h-16">
                  <AvatarImage src={selectedRequest.artist_avatar || "/placeholder.svg"} />
                  <AvatarFallback className="bg-purple-600 text-xl">
                    {selectedRequest.artist_name?.[0] || "A"}
                  </AvatarFallback>
                </Avatar>
                <div>
                  <p className="text-xl font-bold text-white">{selectedRequest.artist_name}</p>
                  <div className="flex items-center gap-4 text-sm text-zinc-400 mt-1">
                    <span>{formatNumber(selectedRequest.total_followers)} followers</span>
                    <span>{formatNumber(selectedRequest.total_streams)} streams</span>
                    <span>{formatNumber(selectedRequest.monthly_listeners)} auditeurs/mois</span>
                  </div>
                </div>
              </div>

              {/* Reason */}
              {selectedRequest.reason && (
                <div>
                  <p className="text-sm text-zinc-400 mb-2">Raison de la demande:</p>
                  <p className="text-white bg-zinc-800/50 p-3 rounded-lg">{selectedRequest.reason}</p>
                </div>
              )}

              {/* Social Proof */}
              {selectedRequest.social_proof && (
                <div>
                  <p className="text-sm text-zinc-400 mb-2">Liens sociaux:</p>
                  <div className="flex flex-wrap gap-2">
                    {selectedRequest.social_proof.instagram && (
                      <a
                        href={`https://instagram.com/${selectedRequest.social_proof.instagram.replace("@", "")}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center gap-1 px-3 py-1 bg-zinc-800 rounded-full text-sm text-zinc-300 hover:bg-zinc-700"
                      >
                        Instagram <ExternalLink className="w-3 h-3" />
                      </a>
                    )}
                    {selectedRequest.social_proof.twitter && (
                      <a
                        href={`https://twitter.com/${selectedRequest.social_proof.twitter.replace("@", "")}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center gap-1 px-3 py-1 bg-zinc-800 rounded-full text-sm text-zinc-300 hover:bg-zinc-700"
                      >
                        Twitter <ExternalLink className="w-3 h-3" />
                      </a>
                    )}
                    {selectedRequest.social_proof.website && (
                      <a
                        href={selectedRequest.social_proof.website}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center gap-1 px-3 py-1 bg-zinc-800 rounded-full text-sm text-zinc-300 hover:bg-zinc-700"
                      >
                        Site web <ExternalLink className="w-3 h-3" />
                      </a>
                    )}
                  </div>
                  {selectedRequest.social_proof.press_links?.length > 0 && (
                    <div className="mt-3">
                      <p className="text-xs text-zinc-500 mb-1">Articles de presse:</p>
                      <div className="space-y-1">
                        {selectedRequest.social_proof.press_links.map((link: string, i: number) => (
                          <a
                            key={i}
                            href={link}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="block text-sm text-purple-400 hover:underline truncate"
                          >
                            {link}
                          </a>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Request Info */}
              <div className="flex items-center gap-4 text-sm text-zinc-400">
                <span>Soumise le {formatDate(selectedRequest.created_at)}</span>
                {selectedRequest.reviewer_name && <span>Traitee par {selectedRequest.reviewer_name}</span>}
              </div>

              {/* Actions */}
              {selectedRequest.status === "pending" && (
                <DialogFooter className="gap-2">
                  <Button
                    variant="outline"
                    onClick={() => {
                      setRejectDialogOpen(true)
                    }}
                    className="border-red-500 text-red-400 hover:bg-red-500/10"
                  >
                    <XCircle className="w-4 h-4 mr-2" />
                    Refuser
                  </Button>
                  <Button
                    onClick={() => handleApprove(selectedRequest)}
                    disabled={processing}
                    className="bg-green-600 hover:bg-green-700"
                  >
                    <CheckCircle className="w-4 h-4 mr-2" />
                    Approuver
                  </Button>
                </DialogFooter>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Reject Dialog */}
      <Dialog open={rejectDialogOpen} onOpenChange={setRejectDialogOpen}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Refuser la demande</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Indiquez la raison du refus. Cette information sera envoyee a l'artiste.
            </DialogDescription>
          </DialogHeader>

          <Textarea
            value={rejectionReason}
            onChange={(e) => setRejectionReason(e.target.value)}
            placeholder="Ex: Profil incomplet, pas assez de contenu publie..."
            className="bg-zinc-800 border-zinc-700 text-white min-h-[100px]"
          />

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setRejectDialogOpen(false)}
              className="border-zinc-700 text-zinc-300"
            >
              Annuler
            </Button>
            <Button
              onClick={handleReject}
              disabled={processing || !rejectionReason}
              className="bg-red-600 hover:bg-red-700"
            >
              Confirmer le refus
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
