"use client"

import { useState } from "react"
import { ArrowLeft, Check, Crown, Music, Zap, Download, Users, Headphones, Loader2 } from "lucide-react"
import Link from "next/link"
import { useRouter } from "next/navigation"
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 { useAuth } from "@/components/auth-provider"
import { useToast } from "@/hooks/use-toast"

const plans = [
  {
    id: "free",
    name: "Gratuit",
    price: "0 FCFA",
    period: "pour toujours",
    features: [
      "Ecoute avec publicites",
      "Qualite audio standard",
      "Mode aleatoire uniquement",
      "Acces limite au catalogue",
    ],
    limitations: ["Pas de telechargement", "Pas d'ecoute hors ligne", "6 skips par heure"],
    color: "zinc",
    popular: false,
  },
  {
    id: "premium",
    name: "Premium",
    price: "6,554 FCFA",
    period: "par mois",
    features: [
      "Ecoute sans publicites",
      "Qualite audio haute definition",
      "Ecoute a la demande",
      "Telechargements illimites",
      "Ecoute hors ligne",
      "Skips illimites",
      "Acces complet au catalogue",
    ],
    limitations: [],
    color: "purple",
    popular: true,
  },
  {
    id: "family",
    name: "Famille",
    price: "9,833 FCFA",
    period: "par mois",
    features: [
      "Tout Premium inclus",
      "Jusqu'a 6 comptes",
      "Controle parental",
      "Mix famille partage",
      "Gestion des membres",
    ],
    limitations: [],
    color: "pink",
    popular: false,
  },
]

