"use client"

import { useState } from "react"
import useSWR from "swr"
import { Download, FileText, Calendar, Eye, Trash2, Loader2, Plus } from "lucide-react"
import { Button } from "@/components/ui/button"
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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { useToast } from "@/hooks/use-toast"

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

const reportTemplates = [
  {
    id: 1,
    name: "Rapport des streams",
    description: "Analyse detaillee des streams par periode",
    type: "streams",
  },
  {
    id: 2,
    name: "Rapport utilisateurs",
    description: "Statistiques sur les utilisateurs actifs et nouveaux",
    type: "users",
  },
  {
    id: 3,
    name: "Rapport revenus",
    description: "Analyse des revenus et abonnements",
    type: "revenue",
  },
  {
    id: 4,
    name: "Rapport contenu",
    description: "Statistiques sur les titres, albums et artistes",
    type: "content",
  },
]

export default function AdminReportsPage() {
  const { toast } = useToast()
  const [showGenerateReport, setShowGenerateReport] = useState(false)
  const [typeFilter, setTypeFilter] = useState("all")
  const [isSubmitting, setIsSubmitting] = useState(false)

  const [formData, setFormData] = useState({
    name: "",
    type: "streams",
    start_date: new Date().toISOString().split("T")[0],
    end_date: new Date().toISOString().split("T")[0],
    format: "pdf",
  })

  const {
    data: reports,
    isLoading,
    mutate,
  } = useSWR("/api/admin/reports", fetcher, {
    dedupingInterval: 30000,
  })

  const generatedReports = Array.isArray(reports) ? reports : []

  const filteredReports = generatedReports.filter((report: any) => {
    return typeFilter === "all" || report.type === typeFilter
  })

  const handleGenerateReport = async () => {
    if (!formData.name) {
      toast({ title: "Erreur", description: "Veuillez entrer un nom pour le rapport", variant: "destructive" })
      return
    }

    setIsSubmitting(true)
    try {
      const res = await fetch("/api/admin/reports", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      })

      if (res.ok) {
        toast({ title: "Rapport créé", description: "Le rapport est en cours de génération" })
        mutate()
        setShowGenerateReport(false)
        setFormData({
          name: "",
          type: "streams",
          start_date: new Date().toISOString().split("T")[0],
          end_date: new Date().toISOString().split("T")[0],
          format: "pdf",
        })
      } else {
        toast({ title: "Erreur", description: "Impossible de créer le rapport", variant: "destructive" })
      }
    } catch (error) {
      toast({ title: "Erreur", description: "Une erreur est survenue", variant: "destructive" })
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleDeleteReport = async (id: string) => {
    try {
      const res = await fetch(`/api/admin/reports/${id}`, { method: "DELETE" })
      if (res.ok) {
        toast({ title: "Rapport supprimé" })
        mutate()
      }
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de supprimer le rapport", variant: "destructive" })
    }
  }

  const openTemplateDialog = (template: (typeof reportTemplates)[0]) => {
    const today = new Date()
    const monthAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)

    setFormData({
      name: `${template.name} - ${today.toLocaleDateString("fr-FR")}`,
      type: template.type,
      start_date: monthAgo.toISOString().split("T")[0],
      end_date: today.toISOString().split("T")[0],
      format: "pdf",
    })
    setShowGenerateReport(true)
  }

  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>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Rapports</h1>
          <p className="text-zinc-400 text-sm">Generez et telechargez des rapports detailles</p>
        </div>
        <Button onClick={() => setShowGenerateReport(true)} className="bg-purple-600 hover:bg-purple-700">
          <Plus className="w-4 h-4 mr-2" />
          Generer un rapport
        </Button>
      </div>

      {/* Report Templates */}
      <div>
        <h2 className="text-lg font-semibold text-white mb-4">Modeles de rapports</h2>
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {reportTemplates.map((template) => (
            <Card
              key={template.id}
              className="bg-zinc-800/30 border-zinc-700/50 hover:bg-zinc-800/50 transition-colors cursor-pointer"
              onClick={() => openTemplateDialog(template)}
            >
              <CardHeader className="pb-2">
                <CardTitle className="text-white text-base">{template.name}</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-zinc-400">{template.description}</p>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>

      {/* Generated Reports */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-white">Rapports generes ({filteredReports.length})</h2>
          <Select value={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger className="w-40 bg-zinc-800/50 border-zinc-700 text-white">
              <SelectValue placeholder="Filtrer par type" />
            </SelectTrigger>
            <SelectContent className="bg-zinc-800 border-zinc-700">
              <SelectItem value="all">Tous les types</SelectItem>
              <SelectItem value="streams">Streams</SelectItem>
              <SelectItem value="users">Utilisateurs</SelectItem>
              <SelectItem value="revenue">Revenus</SelectItem>
              <SelectItem value="content">Contenu</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {filteredReports.length === 0 ? (
          <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-12 text-center">
            <FileText className="w-12 h-12 text-zinc-600 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-white mb-2">Aucun rapport</h3>
            <p className="text-zinc-400 mb-4">Générez votre premier rapport pour le voir ici</p>
            <Button onClick={() => setShowGenerateReport(true)} className="bg-purple-600 hover:bg-purple-700">
              <Plus className="w-4 h-4 mr-2" />
              Generer un rapport
            </Button>
          </div>
        ) : (
          <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-zinc-700/50">
                    <th className="p-4 text-left text-sm font-medium text-zinc-400">Nom</th>
                    <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden md:table-cell">Type</th>
                    <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden lg:table-cell">Date</th>
                    <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden lg:table-cell">Format</th>
                    <th className="p-4 text-left text-sm font-medium text-zinc-400">Statut</th>
                    <th className="p-4 text-right text-sm font-medium text-zinc-400">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredReports.map((report: any) => (
                    <tr key={report.id} className="border-b border-zinc-700/30 hover:bg-zinc-700/20 transition-colors">
                      <td className="p-4">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                            <FileText className="w-5 h-5 text-purple-400" />
                          </div>
                          <span className="font-medium text-white">{report.name}</span>
                        </div>
                      </td>
                      <td className="p-4 hidden md:table-cell">
                        <Badge variant="outline" className="border-zinc-600 text-zinc-300 capitalize">
                          {report.type}
                        </Badge>
                      </td>
                      <td className="p-4 text-zinc-400 hidden lg:table-cell">
                        <span className="flex items-center gap-1">
                          <Calendar className="w-4 h-4" />
                          {new Date(report.created_at).toLocaleDateString("fr-FR")}
                        </span>
                      </td>
                      <td className="p-4 text-zinc-400 hidden lg:table-cell uppercase">{report.format || "PDF"}</td>
                      <td className="p-4">
                        {report.status === "ready" ? (
                          <Badge className="bg-green-500/20 text-green-400 border-0">Pret</Badge>
                        ) : (
                          <Badge className="bg-yellow-500/20 text-yellow-400 border-0">En cours</Badge>
                        )}
                      </td>
                      <td className="p-4">
                        <div className="flex items-center justify-end gap-2">
                          <Button
                            variant="ghost"
                            size="icon"
                            className="text-zinc-400 hover:text-white"
                            disabled={report.status !== "ready"}
                          >
                            <Eye className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="text-zinc-400 hover:text-white"
                            disabled={report.status !== "ready"}
                          >
                            <Download className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="text-red-400 hover:text-red-300"
                            onClick={() => handleDeleteReport(report.id)}
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>

      {/* Generate Report Dialog */}
      <Dialog open={showGenerateReport} onOpenChange={setShowGenerateReport}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Generer un rapport</DialogTitle>
            <DialogDescription className="text-zinc-400">Configurez les parametres du rapport</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Nom du rapport</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                placeholder="Rapport mensuel..."
                value={formData.name}
                onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Type de rapport</Label>
              <Select value={formData.type} onValueChange={(v) => setFormData((prev) => ({ ...prev, type: v }))}>
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="streams">Rapport des streams</SelectItem>
                  <SelectItem value="users">Rapport utilisateurs</SelectItem>
                  <SelectItem value="revenue">Rapport revenus</SelectItem>
                  <SelectItem value="content">Rapport contenu</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Date de debut</Label>
                <Input
                  type="date"
                  className="bg-zinc-800 border-zinc-700"
                  value={formData.start_date}
                  onChange={(e) => setFormData((prev) => ({ ...prev, start_date: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label>Date de fin</Label>
                <Input
                  type="date"
                  className="bg-zinc-800 border-zinc-700"
                  value={formData.end_date}
                  onChange={(e) => setFormData((prev) => ({ ...prev, end_date: e.target.value }))}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Format</Label>
              <Select value={formData.format} onValueChange={(v) => setFormData((prev) => ({ ...prev, format: v }))}>
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="pdf">PDF</SelectItem>
                  <SelectItem value="csv">CSV</SelectItem>
                  <SelectItem value="xlsx">Excel</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowGenerateReport(false)}>
              Annuler
            </Button>
            <Button
              className="bg-purple-600 hover:bg-purple-700"
              onClick={handleGenerateReport}
              disabled={isSubmitting || !formData.name}
            >
              {isSubmitting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
              Generer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
