"use client"

import type React from "react"

import { useState, useRef } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { ChevronLeft, Camera, Loader2 } from "lucide-react"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { BottomNav } from "@/components/bottom-nav"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"

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

export default function EditProfilePage() {
  const { user, updateProfile } = useAuth()
  const router = useRouter()
  const fileInputRef = useRef<HTMLInputElement>(null)

  const [name, setName] = useState(user?.name || "")
  const [bio, setBio] = useState("")
  const [country, setCountry] = useState(user?.country || "")
  const [language, setLanguage] = useState(user?.language || "fr")
  const [avatarUrl, setAvatarUrl] = useState(user?.avatar || "")
  const [isUploading, setIsUploading] = useState(false)
  const [isSaving, setIsSaving] = useState(false)
  const [error, setError] = useState("")
  const [success, setSuccess] = useState("")

  const { data: userData, mutate } = useSWR(user ? `/api/users/${user.id}` : null, fetcher, {
    onSuccess: (data) => {
      if (data && !name) {
        setName(data.name || "")
        setBio(data.bio || "")
        setCountry(data.country || "")
        setLanguage(data.language || "fr")
        setAvatarUrl(data.avatar_url || "")
      }
    },
  })

  const handleAvatarClick = () => {
    fileInputRef.current?.click()
  }

  const handleAvatarChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    if (!file.type.startsWith("image/")) {
      setError("Veuillez sélectionner une image")
      return
    }

    if (file.size > 4.5 * 1024 * 1024) {
      setError("L'image ne doit pas dépasser 4.5 Mo")
      return
    }

    setIsUploading(true)
    setError("")

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

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

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

      const data = await response.json()
      setAvatarUrl(data.url)
      setSuccess("Photo mise à jour")
    } catch (err) {
      console.error("Upload error:", err)
      setError(err instanceof Error ? err.message : "Erreur lors du téléchargement de l'image")
    } finally {
      setIsUploading(false)
    }
  }

  const handleSave = async () => {
    if (!user) return

    setIsSaving(true)
    setError("")
    setSuccess("")

    try {
      const response = await fetch(`/api/users/${user.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          avatar_url: avatarUrl,
          country,
          language,
        }),
      })

      if (!response.ok) {
        throw new Error("Erreur lors de la sauvegarde")
      }

      // Update auth context
      updateProfile({
        name,
        avatar: avatarUrl,
        country,
        language,
      })

      // Revalidate SWR cache
      mutate()

      setSuccess("Profil mis à jour avec succès!")
      setTimeout(() => router.push("/profile"), 1500)
    } catch (err) {
      console.error("Save error:", err)
      setError("Erreur lors de la sauvegarde du profil")
    } finally {
      setIsSaving(false)
    }
  }

  const getInitials = (name: string) => {
    return name
      .split(" ")
      .map((n) => n[0])
      .join("")
      .toUpperCase()
      .slice(0, 2)
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <p className="text-muted-foreground">Veuillez vous connecter</p>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      <div className="mx-auto max-w-md px-4 py-6">
        {/* Header */}
        <div className="mb-8 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link href="/profile" className="text-foreground hover:text-primary">
              <ChevronLeft className="h-6 w-6" />
            </Link>
            <h1 className="text-xl font-bold text-foreground">Modifier le profil</h1>
          </div>
          <Button onClick={handleSave} disabled={isSaving}>
            {isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : "Enregistrer"}
          </Button>
        </div>

        {/* Messages */}
        {error && <div className="mb-4 rounded-lg bg-destructive/20 p-3 text-sm text-destructive">{error}</div>}
        {success && <div className="mb-4 rounded-lg bg-green-500/20 p-3 text-sm text-green-500">{success}</div>}

        {/* Avatar */}
        <div className="mb-8 flex flex-col items-center">
          <div className="relative">
            <Avatar className="h-24 w-24">
              <AvatarImage src={avatarUrl || "/placeholder.svg"} alt={name} />
              <AvatarFallback>{getInitials(name || "U")}</AvatarFallback>
            </Avatar>
            <button
              onClick={handleAvatarClick}
              disabled={isUploading}
              className="absolute bottom-0 right-0 flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground disabled:opacity-50"
            >
              {isUploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Camera className="h-4 w-4" />}
            </button>
            <input ref={fileInputRef} type="file" accept="image/*" onChange={handleAvatarChange} className="hidden" />
          </div>
          <button
            onClick={handleAvatarClick}
            disabled={isUploading}
            className="mt-2 text-sm text-primary disabled:opacity-50"
          >
            {isUploading ? "Téléchargement..." : "Changer la photo"}
          </button>
        </div>

        {/* Form */}
        <div className="space-y-6">
          <div className="space-y-2">
            <Label htmlFor="name">Nom</Label>
            <Input id="name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Votre nom" />
          </div>

          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input id="email" type="email" value={user.email} disabled className="bg-secondary/50" />
            <p className="text-xs text-muted-foreground">L'email ne peut pas être modifié</p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="bio">Bio</Label>
            <Textarea
              id="bio"
              value={bio}
              onChange={(e) => setBio(e.target.value.slice(0, 150))}
              placeholder="Parlez de vous..."
              rows={3}
            />
            <p className="text-sm text-muted-foreground">{bio.length}/150</p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="country">Pays</Label>
            <Select value={country} onValueChange={setCountry}>
              <SelectTrigger>
                <SelectValue placeholder="Sélectionner un pays" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="CI">Côte d'Ivoire</SelectItem>
                <SelectItem value="SN">Sénégal</SelectItem>
                <SelectItem value="ML">Mali</SelectItem>
                <SelectItem value="BF">Burkina Faso</SelectItem>
                <SelectItem value="GN">Guinée</SelectItem>
                <SelectItem value="CM">Cameroun</SelectItem>
                <SelectItem value="CD">RD Congo</SelectItem>
                <SelectItem value="CG">Congo</SelectItem>
                <SelectItem value="GA">Gabon</SelectItem>
                <SelectItem value="BJ">Bénin</SelectItem>
                <SelectItem value="TG">Togo</SelectItem>
                <SelectItem value="NE">Niger</SelectItem>
                <SelectItem value="FR">France</SelectItem>
                <SelectItem value="BE">Belgique</SelectItem>
                <SelectItem value="CA">Canada</SelectItem>
                <SelectItem value="US">États-Unis</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="language">Langue</Label>
            <Select value={language} onValueChange={setLanguage}>
              <SelectTrigger>
                <SelectValue placeholder="Sélectionner une langue" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="fr">Français</SelectItem>
                <SelectItem value="en">English</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </div>

      <BottomNav />
    </div>
  )
}
