"use client"

import { useState } from "react"
import {
  Plus,
  Megaphone,
  TrendingUp,
  Calendar,
  DollarSign,
  Eye,
  MoreHorizontal,
  Edit,
  Trash2,
  Loader2,
  Pause,
  Play,
} from "lucide-react"
import { Button } from "@/components/ui/button"
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 {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useAuth } from "@/components/auth-provider"
import { useToast } from "@/hooks/use-toast"
import useSWR, { mutate } from "swr"

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

export default function ArtistPromotionsPage() {
  const { user } = useAuth()
  const { toast } = useToast()
  const artistId = user?.artistId
  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [newCampaign, setNewCampaign] = useState({
    title: "",
    trackId: "",
    budget: "",
    startDate: "",
    endDate: "",
    objective: "streams",
  })

  const { data, isLoading } = useSWR(artistId ? `/api/artist/campaigns?artistId=${artistId}` : null, fetcher)

  const { data: tracksData } = useSWR(artistId ? `/api/tracks?artistId=${artistId}` : null, fetcher)

  const campaigns = data?.campaigns || []
  const tracks = tracksData?.data || tracksData?.tracks || []

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

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("fr-FR").format(amount) + " FCFA"
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "active":
        return <Badge className="bg-green-500/20 text-green-400 border-0">Active</Badge>
      case "scheduled":
        return <Badge className="bg-blue-500/20 text-blue-400 border-0">Planifiee</Badge>
      case "paused":
        return <Badge className="bg-yellow-500/20 text-yellow-400 border-0">En pause</Badge>
      case "completed":
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Terminee</Badge>
      default:
        return <Badge>{status}</Badge>
    }
  }

  const handleCreateCampaign = async () => {
    try {
      const response = await fetch("/api/artist/campaigns", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          artistId,
          title: newCampaign.title,
          trackId: newCampaign.trackId || null,
          budget: Number.parseInt(newCampaign.budget) || 0,
          startDate: newCampaign.startDate,
          endDate: newCampaign.endDate,
          objective: newCampaign.objective,
        }),
      })

      if (response.ok) {
        toast({ title: "Campagne creee avec succes" })
        setShowCreateDialog(false)
        setNewCampaign({ title: "", trackId: "", budget: "", startDate: "", endDate: "", objective: "streams" })
        mutate(`/api/artist/campaigns?artistId=${artistId}`)
      }
    } catch (error) {
      toast({ title: "Erreur lors de la creation", variant: "destructive" })
    }
  }

  const handleToggleStatus = async (id: string, currentStatus: string) => {
    const newStatus = currentStatus === "active" ? "paused" : "active"
    try {
      const response = await fetch("/api/artist/campaigns", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, status: newStatus }),
      })

      if (response.ok) {
        toast({ title: newStatus === "active" ? "Campagne activee" : "Campagne mise en pause" })
        mutate(`/api/artist/campaigns?artistId=${artistId}`)
      }
    } catch (error) {
      toast({ title: "Erreur", variant: "destructive" })
    }
  }

  const handleDeleteCampaign = async (id: string) => {
    try {
      const response = await fetch(`/api/artist/campaigns?id=${id}`, { method: "DELETE" })
      if (response.ok) {
        toast({ title: "Campagne supprimee" })
        mutate(`/api/artist/campaigns?artistId=${artistId}`)
      }
    } catch (error) {
      toast({ title: "Erreur lors de la suppression", variant: "destructive" })
    }
  }

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

  const activeCampaigns = campaigns.filter((c: any) => c.status === "active")
  const totalSpent = campaigns.reduce((acc: number, c: any) => acc + (c.spent || 0), 0)
  const totalImpressions = campaigns.reduce((acc: number, c: any) => acc + (c.impressions || 0), 0)
  const totalClicks = campaigns.reduce((acc: number, c: any) => acc + (c.clicks || 0), 0)
  const avgCtr = totalImpressions > 0 ? ((totalClicks / totalImpressions) * 100).toFixed(2) : "0"

  return (
    <div className="space-y-6">
      <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">Promotions</h1>
          <p className="text-zinc-400">Gerez vos campagnes publicitaires</p>
        </div>
        <Button onClick={() => setShowCreateDialog(true)} className="bg-purple-600 hover:bg-purple-700">
          <Plus className="w-4 h-4 mr-2" />
          Nouvelle campagne
        </Button>
      </div>

      {/* Stats */}
      <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">Campagnes actives</p>
                <p className="text-2xl font-bold text-white">{activeCampaigns.length}</p>
              </div>
              <div className="w-10 h-10 bg-green-500/20 rounded-lg flex items-center justify-center">
                <Megaphone className="w-5 h-5 text-green-400" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">Budget depense</p>
                <p className="text-2xl font-bold text-white">{formatCurrency(totalSpent)}</p>
              </div>
              <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                <DollarSign className="w-5 h-5 text-purple-400" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">Impressions</p>
                <p className="text-2xl font-bold text-white">{formatNumber(totalImpressions)}</p>
              </div>
              <div className="w-10 h-10 bg-blue-500/20 rounded-lg flex items-center justify-center">
                <Eye className="w-5 h-5 text-blue-400" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">Taux de clic moyen</p>
                <p className="text-2xl font-bold text-white">{avgCtr}%</p>
              </div>
              <div className="w-10 h-10 bg-pink-500/20 rounded-lg flex items-center justify-center">
                <TrendingUp className="w-5 h-5 text-pink-400" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Campaigns List */}
      <Card className="bg-zinc-800/30 border-zinc-700/50">
        <CardHeader>
          <CardTitle className="text-white">Vos campagnes</CardTitle>
        </CardHeader>
        <CardContent>
          {campaigns.length === 0 ? (
            <div className="text-center py-8">
              <Megaphone className="w-12 h-12 text-zinc-600 mx-auto mb-4" />
              <p className="text-zinc-400">Aucune campagne pour le moment</p>
              <Button onClick={() => setShowCreateDialog(true)} className="mt-4 bg-purple-600 hover:bg-purple-700">
                Creer votre premiere campagne
              </Button>
            </div>
          ) : (
            <div className="space-y-4">
              {campaigns.map((campaign: any) => (
                <div key={campaign.id} className="flex items-center gap-4 p-4 bg-zinc-900/50 rounded-lg">
                  <div className="w-12 h-12 bg-purple-500/20 rounded-lg flex items-center justify-center">
                    <Megaphone className="w-6 h-6 text-purple-400" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <h3 className="text-white font-medium">{campaign.title}</h3>
                      {getStatusBadge(campaign.status)}
                    </div>
                    {campaign.track_title && <p className="text-zinc-400 text-sm">Titre: {campaign.track_title}</p>}
                    <div className="flex items-center gap-4 mt-2 text-sm text-zinc-500">
                      <span className="flex items-center gap-1">
                        <Calendar className="w-3 h-3" />
                        {new Date(campaign.start_date).toLocaleDateString("fr-FR")} -{" "}
                        {new Date(campaign.end_date).toLocaleDateString("fr-FR")}
                      </span>
                      <span className="flex items-center gap-1">
                        <DollarSign className="w-3 h-3" />
                        {formatCurrency(campaign.spent || 0)} / {formatCurrency(campaign.budget)}
                      </span>
                    </div>
                  </div>
                  <div className="text-right hidden sm:block">
                    <p className="text-white font-medium">{formatNumber(campaign.impressions || 0)}</p>
                    <p className="text-zinc-400 text-sm">impressions</p>
                  </div>
                  <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 className="text-zinc-300">
                        <Eye className="w-4 h-4 mr-2" /> Voir les details
                      </DropdownMenuItem>
                      {(campaign.status === "active" || campaign.status === "paused") && (
                        <DropdownMenuItem
                          className="text-zinc-300"
                          onClick={() => handleToggleStatus(campaign.id, campaign.status)}
                        >
                          {campaign.status === "active" ? (
                            <>
                              <Pause className="w-4 h-4 mr-2" /> Mettre en pause
                            </>
                          ) : (
                            <>
                              <Play className="w-4 h-4 mr-2" /> Activer
                            </>
                          )}
                        </DropdownMenuItem>
                      )}
                      <DropdownMenuItem className="text-zinc-300">
                        <Edit className="w-4 h-4 mr-2" /> Modifier
                      </DropdownMenuItem>
                      <DropdownMenuSeparator className="bg-zinc-700" />
                      <DropdownMenuItem onClick={() => handleDeleteCampaign(campaign.id)} className="text-red-400">
                        <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Create Campaign Dialog */}
      <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Nouvelle campagne</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Creez une campagne promotionnelle pour votre musique
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Nom de la campagne</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                placeholder="Ex: Promo Nouveau Single"
                value={newCampaign.title}
                onChange={(e) => setNewCampaign({ ...newCampaign, title: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label>Titre a promouvoir (optionnel)</Label>
              <Select
                value={newCampaign.trackId}
                onValueChange={(value) => setNewCampaign({ ...newCampaign, trackId: value })}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue placeholder="Selectionner un titre" />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  {tracks.map((track: any) => (
                    <SelectItem key={track.id} value={track.id}>
                      {track.title}
                    </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={newCampaign.startDate}
                  onChange={(e) => setNewCampaign({ ...newCampaign, startDate: 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={newCampaign.endDate}
                  onChange={(e) => setNewCampaign({ ...newCampaign, endDate: e.target.value })}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Budget (FCFA)</Label>
              <Input
                type="number"
                className="bg-zinc-800 border-zinc-700"
                placeholder="500000"
                value={newCampaign.budget}
                onChange={(e) => setNewCampaign({ ...newCampaign, budget: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label>Objectif</Label>
              <Select
                value={newCampaign.objective}
                onValueChange={(value) => setNewCampaign({ ...newCampaign, objective: value })}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue placeholder="Choisir un objectif" />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="streams">Augmenter les streams</SelectItem>
                  <SelectItem value="followers">Gagner des followers</SelectItem>
                  <SelectItem value="awareness">Notoriete</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowCreateDialog(false)}>
              Annuler
            </Button>
            <Button
              className="bg-purple-600 hover:bg-purple-700"
              onClick={handleCreateCampaign}
              disabled={!newCampaign.title || !newCampaign.startDate || !newCampaign.endDate}
            >
              Creer la campagne
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
