"use client"

import type React from "react"
import { useState, useEffect } from "react"
import { AuthGuard } from "@/components/auth-guard"
import { DashboardLayout } from "@/components/dashboard-layout"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { CheckCircle2,CircleX } from "lucide-react"
import { getAuthToken, getUser } from "@/lib/auth"

export default function SettingsPage() {
  const [user, setUser] = useState<{ name: string; email: string } | null>(null)
  const [name, setName] = useState("")
  const [email, setEmail] = useState("")
  const [currentPassword, setCurrentPassword] = useState("")
  const [newPassword, setNewPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  // Fetch user data on client side
  useEffect(() => {
    const currentUser = getUser()
    if (currentUser) {
      setUser(currentUser)
      setName(currentUser.name || "")
      setEmail(currentUser.email || "")
    }
  }, [])

  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setSuccess(false)
    setError(null)

    try {
      const token = getAuthToken()
      if (!token) {
        setError("Aucun jeton d'authentification trouvé")
        setLoading(false)
        return
      }

      const response = await fetch("/api/users/profile", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ name, email }),
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || `Échec de la mise à jour du profil : ${response.status}`)
      }

      const data = await response.json()
      // Update localStorage with new user data
      if (typeof window !== "undefined") {
        localStorage.setItem("user", JSON.stringify(data.user))
        setUser(data.user)
      }
      setSuccess(true)
      setTimeout(() => setSuccess(false), 3000)
    } catch (err: any) {
      setError(`Erreur lors de la mise à jour du profil`)
      // console.error("Erreur de mise à jour du profil :", err)
    } finally {
      setLoading(false)
    }
  }

  const handleUpdatePassword = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setSuccess(false)
    setError(null)

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

    try {
      const token = getAuthToken()
      if (!token) {
        setError("Aucun jeton d'authentification trouvé")
        setLoading(false)
        return
      }

      const response = await fetch("/api/users/profile", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ currentPassword, newPassword }),
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || `Échec de la mise à jour du mot de passe : ${response.status}`)
      }

      setSuccess(true)
      setCurrentPassword("")
      setNewPassword("")
      setConfirmPassword("")
      setTimeout(() => setSuccess(false), 3000)
    } catch (err: any) {
      setError(`Erreur lors de la mise à jour du mot de passe`)
      // console.error("Erreur de mise à jour du mot de passe :", err)
    } finally {
      setLoading(false)
    }
  }

  return (
    <AuthGuard allowedRoles={["admin"]}>
      <DashboardLayout>
        <div className="space-y-6">
          <div className="hidden md:block">
            <h1 className="text-3xl font-semibold tracking-tight">Paramètres</h1>
            <p className="text-muted-foreground">Gérer les paramètres de votre compte</p>
          </div>

          {success && (
            <Alert variant={"success"}>
              <CheckCircle2 size={4}/>
              <AlertDescription>Paramètres mis à jour avec succès !</AlertDescription>
            </Alert>
          )}

          {error && (
            <Alert variant={"destructive"}>
              <CircleX size={4}/>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          <Card className="border-border">
            <CardHeader>
              <CardTitle>Informations du profil</CardTitle>
              <CardDescription>Mettre à jour les informations de votre profil</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleUpdateProfile} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="name">Nom complet</Label>
                  <Input
                    id="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    required
                    className="bg-background"
                    disabled={!user || loading}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="email">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                    className="bg-background"
                    disabled={!user || loading}
                  />
                </div>

                <Button type="submit" disabled={loading || !user}>
                  {loading ? "Enregistrement..." : "Enregistrer les modifications"}
                </Button>
              </form>
            </CardContent>
          </Card>

          <Card className="border-border">
            <CardHeader>
              <CardTitle>Changer le mot de passe</CardTitle>
              <CardDescription>Mettre à jour votre mot de passe pour sécuriser votre compte</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleUpdatePassword} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="current-password">Mot de passe actuel</Label>
                  <Input
                    id="current-password"
                    type="password"
                    value={currentPassword}
                    onChange={(e) => setCurrentPassword(e.target.value)}
                    required
                    className="bg-background"
                    disabled={!user || loading}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="new-password">Nouveau mot de passe</Label>
                  <Input
                    id="new-password"
                    type="password"
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    required
                    className="bg-background"
                    disabled={!user || loading}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="confirm-password">Confirmer le nouveau mot de passe</Label>
                  <Input
                    id="confirm-password"
                    type="password"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    required
                    className="bg-background"
                    disabled={!user || loading}
                  />
                </div>

                <Button type="submit" disabled={loading || !user}>
                  {loading ? "Mise à jour..." : "Mettre à jour le mot de passe"}
                </Button>
              </form>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </AuthGuard>
  )
}