"use client";
import React, { useState, useEffect } from "react";
import { User, Mail, CreditCard, Shield, MapPin, Building } from "lucide-react";
import { formatCPF } from "@/lib/masks";

interface UserData {
  id: string;
  nome: string;
  email: string;
  cpf: string;
  "nome-social": string;
  nivel: string;
  "registro-completo": boolean;
  enderecos: string[];
  empresasDados: string[];
  createdAt: string;
  updatedAt: string;
}

interface EnderecoData {
  id: string;
  titulo: string;
  cep: string;
  logradouro: string;
  numero: string;
  complemento: string;
  cidade: string;
  estado: string;
  pais: string;
  bairro: string;
}

interface EmpresaData {
  id: string;
  cnpj: string;
  "razao-social": string;
  "nome-fantasia": string;
  "data-abertura": string;
  situacao: string;
  "natureza-juridica": string;
  porte: string;
  "capital-social": number;
  telefone: string;
  email: string;
  "atividade-principal-codigo": string;
  "atividade-principal-desc": string;
}

export default function ProfileForm({ usuarioData }: { usuarioData?: UserData | null }) {
  const [showEditForm, setShowEditForm] = useState(false);
  const [enderecosDetalhados, setEnderecosDetalhados] = useState<EnderecoData[]>([]);
  const [empresasDetalhadas, setEmpresasDetalhadas] = useState<EmpresaData[]>([]);
  const [loadingDetalhes, setLoadingDetalhes] = useState(false);

  // Buscar dados detalhados quando usuarioData mudar
  useEffect(() => {
    if (usuarioData && (usuarioData.enderecos.length > 0 || usuarioData.empresasDados.length > 0)) {
      buscarDadosDetalhados();
    }
  }, [usuarioData]);

  const buscarDadosDetalhados = async () => {
    if (!usuarioData) return;
    
    setLoadingDetalhes(true);
    try {
      const token = localStorage.getItem('access_token');
      
      if (!token) {
        console.error('Token de acesso não encontrado');
        return;
      }

      // Buscar dados dos endereços
      const enderecosPromises = usuarioData.enderecos.map(async (enderecoId) => {
        const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL}/enderecos/${enderecoId}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Accept': 'application/json',
          },
        });
        
        if (response.ok) {
          return await response.json();
        }
        return null;
      });

      // Buscar dados das empresas
      const empresasPromises = usuarioData.empresasDados.map(async (empresaId) => {
        const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL}/empresas/${empresaId}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Accept': 'application/json',
          },
        });
        
        if (response.ok) {
          return await response.json();
        }
        return null;
      });

      const [enderecosResults, empresasResults] = await Promise.all([
        Promise.all(enderecosPromises),
        Promise.all(empresasPromises)
      ]);

      setEnderecosDetalhados(enderecosResults.filter(Boolean));
      setEmpresasDetalhadas(empresasResults.filter(Boolean));
      
    } catch (error) {
      console.error('Erro ao buscar dados detalhados:', error);
    } finally {
      setLoadingDetalhes(false);
    }
  };

  if (!usuarioData) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <p className="text-gray-600">Carregando dados do usuário...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto p-6 space-y-6">
      {/* Header do Perfil */}
      <div className="bg-white rounded-lg shadow-md p-6">
        <div className="flex items-center space-x-4">
          <div className="w-16 h-16 bg-blue-500 rounded-full flex items-center justify-center">
            <User className="w-8 h-8 text-white" />
          </div>
          <div className="flex-1">
            <h1 className="text-2xl font-bold text-gray-900">{usuarioData.nome}</h1>
            <p className="text-gray-600">{usuarioData.email}</p>
            <div className="flex items-center space-x-2 mt-2">
              <span className="px-2 py-1 bg-blue-100 text-blue-800 rounded-full text-xs font-medium">
                {usuarioData.nivel}
              </span>
              {usuarioData["registro-completo"] && (
                <span className="px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs font-medium">
                  ✓ Registro Completo
                </span>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Informações Básicas */}
      <div className="bg-white rounded-lg shadow-md p-6">
        <h2 className="text-xl font-semibold text-gray-900 mb-4 flex items-center">
          <User className="w-5 h-5 mr-2" />
          Informações Básicas
        </h2>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="flex items-center space-x-3">
            <User className="w-5 h-5 text-gray-400" />
            <div>
              <p className="text-sm text-gray-500">Nome</p>
              <p className="text-gray-900">{usuarioData.nome}</p>
            </div>
          </div>
          
          <div className="flex items-center space-x-3">
            <Mail className="w-5 h-5 text-gray-400" />
            <div>
              <p className="text-sm text-gray-500">E-mail</p>
              <p className="text-gray-900">{usuarioData.email}</p>
            </div>
          </div>
          
          <div className="flex items-center space-x-3">
            <CreditCard className="w-5 h-5 text-gray-400" />
            <div>
              <p className="text-sm text-gray-500">CPF</p>
              <p className="text-gray-900">{formatCPF(usuarioData.cpf)}</p>
            </div>
          </div>
          
          <div className="flex items-center space-x-3">
            <Shield className="w-5 h-5 text-gray-400" />
            <div>
              <p className="text-sm text-gray-500">Nome Social</p>
              <p className="text-gray-900">{usuarioData["nome-social"] || "Não informado"}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Estatísticas */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-2">
            Endereços Cadastrados
          </h3>
          <p className="text-3xl font-bold text-blue-600">{usuarioData.enderecos?.length || 0}</p>
        </div>
        
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-2">
            Empresas Vinculadas
          </h3>
          <p className="text-3xl font-bold text-green-600">{usuarioData.empresasDados?.length || 0}</p>
        </div>
      </div>

      {/* Endereços Detalhados */}
      {enderecosDetalhados.length > 0 && (
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-xl font-semibold text-gray-900 mb-4 flex items-center">
            <MapPin className="w-5 h-5 mr-2" />
            Endereços Cadastrados
          </h3>
          <div className="space-y-4">
            {enderecosDetalhados.map((endereco, index) => (
              <div key={endereco.id} className="border border-gray-200 rounded-lg p-4">
                <div className="flex items-center justify-between mb-2">
                  <h4 className="font-medium text-gray-900">{endereco.titulo}</h4>
                  <span className="text-sm text-gray-500">#{endereco.id.slice(-8)}</span>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-gray-500">Endereço:</span>
                    <p className="text-gray-900">
                      {endereco.logradouro}, {endereco.numero}
                      {endereco.complemento && ` - ${endereco.complemento}`}
                    </p>
                  </div>
                  <div>
                    <span className="text-gray-500">Bairro:</span>
                    <p className="text-gray-900">{endereco.bairro}</p>
                  </div>
                  <div>
                    <span className="text-gray-500">Cidade/Estado:</span>
                    <p className="text-gray-900">{endereco.cidade} - {endereco.estado}</p>
                  </div>
                  <div>
                    <span className="text-gray-500">CEP:</span>
                    <p className="text-gray-900">{endereco.cep}</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
          {loadingDetalhes && (
            <div className="text-center py-4">
              <p className="text-gray-500">Carregando dados dos endereços...</p>
            </div>
          )}
        </div>
      )}

      {/* Empresas Detalhadas */}
      {empresasDetalhadas.length > 0 && (
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-xl font-semibold text-gray-900 mb-4 flex items-center">
            <Building className="w-5 h-5 mr-2" />
            Empresas Vinculadas
          </h3>
          <div className="space-y-4">
            {empresasDetalhadas.map((empresa, index) => (
              <div key={empresa.id} className="border border-gray-200 rounded-lg p-4">
                <div className="flex items-center justify-between mb-2">
                  <h4 className="font-medium text-gray-900">{empresa["nome-fantasia"]}</h4>
                  <span className="text-sm text-gray-500">#{empresa.id.slice(-8)}</span>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-gray-500">Razão Social:</span>
                    <p className="text-gray-900">{empresa["razao-social"]}</p>
                  </div>
                  <div>
                    <span className="text-gray-500">CNPJ:</span>
                    <p className="text-gray-900">{empresa.cnpj}</p>
                  </div>
                  <div>
                    <span className="text-gray-500">Situação:</span>
                    <p className="text-gray-900">{empresa.situacao}</p>
                  </div>
                  <div>
                    <span className="text-gray-500">Porte:</span>
                    <p className="text-gray-900">{empresa.porte}</p>
                  </div>
                  <div>
                    <span className="text-gray-500">Telefone:</span>
                    <p className="text-gray-900">{empresa.telefone}</p>
                  </div>
                  <div>
                    <span className="text-gray-500">Email:</span>
                    <p className="text-gray-900">{empresa.email}</p>
                  </div>
                  <div className="md:col-span-2">
                    <span className="text-gray-500">Atividade Principal:</span>
                    <p className="text-gray-900">{empresa["atividade-principal-desc"]}</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
          {loadingDetalhes && (
            <div className="text-center py-4">
              <p className="text-gray-500">Carregando dados das empresas...</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