export default function SubscriptionPage() {
  const router = useRouter()
  const { user, updateProfile } = useAuth()
  const { toast } = useToast()
  const [showUpgradeDialog, setShowUpgradeDialog] = useState(false)
  const [selectedPlan, setSelectedPlan] = useState<(typeof plans)[0] | null>(null)
  const [isUpgrading, setIsUpgrading] = useState(false)

  const currentPlan = user?.subscription?.plan || "free"

  const handleUpgrade = (plan: (typeof plans)[0]) => {
    setSelectedPlan(plan)
    setShowUpgradeDialog(true)
  }

  const confirmUpgrade = async () => {
    if (!user || !selectedPlan) return

    setIsUpgrading(true)

    try {
      const response = await fetch("/api/subscription/upgrade", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          userId: user.id,
          planId: selectedPlan.id,
          billingCycle: "monthly",
        }),
      })

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error || "Erreur lors de la mise à niveau")
      }

      const data = await response.json()

      // Update user profile in local state
      updateProfile({
        subscription: {
          ...user.subscription,
          plan: selectedPlan.id as any,
        },
        isPremium: selectedPlan.id !== "free",
      })

      toast({
        title: "Abonnement activé",
        description: `Vous êtes maintenant abonné au plan ${selectedPlan.name}`,
      })

      setShowUpgradeDialog(false)
      setTimeout(() => router.push("/home"), 1000)
    } catch (error: any) {
      toast({
        title: "Erreur",
        description: error.message || "Une erreur est survenue",
        variant: "destructive",
      })
    } finally {
      setIsUpgrading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-zinc-900 to-black text-white pb-24">
      <div className="max-w-5xl mx-auto px-4 py-8">
        <div className="flex items-center gap-4 mb-8">
          <Link href="/profile">
            <Button variant="ghost" size="icon" className="text-zinc-400 hover:text-white">
              <ArrowLeft className="w-5 h-5" />
            </Button>
          </Link>
          <div>
            <h1 className="text-2xl font-bold">Abonnement</h1>
            <p className="text-zinc-400">Choisissez le forfait qui vous convient</p>
          </div>
        </div>

        {/* Current Plan Banner */}
        <Card className="bg-gradient-to-r from-purple-900/50 to-pink-900/50 border-purple-500/30 mb-8">
          <CardContent className="p-6 flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-purple-500/20 rounded-full flex items-center justify-center">
                <Music className="w-6 h-6 text-purple-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Votre forfait actuel</p>
                <p className="text-white font-semibold text-lg capitalize">{currentPlan}</p>
              </div>
            </div>
            <Badge className="bg-zinc-500/20 text-zinc-300 border-0">Actif</Badge>
          </CardContent>
        </Card>

        {/* Plans Grid */}
        <div className="grid md:grid-cols-3 gap-6">
          {plans.map((plan) => (
            <Card
              key={plan.id}
              className={`relative bg-zinc-800/30 border-zinc-700/50 ${
                plan.popular ? "ring-2 ring-purple-500" : ""
              } ${currentPlan === plan.id ? "border-green-500/50" : ""}`}
            >
              {plan.popular && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                  <Badge className="bg-purple-600 text-white border-0">
                    <Zap className="w-3 h-3 mr-1" />
                    Populaire
                  </Badge>
                </div>
              )}
              <CardHeader className="text-center pb-2">
                <div
                  className={`w-16 h-16 mx-auto mb-4 rounded-full flex items-center justify-center ${
                    plan.id === "premium"
                      ? "bg-purple-500/20"
                      : plan.id === "family"
                        ? "bg-pink-500/20"
                        : "bg-zinc-500/20"
                  }`}
                >
                  {plan.id === "premium" ? (
                    <Crown className="w-8 h-8 text-purple-400" />
                  ) : plan.id === "family" ? (
                    <Users className="w-8 h-8 text-pink-400" />
                  ) : (
                    <Headphones className="w-8 h-8 text-zinc-400" />
                  )}
                </div>
                <CardTitle className="text-white text-xl">{plan.name}</CardTitle>
                <div className="mt-2">
                  <span className="text-3xl font-bold text-white">{plan.price}</span>
                  <span className="text-zinc-400 text-sm ml-1">{plan.period}</span>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                <ul className="space-y-2">
                  {plan.features.map((feature, index) => (
                    <li key={index} className="flex items-center gap-2 text-sm">
                      <Check className="w-4 h-4 text-green-400 flex-shrink-0" />
                      <span className="text-zinc-300">{feature}</span>
                    </li>
                  ))}
                </ul>
                {plan.limitations.length > 0 && (
                  <ul className="space-y-2 pt-2 border-t border-zinc-700/50">
                    {plan.limitations.map((limitation, index) => (
                      <li key={index} className="flex items-center gap-2 text-sm text-zinc-500">
                        <span className="w-4 h-4 flex items-center justify-center">-</span>
                        {limitation}
                      </li>
                    ))}
                  </ul>
                )}
                <Button
                  onClick={() => handleUpgrade(plan)}
                  disabled={currentPlan === plan.id}
                  className={`w-full mt-4 ${
                    plan.id === "premium"
                      ? "bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700"
                      : plan.id === "family"
                        ? "bg-pink-600 hover:bg-pink-700"
                        : "bg-zinc-700 hover:bg-zinc-600"
                  }`}
                >
                  {currentPlan === plan.id ? "Forfait actuel" : "Choisir ce forfait"}
                </Button>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* Features Comparison */}
        <Card className="bg-zinc-800/30 border-zinc-700/50 mt-8">
          <CardHeader>
            <CardTitle className="text-white">Avantages Premium</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="flex items-center gap-3 p-4 bg-zinc-900/50 rounded-lg">
                <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                  <Music className="w-5 h-5 text-purple-400" />
                </div>
                <div>
                  <p className="text-white font-medium">Sans pub</p>
                  <p className="text-zinc-400 text-sm">Musique ininterrompue</p>
                </div>
              </div>
              <div className="flex items-center gap-3 p-4 bg-zinc-900/50 rounded-lg">
                <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                  <Download className="w-5 h-5 text-purple-400" />
                </div>
                <div>
                  <p className="text-white font-medium">Hors ligne</p>
                  <p className="text-zinc-400 text-sm">Telechargez vos titres</p>
                </div>
              </div>
              <div className="flex items-center gap-3 p-4 bg-zinc-900/50 rounded-lg">
                <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                  <Headphones className="w-5 h-5 text-purple-400" />
                </div>
                <div>
                  <p className="text-white font-medium">HD Audio</p>
                  <p className="text-zinc-400 text-sm">Qualite superieure</p>
                </div>
              </div>
              <div className="flex items-center gap-3 p-4 bg-zinc-900/50 rounded-lg">
                <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                  <Zap className="w-5 h-5 text-purple-400" />
                </div>
                <div>
                  <p className="text-white font-medium">Skips illimites</p>
                  <p className="text-zinc-400 text-sm">Passez les titres</p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Upgrade Dialog */}
      <Dialog open={showUpgradeDialog} onOpenChange={setShowUpgradeDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Passer a {selectedPlan?.name}</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Vous allez etre facture {selectedPlan?.price} {selectedPlan?.period}.
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <div className="bg-zinc-800/50 rounded-lg p-4 space-y-2">
              <div className="flex justify-between">
                <span className="text-zinc-400">Forfait</span>
                <span className="text-white">{selectedPlan?.name}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-zinc-400">Prix</span>
                <span className="text-white">{selectedPlan?.price}/mois</span>
              </div>
              <div className="flex justify-between pt-2 border-t border-zinc-700">
                <span className="text-zinc-400">Total aujourd'hui</span>
                <span className="text-white font-semibold">{selectedPlan?.price}</span>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowUpgradeDialog(false)} disabled={isUpgrading}>
              Annuler
            </Button>
            <Button onClick={confirmUpgrade} className="bg-purple-600 hover:bg-purple-700" disabled={isUpgrading}>
              {isUpgrading ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Traitement...
                </>
              ) : (
                "Confirmer l'achat"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
