"use client"

import React, { useState, useEffect, useCallback } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { User, Shield, Key, Edit, Copy, CheckCircle, ArrowLeft, Save, X } from "@/lib/icons"
import UserStore from "@/lib/4nk/UserStore"
import { use4NK } from "@/lib/contexts/FourNKContext"
import MessageBus from "@/lib/4nk/MessageBus"
import { iframeUrl } from "@/app/page"

export default function AccountPage() {
  const [userInfo, setUserInfo] = useState<any>(null)
  const [userPairingId, setUserPairingId] = useState<string | null>(null)
  const [isCopied, setIsCopied] = useState(false)
  const [isEditing, setIsEditing] = useState(false)
  const [editedName, setEditedName] = useState("")
  const [isUpdating, setIsUpdating] = useState(false)
  const router = useRouter()
  
  // Récupérer les données du contexte 4NK
  const { userName, refreshUserName } = use4NK()

  useEffect(() => {
    const updateUserInfo = async () => {
      const userStore = UserStore.getInstance()
      const accessToken = userStore.getAccessToken()
      const pairingId = userStore.getUserPairingId()
      
      setUserPairingId(pairingId)
      
      if (accessToken && userName !== null) {
        setUserInfo({
          id: pairingId?.slice(0, 8) + "...",
          name: userName,
          role: "Utilisateur",
        })
      }
    };
    
    updateUserInfo();
  }, [userName])

  const handleCopyToClipboard = () => {
    if (userPairingId) {
      navigator.clipboard.writeText(userPairingId).then(() => {
        setIsCopied(true);
        setTimeout(() => setIsCopied(false), 2000);
      }).catch(err => {
        console.error('Erreur lors de la copie : ', err);
      });
    }
  }

  // Fonction pour mettre à jour le memberPublicName
  const handleUpdateName = useCallback(async (newName: string) => {
    if (!userPairingId) return;

    setIsUpdating(true);
    try {
      const messageBus = MessageBus.getInstance(iframeUrl);
      await messageBus.isReady();

      const updateData = {
        memberPublicName: newName
      };

      // 1. Mettre à jour le process
      const updatedProcess = await messageBus.updateProcess(userPairingId, updateData, [], null);
      console.log("Process mis à jour :", updatedProcess);

      if (!updatedProcess) {
        throw new Error('updateProcess n\'a pas retourné de process mis à jour');
      }

      // 2. Extraire le newStateId
      const newStateId = updatedProcess.diffs[0]?.state_id;
      if (!newStateId) {
        throw new Error('No new state id found');
      }

      // 3. Notifier et Valider
      await messageBus.notifyProcessUpdate(userPairingId, newStateId);
      await messageBus.validateState(userPairingId, newStateId);
      
      // 4. Attendre un peu pour que la mise à jour se propage
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 5. Forcer la mise à jour du contexte
      await refreshUserName();
      
      // 6. Mettre à jour l'interface
      setIsEditing(false);
      setEditedName("");

    } catch (error) {
      console.error('Error updating name:', error);
      alert('Erreur lors de la mise à jour du nom');
    } finally {
      setIsUpdating(false);
    }
  }, [userPairingId, refreshUserName]);

  const handleStartEdit = () => {
    setEditedName(userName || "");
    setIsEditing(true);
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditedName("");
  };

  const handleSaveEdit = () => {
    if (editedName.trim() && editedName.trim() !== userName) {
      handleUpdateName(editedName.trim());
    } else {
      setIsEditing(false);
      setEditedName("");
    }
  };

  if (!userInfo) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <div className="text-center">
          <Shield className="h-12 w-12 mx-auto mb-4 text-blue-600 dark:text-blue-400" />
          <p className="text-gray-600 dark:text-gray-400">Chargement du profil...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-6">
      <div className="max-w-2xl mx-auto space-y-6">
        
        {/* Header */}
        <div className="relative">
          <Button 
            variant="ghost" 
            size="sm" 
            onClick={() => router.back()}
            className="absolute left-0 top-0 flex items-center text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
          >
            <ArrowLeft className="h-4 w-4 mr-1" />
            Retour
          </Button>
          <div className="text-center">
            <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
              Mon Profil
            </h1>
            <p className="text-gray-600 dark:text-gray-400 mt-2">
              Informations de votre compte 4NK
            </p>
          </div>
        </div>

        {/* Profile Card */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-center">
              <User className="h-5 w-5 mr-2" />
              Profil Utilisateur
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            
            {/* User Avatar and Basic Info */}
            <div className="flex flex-col items-center space-y-4">
              <div className="w-20 h-20 bg-blue-100 dark:bg-blue-800 rounded-full flex items-center justify-center">
                <span className="text-blue-600 dark:text-blue-400 font-bold text-2xl">
                  {userInfo.name.charAt(0)}
                </span>
              </div>
              <div className="text-center space-y-2">
                {isEditing ? (
                  <div className="flex items-center space-x-2">
                    <Input
                      value={editedName}
                      onChange={(e) => setEditedName(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter' && editedName.trim()) {
                          handleSaveEdit();
                        } else if (e.key === 'Escape') {
                          handleCancelEdit();
                        }
                      }}
                      className="text-center text-xl font-semibold"
                      placeholder="Entrez votre nom"
                      disabled={isUpdating}
                      autoFocus
                    />
                    <Button
                      size="sm"
                      onClick={handleSaveEdit}
                      disabled={isUpdating || !editedName.trim()}
                    >
                      {isUpdating ? (
                        <div className="animate-spin h-4 w-4 border-2 border-blue-600 border-t-transparent rounded-full" />
                      ) : (
                        <Save className="h-4 w-4" />
                      )}
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={handleCancelEdit}
                      disabled={isUpdating}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                ) : (
                  <div className="flex items-center justify-center space-x-2">
                    <h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
                      {userInfo.name}
                    </h3>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={handleStartEdit}
                      className="opacity-60 hover:opacity-100"
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                  </div>
                )}
              </div>
            </div>

            <hr className="border-gray-200 dark:border-gray-700" />

            {/* Account Details */}
            <div className="space-y-4">
              <div className="flex justify-between items-center">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  ID Utilisateur
                </label>
                <div className="flex items-center space-x-2">
                  <span className="text-gray-900 dark:text-gray-100 font-mono text-sm">
                    {userInfo.id}
                  </span>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleCopyToClipboard}
                    className="h-6 w-6 p-0"
                  >
                    {isCopied ? (
                      <CheckCircle className="h-4 w-4 text-green-500" />
                    ) : (
                      <Copy className="h-4 w-4 text-gray-500" />
                    )}
                  </Button>
                </div>
              </div>
              
              <div className="flex justify-between items-center">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Rôle
                </label>
                <span className="text-gray-900 dark:text-gray-100">{userInfo.role}</span>
              </div>

            </div>
          </CardContent>
        </Card>

        {/* Security Card */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-center">
              <Shield className="h-5 w-5 mr-2" />
              Sécurité 4NK
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center justify-center">
                <Key className="h-4 w-4 mr-1" />
                ID de Jumelage Complet
              </label>
              <div className="bg-gray-100 dark:bg-gray-800 p-3 rounded-lg">
                <p className="text-xs font-mono text-gray-600 dark:text-gray-400 break-all text-center">
                  {userPairingId || 'Non disponible'}
                </p>
              </div>
            </div>

            <div className="flex items-center justify-center p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
              <div className="flex items-center">
                <Shield className="h-5 w-5 text-green-600 dark:text-green-400 mr-2" />
                <span className="text-sm font-medium text-green-800 dark:text-green-200">
                  Chiffrement actif
                </span>
              </div>
              <Badge variant="outline" className="bg-green-100 dark:bg-green-800 text-green-700 dark:text-green-200 border-green-200 dark:border-green-700 ml-2">
                4NK
              </Badge>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
