"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Eye, EyeOff, Music2, Loader2, User, Mic2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useAuth, type UserRole } from "@/components/auth-provider"

export default function SignupPage() {
  const router = useRouter()
  const { signup, isLoading, isAuthenticated } = useAuth()
  const [name, setName] = useState("")
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const [accountType, setAccountType] = useState<UserRole>("user")
  const [artistName, setArtistName] = useState("")
  const [error, setError] = useState("")
  const [acceptTerms, setAcceptTerms] = useState(false)

  useEffect(() => {
    if (isAuthenticated) {
      router.push("/home")
    }
  }, [isAuthenticated, router])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError("")

    if (!name || !email || !password || !confirmPassword) {
      setError("Veuillez remplir tous les champs")
      return
    }

    if (password !== confirmPassword) {
      setError("Les mots de passe ne correspondent pas")
      return
    }

    if (password.length < 8) {
      setError("Le mot de passe doit contenir au moins 8 caracteres")
      return
    }

    if (!acceptTerms) {
      setError("Veuillez accepter les conditions d'utilisation")
      return
    }

    if (accountType === "artist" && !artistName) {
      setError("Veuillez entrer votre nom d'artiste")
      return
    }

    const result = await signup({
      email,
      password,
      name,
      role: accountType,
      artistName: accountType === "artist" ? artistName : undefined,
    })

    if (result.success) {
      if (accountType === "artist") {
        router.push("/artist")
      } else {
        router.push("/home")
      }
    } else {
      setError(result.error || "Une erreur est survenue")
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-zinc-950 via-zinc-900 to-purple-950 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo */}
        <div className="text-center mb-8">
          <Link href="/" className="inline-flex items-center gap-2 text-white">
            <div className="w-12 h-12 bg-gradient-to-br from-purple-500 to-pink-500 rounded-xl flex items-center justify-center">
              <Music2 className="w-7 h-7 text-white" />
            </div>
            <span className="text-2xl font-bold">AfricanMusic</span>
          </Link>
        </div>

        {/* Card */}
        <div className="bg-zinc-900/80 backdrop-blur-xl border border-zinc-800 rounded-2xl p-8">
          <div className="text-center mb-6">
            <h1 className="text-2xl font-bold text-white mb-2">Creer un compte</h1>
            <p className="text-zinc-400">Rejoignez des millions d'auditeurs</p>
          </div>

          {/* Account Type Selection */}
          <div className="grid grid-cols-2 gap-3 mb-6">
            <button
              type="button"
              onClick={() => setAccountType("user")}
              className={`p-4 rounded-xl border-2 transition-all ${
                accountType === "user"
                  ? "border-purple-500 bg-purple-500/10"
                  : "border-zinc-700 bg-zinc-800/50 hover:border-zinc-600"
              }`}
            >
              <User
                className={`w-6 h-6 mx-auto mb-2 ${accountType === "user" ? "text-purple-400" : "text-zinc-400"}`}
              />
              <p className={`text-sm font-medium ${accountType === "user" ? "text-white" : "text-zinc-400"}`}>
                Auditeur
              </p>
              <p className="text-xs text-zinc-500 mt-1">Ecoutez de la musique</p>
            </button>
            <button
              type="button"
              onClick={() => setAccountType("artist")}
              className={`p-4 rounded-xl border-2 transition-all ${
                accountType === "artist"
                  ? "border-purple-500 bg-purple-500/10"
                  : "border-zinc-700 bg-zinc-800/50 hover:border-zinc-600"
              }`}
            >
              <Mic2
                className={`w-6 h-6 mx-auto mb-2 ${accountType === "artist" ? "text-purple-400" : "text-zinc-400"}`}
              />
              <p className={`text-sm font-medium ${accountType === "artist" ? "text-white" : "text-zinc-400"}`}>
                Artiste
              </p>
              <p className="text-xs text-zinc-500 mt-1">Partagez votre musique</p>
            </button>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            {error && (
              <div className="bg-red-500/10 border border-red-500/20 text-red-400 text-sm rounded-lg p-3">{error}</div>
            )}

            <div className="space-y-2">
              <Label htmlFor="name" className="text-zinc-300">
                Nom complet
              </Label>
              <Input
                id="name"
                type="text"
                placeholder="Votre nom"
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="bg-zinc-800/50 border-zinc-700 text-white placeholder:text-zinc-500 h-12"
              />
            </div>

            {accountType === "artist" && (
              <div className="space-y-2">
                <Label htmlFor="artistName" className="text-zinc-300">
                  Nom d'artiste
                </Label>
                <Input
                  id="artistName"
                  type="text"
                  placeholder="Votre nom de scene"
                  value={artistName}
                  onChange={(e) => setArtistName(e.target.value)}
                  className="bg-zinc-800/50 border-zinc-700 text-white placeholder:text-zinc-500 h-12"
                />
              </div>
            )}

            <div className="space-y-2">
              <Label htmlFor="email" className="text-zinc-300">
                Email
              </Label>
              <Input
                id="email"
                type="email"
                placeholder="votre@email.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="bg-zinc-800/50 border-zinc-700 text-white placeholder:text-zinc-500 h-12"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="password" className="text-zinc-300">
                Mot de passe
              </Label>
              <div className="relative">
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  placeholder="Minimum 8 caracteres"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="bg-zinc-800/50 border-zinc-700 text-white placeholder:text-zinc-500 h-12 pr-12"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-white"
                >
                  {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                </button>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirmPassword" className="text-zinc-300">
                Confirmer le mot de passe
              </Label>
              <Input
                id="confirmPassword"
                type="password"
                placeholder="Confirmez votre mot de passe"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                className="bg-zinc-800/50 border-zinc-700 text-white placeholder:text-zinc-500 h-12"
              />
            </div>

            <label className="flex items-start gap-2 text-zinc-400 text-sm">
              <input
                type="checkbox"
                checked={acceptTerms}
                onChange={(e) => setAcceptTerms(e.target.checked)}
                className="rounded bg-zinc-700 border-zinc-600 mt-0.5"
              />
              <span>
                J'accepte les{" "}
                <Link href="/terms" className="text-purple-400 hover:text-purple-300">
                  conditions d'utilisation
                </Link>{" "}
                et la{" "}
                <Link href="/privacy" className="text-purple-400 hover:text-purple-300">
                  politique de confidentialite
                </Link>
              </span>
            </label>

            <Button
              type="submit"
              disabled={isLoading}
              className="w-full h-12 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white font-medium"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                  Creation...
                </>
              ) : (
                "Creer mon compte"
              )}
            </Button>
          </form>

          <p className="mt-6 text-center text-zinc-400 text-sm">
            Deja un compte?{" "}
            <Link href="/" className="text-purple-400 hover:text-purple-300 font-medium">
              Se connecter
            </Link>
          </p>
        </div>
      </div>
    </div>
  )
}
