"use client"

import { useState, useRef, useEffect } from "react"
import { User, Bell, Shield, CheckCircle, Upload, Camera, Loader2, ImageIcon, Clock, XCircle } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import { useAuth } from "@/components/auth-provider"
import { useToast } from "@/hooks/use-toast"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog"
import useSWR from "swr"

const fetcher = async (url: string) => {
  const res = await fetch(url)
  const json = await res.json()
  // Handle both { data: artist } and direct artist responses
  return json.data || json
}

export default function ArtistSettingsPage() {
  const { user, updateProfile } = useAuth()
  const { toast } = useToast()
  const artistId = user?.artistId
  const avatarInputRef = useRef<HTMLInputElement>(null)
  const coverInputRef = useRef<HTMLInputElement>(null)

  const { data: artistData, mutate } = useSWR(artistId ? `/api/artists/${artistId}` : null, fetcher, {
    revalidateOnFocus: true,
    revalidateOnMount: true,
  })

  const { data: verificationData, mutate: mutateVerification } = useSWR(
    artistId ? `/api/artist/verification?artist_id=${artistId}` : null,
    fetcher,
  )

  const [saving, setSaving] = useState(false)
  const [uploadingAvatar, setUploadingAvatar] = useState(false)
  const [uploadingCover, setUploadingCover] = useState(false)

  const [verificationDialogOpen, setVerificationDialogOpen] = useState(false)
  const [submittingVerification, setSubmittingVerification] = useState(false)
  const [verificationForm, setVerificationForm] = useState({
    reason: "",
    instagram: "",
    twitter: "",
    website: "",
    pressLinks: "",
  })

  const [profile, setProfile] = useState({
    name: "",
    bio: "",
    country: "",
    genres: "",
    website: "",
    instagram: "",
    twitter: "",
    youtube: "",
    avatar_url: "",
    cover_url: "",
  })

  const [notifications, setNotifications] = useState({
    newFollower: true,
    playlistAdd: true,
    streamMilestone: true,
    weeklyReport: true,
    marketing: false,
  })

  // Load artist data into form
  useEffect(() => {
    if (artistData) {
      const socialLinks = artistData.social_links || {}
      setProfile({
        name: artistData.name || "",
        bio: artistData.bio || "",
        country: artistData.country || "",
        genres: Array.isArray(artistData.genres) ? artistData.genres.join(", ") : artistData.genres || "",
        website: socialLinks.website || "",
        instagram: socialLinks.instagram || "",
        twitter: socialLinks.twitter || "",
        youtube: socialLinks.youtube || "",
        avatar_url: artistData.avatar_url || "",
        cover_url: artistData.cover_url || "",
      })
    }
  }, [artistData])

  const handleImageUpload = async (file: File, type: "avatar" | "cover") => {
    if (!file || !artistId) return

    const setUploading = type === "avatar" ? setUploadingAvatar : setUploadingCover
    setUploading(true)

    try {
      const formData = new FormData()
      formData.append("file", file)
      formData.append("type", type)

      const response = await fetch("/api/upload", {
        method: "POST",
        body: formData,
      })

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error || "Upload failed")
      }

      const { url } = await response.json()

      // Update artist profile with new image URL
      const updateField = type === "avatar" ? "avatar_url" : "cover_url"
      const updateResponse = await fetch(`/api/artists/${artistId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ [updateField]: url }),
      })

      if (!updateResponse.ok) {
        throw new Error("Failed to update profile")
      }

      setProfile((prev) => ({ ...prev, [updateField]: url }))

      await mutate()

      if (type === "avatar") {
        // Update the auth context so sidebar and header update immediately
        updateProfile({ avatar: url })
      }

      toast({
        title: "Image mise a jour",
        description:
          type === "avatar" ? "Votre photo de profil a ete mise a jour" : "Votre couverture a ete mise a jour",
      })
    } catch (error) {
      toast({
        title: "Erreur",
        description: error instanceof Error ? error.message : "Erreur lors du telechargement",
        variant: "destructive",
      })
    } finally {
      setUploading(false)
    }
  }

  const handleSave = async () => {
    if (!artistId) {
      toast({
        title: "Erreur",
        description: "ID artiste non trouve. Veuillez rafraichir la page.",
        variant: "destructive",
      })
      return
    }

    setSaving(true)

    try {
      const updateData = {
        name: profile.name,
        bio: profile.bio,
        country: profile.country,
        genres: profile.genres
          .split(",")
          .map((g) => g.trim())
          .filter(Boolean),
        social_links: {
          website: profile.website,
          instagram: profile.instagram,
          twitter: profile.twitter,
          youtube: profile.youtube,
        },
      }

      const response = await fetch(`/api/artists/${artistId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updateData),
      })

      const responseData = await response.json()

      if (!response.ok) {
        throw new Error(responseData.error || "Failed to save")
      }

      // Handle both { data: artist } and direct artist responses
      const updatedArtist = responseData.data || responseData

      // Update SWR cache
      await mutate(updatedArtist, { revalidate: false })

      // Update auth context
      updateProfile({
        name: profile.name,
        artistProfile: {
          stageName: profile.name,
          verified: updatedArtist.is_verified || false,
          monthlyListeners: user?.artistProfile?.monthlyListeners || 0,
          totalStreams: user?.artistProfile?.totalStreams || 0,
        },
      })

      toast({
        title: "Profil enregistre",
        description: "Vos modifications ont ete enregistrees avec succes",
      })
    } catch (error) {
      toast({
        title: "Erreur",
        description: error instanceof Error ? error.message : "Erreur lors de l'enregistrement",
        variant: "destructive",
      })
    } finally {
      setSaving(false)
    }
  }

  const handleSubmitVerification = async () => {
    if (!artistId) return
    setSubmittingVerification(true)

    try {
      const response = await fetch("/api/artist/verification", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          artist_id: artistId,
          reason: verificationForm.reason,
          social_proof: {
            instagram: verificationForm.instagram || profile.instagram,
            twitter: verificationForm.twitter || profile.twitter,
            website: verificationForm.website || profile.website,
            press_links: verificationForm.pressLinks.split("\n").filter(Boolean),
          },
        }),
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || "Failed to submit request")
      }

      toast({
        title: "Demande envoyee",
        description: "Votre demande de verification a ete soumise. Nous vous repondrons sous 48-72h.",
      })

      setVerificationDialogOpen(false)
      mutateVerification()
    } catch (error) {
      toast({
        title: "Erreur",
        description: error instanceof Error ? error.message : "Erreur lors de l'envoi de la demande",
        variant: "destructive",
      })
    } finally {
      setSubmittingVerification(false)
    }
  }

  const renderVerificationStatus = () => {
    const isVerified = artistData?.is_verified || verificationData?.is_verified
    const pendingRequest = verificationData?.request?.status === "pending"
    const rejectedRequest = verificationData?.request?.status === "rejected"

    if (isVerified) {
      return (
        <div className="flex items-center gap-3 p-4 bg-green-500/10 rounded-lg border border-green-500/20">
          <CheckCircle className="w-6 h-6 text-green-400" />
          <div>
            <p className="text-white font-medium">Artiste verifie</p>
            <p className="text-zinc-400 text-sm">Votre profil est verifie et affiche le badge officiel</p>
          </div>
        </div>
      )
    }

    if (pendingRequest) {
      return (
        <div className="flex items-center gap-3 p-4 bg-yellow-500/10 rounded-lg border border-yellow-500/20">
          <Clock className="w-6 h-6 text-yellow-400" />
          <div>
            <p className="text-white font-medium">Demande en cours</p>
            <p className="text-zinc-400 text-sm">
              Votre demande est en cours d'examen. Nous vous repondrons sous 48-72h.
            </p>
          </div>
        </div>
      )
    }

    if (rejectedRequest) {
      return (
        <div className="space-y-4">
          <div className="flex items-center gap-3 p-4 bg-red-500/10 rounded-lg border border-red-500/20">
            <XCircle className="w-6 h-6 text-red-400" />
            <div>
              <p className="text-white font-medium">Demande refusee</p>
              <p className="text-zinc-400 text-sm">
                {verificationData?.request?.rejection_reason ||
                  "Votre demande n'a pas ete approuvee. Vous pouvez soumettre une nouvelle demande."}
              </p>
            </div>
          </div>
          <Button
            className="bg-purple-600 hover:bg-purple-700 w-full sm:w-auto"
            onClick={() => setVerificationDialogOpen(true)}
          >
            <Shield className="w-4 h-4 mr-2" />
            Soumettre une nouvelle demande
          </Button>
        </div>
      )
    }

    return (
      <div className="space-y-4">
        <div className="flex items-start gap-3 p-4 bg-purple-500/10 rounded-lg border border-purple-500/20">
          <Shield className="w-6 h-6 text-purple-400 flex-shrink-0 mt-0.5" />
          <div className="flex-1">
            <p className="text-white font-medium mb-2">Obtenez le badge verifie</p>
            <p className="text-zinc-400 text-sm">
              La verification vous donne un badge officiel et une meilleure visibilite sur la plateforme. Les artistes
              verifies apparaissent en priorite dans les recherches et recommandations.
            </p>
          </div>
        </div>
        <Button
          className="bg-purple-600 hover:bg-purple-700 w-full sm:w-auto"
          onClick={() => setVerificationDialogOpen(true)}
        >
          <Shield className="w-4 h-4 mr-2" />
          Demander la verification
        </Button>
      </div>
    )
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">Parametres</h1>
        <p className="text-zinc-400">Gerez votre profil artiste</p>
      </div>

      {/* Cover Image */}
      <Card className="bg-zinc-800/50 border-zinc-700 overflow-hidden">
        <div className="relative h-48 bg-zinc-900">
          {profile.cover_url ? (
            <img src={profile.cover_url || "/placeholder.svg"} alt="Cover" className="w-full h-full object-cover" />
          ) : (
            <div className="w-full h-full flex items-center justify-center bg-gradient-to-r from-purple-900/50 to-zinc-900">
              <ImageIcon className="w-16 h-16 text-zinc-600" />
            </div>
          )}
          <div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity">
            <Button variant="secondary" onClick={() => coverInputRef.current?.click()} disabled={uploadingCover}>
              {uploadingCover ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Upload className="w-4 h-4 mr-2" />}
              Changer la couverture
            </Button>
          </div>
          <input
            ref={coverInputRef}
            type="file"
            accept="image/*"
            className="hidden"
            onChange={(e) => {
              const file = e.target.files?.[0]
              if (file) handleImageUpload(file, "cover")
            }}
          />
        </div>
      </Card>

      {/* Profile Settings */}
      <Card className="bg-zinc-800/50 border-zinc-700">
        <CardHeader>
          <CardTitle className="text-white flex items-center gap-2">
            <User className="w-5 h-5 text-purple-400" />
            Profil artiste
          </CardTitle>
          <CardDescription className="text-zinc-400">Informations visibles par vos auditeurs</CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Avatar Upload */}
          <div className="flex items-center gap-4">
            <div className="relative">
              <img
                src={profile.avatar_url || "/placeholder.svg?height=80&width=80&query=artist"}
                alt="Profile"
                className="w-20 h-20 rounded-full object-cover border-2 border-zinc-700"
              />
              <button
                onClick={() => avatarInputRef.current?.click()}
                disabled={uploadingAvatar}
                className="absolute -bottom-1 -right-1 w-8 h-8 bg-purple-600 rounded-full flex items-center justify-center hover:bg-purple-700 transition-colors disabled:opacity-50"
              >
                {uploadingAvatar ? (
                  <Loader2 className="w-4 h-4 animate-spin text-white" />
                ) : (
                  <Camera className="w-4 h-4 text-white" />
                )}
              </button>
              <input
                ref={avatarInputRef}
                type="file"
                accept="image/*"
                className="hidden"
                onChange={(e) => {
                  const file = e.target.files?.[0]
                  if (file) handleImageUpload(file, "avatar")
                }}
              />
            </div>
            <div>
              <p className="text-white font-medium">Photo de profil</p>
              <p className="text-zinc-500 text-sm">JPG, PNG. Max 5MB. Recommande: 400x400px</p>
            </div>
          </div>

          <div className="grid sm:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label className="text-zinc-300">Nom d'artiste</Label>
              <Input
                value={profile.name}
                onChange={(e) => setProfile({ ...profile, name: e.target.value })}
                className="bg-zinc-900/50 border-zinc-700 text-white"
                placeholder="Votre nom de scene"
              />
            </div>
            <div className="space-y-2">
              <Label className="text-zinc-300">Pays</Label>
              <Input
                value={profile.country}
                onChange={(e) => setProfile({ ...profile, country: e.target.value })}
                className="bg-zinc-900/50 border-zinc-700 text-white"
                placeholder="Ex: France, Mali, Senegal"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label className="text-zinc-300">Genres musicaux</Label>
            <Input
              value={profile.genres}
              onChange={(e) => setProfile({ ...profile, genres: e.target.value })}
              className="bg-zinc-900/50 border-zinc-700 text-white"
              placeholder="Ex: Hip-Hop, Afrobeat, R&B (separes par des virgules)"
            />
          </div>

          <div className="space-y-2">
            <Label className="text-zinc-300">Bio</Label>
            <Textarea
              value={profile.bio}
              onChange={(e) => setProfile({ ...profile, bio: e.target.value })}
              className="bg-zinc-900/50 border-zinc-700 text-white min-h-[120px]"
              placeholder="Racontez votre histoire, votre parcours musical..."
            />
            <p className="text-zinc-500 text-sm">{profile.bio.length}/500 caracteres</p>
          </div>

          <div className="border-t border-zinc-700 pt-4">
            <h3 className="text-white font-medium mb-4">Liens sociaux</h3>
            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label className="text-zinc-300">Site web</Label>
                <Input
                  value={profile.website}
                  onChange={(e) => setProfile({ ...profile, website: e.target.value })}
                  className="bg-zinc-900/50 border-zinc-700 text-white"
                  placeholder="https://votresite.com"
                />
              </div>
              <div className="space-y-2">
                <Label className="text-zinc-300">Instagram</Label>
                <Input
                  value={profile.instagram}
                  onChange={(e) => setProfile({ ...profile, instagram: e.target.value })}
                  className="bg-zinc-900/50 border-zinc-700 text-white"
                  placeholder="@votrecompte"
                />
              </div>
              <div className="space-y-2">
                <Label className="text-zinc-300">Twitter / X</Label>
                <Input
                  value={profile.twitter}
                  onChange={(e) => setProfile({ ...profile, twitter: e.target.value })}
                  className="bg-zinc-900/50 border-zinc-700 text-white"
                  placeholder="@votrecompte"
                />
              </div>
              <div className="space-y-2">
                <Label className="text-zinc-300">YouTube</Label>
                <Input
                  value={profile.youtube}
                  onChange={(e) => setProfile({ ...profile, youtube: e.target.value })}
                  className="bg-zinc-900/50 border-zinc-700 text-white"
                  placeholder="@votrechaine"
                />
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Notifications */}
      <Card className="bg-zinc-800/50 border-zinc-700">
        <CardHeader>
          <CardTitle className="text-white flex items-center gap-2">
            <Bell className="w-5 h-5 text-purple-400" />
            Notifications
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-white">Nouveaux followers</p>
              <p className="text-zinc-400 text-sm">Recevoir une notification pour chaque nouveau follower</p>
            </div>
            <Switch
              checked={notifications.newFollower}
              onCheckedChange={(checked) => setNotifications({ ...notifications, newFollower: checked })}
            />
          </div>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-white">Ajout en playlist</p>
              <p className="text-zinc-400 text-sm">Quand un titre est ajoute a une playlist editoriale</p>
            </div>
            <Switch
              checked={notifications.playlistAdd}
              onCheckedChange={(checked) => setNotifications({ ...notifications, playlistAdd: checked })}
            />
          </div>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-white">Jalons de streams</p>
              <p className="text-zinc-400 text-sm">Notifications pour les 1K, 10K, 100K streams, etc.</p>
            </div>
            <Switch
              checked={notifications.streamMilestone}
              onCheckedChange={(checked) => setNotifications({ ...notifications, streamMilestone: checked })}
            />
          </div>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-white">Rapport hebdomadaire</p>
              <p className="text-zinc-400 text-sm">Resume de vos performances chaque semaine</p>
            </div>
            <Switch
              checked={notifications.weeklyReport}
              onCheckedChange={(checked) => setNotifications({ ...notifications, weeklyReport: checked })}
            />
          </div>
        </CardContent>
      </Card>

      {/* Verification Status - Updated to use renderVerificationStatus */}
      <Card className="bg-zinc-800/50 border-zinc-700">
        <CardHeader>
          <CardTitle className="text-white flex items-center gap-2">
            <Shield className="w-5 h-5 text-purple-400" />
            Verification
          </CardTitle>
        </CardHeader>
        <CardContent>{renderVerificationStatus()}</CardContent>
      </Card>

      {/* Save Button */}
      <div className="flex justify-end gap-3">
        <Button variant="outline" className="border-zinc-700 text-zinc-300 bg-transparent">
          Annuler
        </Button>
        <Button onClick={handleSave} disabled={saving} className="bg-purple-600 hover:bg-purple-700">
          {saving ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              Enregistrement...
            </>
          ) : (
            "Enregistrer les modifications"
          )}
        </Button>
      </div>

      <Dialog open={verificationDialogOpen} onOpenChange={setVerificationDialogOpen}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Shield className="w-5 h-5 text-purple-400" />
              Demande de verification
            </DialogTitle>
            <DialogDescription className="text-zinc-400">
              Remplissez ce formulaire pour demander la verification de votre profil artiste.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label className="text-zinc-300">Pourquoi souhaitez-vous etre verifie?</Label>
              <Textarea
                value={verificationForm.reason}
                onChange={(e) => setVerificationForm({ ...verificationForm, reason: e.target.value })}
                className="bg-zinc-800 border-zinc-700 text-white min-h-[100px]"
                placeholder="Decrivez votre parcours musical, vos accomplissements, pourquoi vous meritez le badge verifie..."
              />
            </div>

            <div className="space-y-2">
              <Label className="text-zinc-300">Liens vers des articles de presse (un par ligne)</Label>
              <Textarea
                value={verificationForm.pressLinks}
                onChange={(e) => setVerificationForm({ ...verificationForm, pressLinks: e.target.value })}
                className="bg-zinc-800 border-zinc-700 text-white"
                placeholder="https://exemple.com/article-sur-vous&#10;https://magazine.com/interview"
                rows={3}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label className="text-zinc-300">Instagram</Label>
                <Input
                  value={verificationForm.instagram}
                  onChange={(e) => setVerificationForm({ ...verificationForm, instagram: e.target.value })}
                  className="bg-zinc-800 border-zinc-700 text-white"
                  placeholder="@votrecompte"
                />
              </div>
              <div className="space-y-2">
                <Label className="text-zinc-300">Twitter / X</Label>
                <Input
                  value={verificationForm.twitter}
                  onChange={(e) => setVerificationForm({ ...verificationForm, twitter: e.target.value })}
                  className="bg-zinc-800 border-zinc-700 text-white"
                  placeholder="@votrecompte"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label className="text-zinc-300">Site web officiel</Label>
              <Input
                value={verificationForm.website}
                onChange={(e) => setVerificationForm({ ...verificationForm, website: e.target.value })}
                className="bg-zinc-800 border-zinc-700 text-white"
                placeholder="https://votresite.com"
              />
            </div>

            <div className="bg-zinc-800/50 rounded-lg p-3 text-sm text-zinc-400">
              <p className="font-medium text-zinc-300 mb-1">Criteres de verification:</p>
              <ul className="list-disc list-inside space-y-1">
                <li>Au moins 1 titre publie sur la plateforme</li>
                <li>Presence sur les reseaux sociaux</li>
                <li>Profil artiste complet (bio, photo, liens)</li>
              </ul>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setVerificationDialogOpen(false)}
              className="border-zinc-700 text-zinc-300 bg-transparent"
            >
              Annuler
            </Button>
            <Button
              onClick={handleSubmitVerification}
              disabled={submittingVerification || !verificationForm.reason}
              className="bg-purple-600 hover:bg-purple-700"
            >
              {submittingVerification ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Envoi...
                </>
              ) : (
                "Soumettre la demande"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
