'use client';
import { useState, useEffect } from 'react';
import { account } from '@/lib/appwrite';
import { Models } from 'appwrite';

interface DebugUsuarioProps {
  className?: string;
}

const DebugUsuario: React.FC<DebugUsuarioProps> = ({ className = '' }) => {
  const [user, setUser] = useState<Models.User<Models.Preferences> | null>(null);
  const [userData, setUserData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        setLoading(true);
        setError(null);

        // Buscar usuário autenticado diretamente do Appwrite Auth
        const currentUser = await account.get();
        setUser(currentUser);

        // Usar os dados do Auth como userData para debug
        setUserData({
          $id: currentUser.$id,
          'auth-id-appwrite': currentUser.$id,
          'nome': currentUser.name || 'Nome não informado',
          'email': currentUser.email || 'Email não informado',
          'telefone': currentUser.phone || null,
          'email-verificado': currentUser.emailVerification,
          'telefone-verificado': currentUser.phoneVerification,
          'status': currentUser.status ? 'Ativo' : 'Inativo',
          'data-criacao': currentUser.$createdAt,
          'ultima-atualizacao': currentUser.$updatedAt,
          'labels': currentUser.labels || [],
          'preferences': currentUser.prefs || {},
          'nivel': 'cliente', // Valor padrão
          'ativo': true, // Valor padrão
          'registro-completo': false // Valor padrão
        });

      } catch (err) {
        console.error('Erro ao buscar dados do usuário:', err);
        setError(err instanceof Error ? err.message : 'Erro desconhecido');
      } finally {
        setLoading(false);
      }
    };

    fetchUserData();
  }, []);

  const renderFieldValue = (value: any, fieldName: string) => {
    if (value === null || value === undefined) {
      return (
        <div className="bg-red-100 border-2 border-red-300 p-3 rounded-lg">
          <span className="text-red-700 font-bold text-lg" style={{ color: '#b91c1c', opacity: 1 }}>
            ❌ NULL/UNDEFINED
          </span>
        </div>
      );
    }
    
    if (value === '') {
      return (
        <div className="bg-orange-100 border-2 border-orange-300 p-3 rounded-lg">
          <span className="text-orange-700 font-bold text-lg" style={{ color: '#c2410c', opacity: 1 }}>
            ⚠️ STRING VAZIA
          </span>
        </div>
      );
    }
    
    if (Array.isArray(value)) {
      if (value.length === 0) {
        return (
          <div className="bg-orange-100 border-2 border-orange-300 p-3 rounded-lg">
            <span className="text-orange-700 font-bold text-lg" style={{ color: '#c2410c', opacity: 1 }}>
              ⚠️ ARRAY VAZIO
            </span>
          </div>
        );
      }
      return (
        <div className="bg-green-100 border-2 border-green-300 p-3 rounded-lg">
          <span className="text-green-700 font-bold text-lg" style={{ color: '#15803d', opacity: 1 }}>✅ ARRAY ({value.length} itens)</span>
          <pre className="mt-3 text-sm bg-white p-3 rounded border-2 border-gray-300 overflow-auto max-h-32" style={{ color: '#000000', opacity: 1 }}>
            {JSON.stringify(value, null, 2)}
          </pre>
        </div>
      );
    }
    
    if (typeof value === 'object') {
      return (
        <div className="bg-green-100 border-2 border-green-300 p-3 rounded-lg">
          <span className="text-green-700 font-bold text-lg" style={{ color: '#15803d', opacity: 1 }}>✅ OBJETO</span>
          <pre className="mt-3 text-sm bg-white p-3 rounded border-2 border-gray-300 overflow-auto max-h-32" style={{ color: '#000000', opacity: 1 }}>
            {JSON.stringify(value, null, 2)}
          </pre>
        </div>
      );
    }
    
    return (
      <div className="bg-green-100 border-2 border-green-300 p-3 rounded-lg">
        <span className="text-green-700 font-bold text-lg" style={{ color: '#15803d', opacity: 1 }}>✅ PREENCHIDO</span>
        <div className="mt-3 text-base bg-white p-3 rounded border-2 border-gray-300 font-medium" style={{ color: '#000000', opacity: 1 }}>
          {String(value)}
        </div>
      </div>
    );
  };

  const checkRegistroCompleto = () => {
    if (!userData) return { completo: false, motivos: ['Usuário não encontrado na base de dados'] };
    
    const motivos: string[] = [];
    
    // Verificar campos obrigatórios conforme useRegistroCompleto
    if (!userData['nome-civil'] || !userData.cpf) {
      motivos.push('Dados pessoais incompletos (nome-civil ou cpf)');
    }
    
    if (!userData.enderecos || userData.enderecos.length === 0) {
      motivos.push('Endereços não preenchidos');
    }
    
    return {
      completo: motivos.length === 0,
      motivos
    };
  };

  if (loading) {
    return (
      <div className={`p-8 bg-white rounded-xl shadow-2xl border-2 border-gray-200 ${className}`}>
        <div className="animate-pulse">
          <div className="h-8 bg-gray-300 rounded w-1/3 mb-6"></div>
          <div className="space-y-4">
            <div className="h-6 bg-gray-300 rounded"></div>
            <div className="h-6 bg-gray-300 rounded w-5/6"></div>
            <div className="h-6 bg-gray-300 rounded w-4/6"></div>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={`p-8 bg-red-50 border-4 border-red-300 rounded-xl shadow-2xl ${className}`}>
        <h2 className="text-3xl font-bold text-red-800 mb-6">❌ Erro ao Carregar Dados</h2>
        <p className="text-xl text-red-700 font-medium">{error}</p>
      </div>
    );
  }

  const registroStatus = checkRegistroCompleto();

  return (
    <div className={`p-8 bg-white rounded-xl shadow-2xl border-2 border-gray-200 ${className}`}>
      <h2 className="text-4xl font-bold text-gray-900 mb-8 border-b-4 border-blue-500 pb-4" style={{ color: '#111827', opacity: 1 }}>🔍 Debug - Dados do Usuário</h2>
      
      {/* Status do Registro */}
      <div className={`p-6 rounded-xl mb-8 border-4 ${
        registroStatus.completo 
          ? 'bg-green-50 border-green-400' 
          : 'bg-red-50 border-red-400'
      }`}>
        <h3 className="text-2xl font-bold mb-4" style={{ color: registroStatus.completo ? '#15803d' : '#b91c1c', opacity: 1 }}>
          {registroStatus.completo ? '✅ Registro Completo' : '❌ Registro Incompleto'}
        </h3>
        {!registroStatus.completo && (
          <ul className="list-disc list-inside text-red-700 text-lg font-medium space-y-2">
            {registroStatus.motivos.map((motivo, index) => (
              <li key={index} style={{ color: '#b91c1c', opacity: 1 }}>{motivo}</li>
            ))}
          </ul>
        )}
      </div>

      {/* Dados de Autenticação */}
      <div className="mb-8">
        <h3 className="text-2xl font-bold text-gray-800 mb-4 border-l-4 border-blue-500 pl-4" style={{ color: '#1f2937', opacity: 1 }}>👤 Dados de Autenticação (Appwrite)</h3>
        <div className="bg-blue-50 p-6 rounded-xl border-2 border-blue-200">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="bg-white p-4 rounded-lg border-2 border-gray-300">
              <strong className="text-lg text-gray-700" style={{ color: '#374151', opacity: 1 }}>ID:</strong>
              <div className="text-base font-medium mt-2" style={{ color: '#000000', opacity: 1 }}>{user?.$id || 'N/A'}</div>
            </div>
            <div className="bg-white p-4 rounded-lg border-2 border-gray-300">
              <strong className="text-lg text-gray-700" style={{ color: '#374151', opacity: 1 }}>Nome:</strong>
              <div className="text-base font-medium mt-2" style={{ color: '#000000', opacity: 1 }}>{user?.name || 'N/A'}</div>
            </div>
            <div className="bg-white p-4 rounded-lg border-2 border-gray-300">
              <strong className="text-lg text-gray-700" style={{ color: '#374151', opacity: 1 }}>Email:</strong>
              <div className="text-base font-medium mt-2" style={{ color: '#000000', opacity: 1 }}>{user?.email || 'N/A'}</div>
            </div>
            <div className="bg-white p-4 rounded-lg border-2 border-gray-300">
              <strong className="text-lg text-gray-700" style={{ color: '#374151', opacity: 1 }}>Verificado:</strong>
              <div className="text-base font-medium mt-2" style={{ color: '#000000', opacity: 1 }}>{user?.emailVerification ? '✅' : '❌'}</div>
            </div>
          </div>
        </div>
      </div>

      {/* Dados da Base de Dados */}
      <div>
        <h3 className="text-2xl font-bold text-gray-800 mb-4 border-l-4 border-purple-500 pl-4" style={{ color: '#1f2937', opacity: 1 }}>🗄️ Dados na Base de Dados</h3>
        
        {!userData ? (
          <div className="bg-red-100 border-4 border-red-400 p-6 rounded-xl">
            <p className="text-red-800 font-bold text-xl" style={{ color: '#991b1b', opacity: 1 }}>❌ Usuário não encontrado na coleção 'usuarios'</p>
            <p className="text-lg text-red-700 mt-3 font-medium" style={{ color: '#b91c1c', opacity: 1 }}>
              Buscando por auth-id-appwrite: {user?.$id}
            </p>
          </div>
        ) : (
          <div className="space-y-6">
            {/* Campos Principais */}
            <div className="bg-purple-50 p-6 rounded-xl border-2 border-purple-200">
              <h4 className="text-xl font-bold mb-4 text-purple-800" style={{ color: '#6b21a8', opacity: 1 }}>📋 Campos Principais</h4>
              <div className="space-y-4">
                <div>
                  <strong className="text-lg text-gray-800 block mb-2" style={{ color: '#1f2937', opacity: 1 }}>nome-civil:</strong>
                  {renderFieldValue(userData['nome-civil'], 'nome-civil')}
                </div>
                <div>
                  <strong className="text-lg text-gray-800 block mb-2" style={{ color: '#1f2937', opacity: 1 }}>nome-social:</strong>
                  {renderFieldValue(userData['nome-social'], 'nome-social')}
                </div>
                <div>
                  <strong className="text-lg text-gray-800 block mb-2" style={{ color: '#1f2937', opacity: 1 }}>cpf:</strong>
                  {renderFieldValue(userData.cpf, 'cpf')}
                </div>
                <div>
                  <strong className="text-lg text-gray-800 block mb-2" style={{ color: '#1f2937', opacity: 1 }}>email:</strong>
                  {renderFieldValue(userData.email, 'email')}
                </div>
                <div>
                  <strong className="text-lg text-gray-800 block mb-2" style={{ color: '#1f2937', opacity: 1 }}>auth-id-appwrite:</strong>
                  {renderFieldValue(userData['auth-id-appwrite'], 'auth-id-appwrite')}
                </div>
              </div>
            </div>

            {/* Endereços */}
            <div className="bg-yellow-50 p-6 rounded-xl border-2 border-yellow-200">
              <h4 className="text-xl font-bold mb-4 text-yellow-800" style={{ color: '#92400e', opacity: 1 }}>🏠 Endereços</h4>
              {renderFieldValue(userData.enderecos, 'enderecos')}
            </div>

            {/* Empresas */}
            <div className="bg-indigo-50 p-6 rounded-xl border-2 border-indigo-200">
              <h4 className="text-xl font-bold mb-4 text-indigo-800" style={{ color: '#3730a3', opacity: 1 }}>🏢 Empresas</h4>
              {renderFieldValue(userData.empresas, 'empresas')}
            </div>

            {/* Todos os Campos */}
            <div className="bg-gray-50 p-6 rounded-xl border-2 border-gray-300">
              <h4 className="text-xl font-bold mb-4 text-gray-800" style={{ color: '#1f2937', opacity: 1 }}>📄 Documento Completo</h4>
              <pre className="text-sm bg-white p-4 rounded-lg border-2 border-gray-300 overflow-auto max-h-96 font-mono" style={{ color: '#000000', opacity: 1 }}>
                {JSON.stringify(userData, null, 2)}
              </pre>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default DebugUsuario;