"use client";

import { useState } from "react";
import { X, User, MapPin, Mail, Phone, Lock, Building } from "lucide-react";

interface CadastroColaboradorModalProps {
  onClose: () => void;
  onSuccess: () => void;
  empresaId: string;
}

interface FormData {
  // Dados pessoais
  nome: string;
  email: string;
  telefone: string;
  cpf: string;
  nomeSocial: string;
  senha: string;
  nivel: string;
  
  // Endereço
  titulo: string;
  cep: string;
  logradouro: string;
  numero: string;
  complemento: string;
  cidade: string;
  estado: string;
  pais: string;
  bairro: string;
}

const CadastroColaboradorModal = ({ onClose, onSuccess, empresaId }: CadastroColaboradorModalProps) => {
  const [currentStep, setCurrentStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<FormData>({
    // Dados pessoais
    nome: "",
    email: "",
    telefone: "",
    cpf: "",
    nomeSocial: "",
    senha: "",
    nivel: "colaborador",
    
    // Endereço
    titulo: "Residencial",
    cep: "",
    logradouro: "",
    numero: "",
    complemento: "",
    cidade: "",
    estado: "",
    pais: "Brasil",
    bairro: ""
  });

  const handleInputChange = (field: keyof FormData, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // Buscar endereço por CEP
  const buscarCep = async (cep: string) => {
    if (cep.length !== 8) return;

    try {
      const response = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
      const data = await response.json();
      
      if (!data.erro) {
        setFormData(prev => ({
          ...prev,
          logradouro: data.logradouro || "",
          cidade: data.localidade || "",
          estado: data.uf || "",
          bairro: data.bairro || ""
        }));
      }
    } catch (error) {
      console.error("Erro ao buscar CEP:", error);
    }
  };

  // Validar etapa atual
  const isStepValid = () => {
    if (currentStep === 1) {
      return formData.nome && formData.email && formData.telefone && 
             formData.cpf && formData.senha;
    }
    
    if (currentStep === 2) {
      return formData.cep && formData.logradouro && formData.numero && 
             formData.cidade && formData.estado && formData.bairro;
    }
    
    return true;
  };

  // Criar endereço
  const criarEndereco = async () => {
    const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL!}/enderecos`, {
      method: 'POST',
      headers: {
        'accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      },
      body: JSON.stringify({
        titulo: formData.titulo,
        cep: formData.cep,
        logradouro: formData.logradouro,
        numero: formData.numero,
        complemento: formData.complemento || "",
        cidade: formData.cidade,
        estado: formData.estado,
        pais: formData.pais,
        latitude: null,
        longitude: null,
        bairro: formData.bairro
      })
    });

    if (!response.ok) {
      throw new Error('Erro ao criar endereço');
    }

    const endereco = await response.json();
    return endereco.id || endereco._id;
  };

  // Criar usuário
  const criarUsuario = async (enderecoId: string) => {
    // Criar payload básico
    const payload: any = {
      identificador: formData.email, // Usar email como identificador
      senha: formData.senha,
      ativo: true,
      superadmin: false,
      nome: formData.nome,
      email: formData.email,
      telefone: formData.telefone.replace(/\D/g, ''), // Remover formatação do telefone
      nivel: formData.nivel,
      "registro-completo": true, // Definir como true conforme especificação
      enderecos: [enderecoId], // Array de strings com IDs
      empresasDados: [empresaId], // Array de strings com IDs
      cpf: formData.cpf.replace(/\D/g, '') // Remover formatação do CPF
    };

    // Adicionar campos opcionais apenas se não estiverem vazios
    if (formData.nomeSocial && formData.nomeSocial.trim()) {
      payload["nome-social"] = formData.nomeSocial.trim();
    }

    // auth-id-appwrite pode ser omitido ou null se não for obrigatório
    // Se for obrigatório, usar um valor padrão válido
    // payload["auth-id-appwrite"] = "N/A"; // Descomente se for obrigatório

    const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL!}/usuarios`, {
      method: 'POST',
      headers: {
        'accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      },
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      throw new Error('Erro ao criar usuário');
    }

    return await response.json();
  };

  // Submeter formulário
  const handleSubmit = async () => {
    if (!isStepValid()) return;

    try {
      setLoading(true);

      // 1. Criar endereço
      const enderecoId = await criarEndereco();
      
      // 2. Criar usuário com o ID do endereço
      await criarUsuario(enderecoId);

      onSuccess();
    } catch (error) {
      console.error('Erro ao cadastrar colaborador:', error);
      alert('Erro ao cadastrar colaborador. Verifique os dados e tente novamente.');
    } finally {
      setLoading(false);
    }
  };

  // Formatar CPF
  const formatCpf = (value: string) => {
    const numbers = value.replace(/\D/g, '');
    return numbers.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
  };

  // Formatar telefone
  const formatTelefone = (value: string) => {
    const numbers = value.replace(/\D/g, '');
    if (numbers.length <= 10) {
      return numbers.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
    }
    return numbers.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
  };

  // Formatar CEP
  const formatCep = (value: string) => {
    const numbers = value.replace(/\D/g, '');
    return numbers.replace(/(\d{5})(\d{3})/, '$1-$2');
  };

  return (
    <div className="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">
              Cadastrar Novo Colaborador
            </h2>
            <p className="text-sm text-gray-600 mt-1">
              Etapa {currentStep} de 3 - {
                currentStep === 1 ? "Dados Pessoais" :
                currentStep === 2 ? "Endereço" : "Revisão"
              }
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Progress Bar */}
        <div className="px-6 py-4 bg-gray-50">
          <div className="flex items-center">
            <div className={`flex items-center justify-center w-8 h-8 rounded-full ${
              currentStep >= 1 ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'
            }`}>
              <User className="w-4 h-4" />
            </div>
            <div className={`flex-1 h-1 mx-4 ${
              currentStep >= 2 ? 'bg-blue-600' : 'bg-gray-200'
            }`} />
            <div className={`flex items-center justify-center w-8 h-8 rounded-full ${
              currentStep >= 2 ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'
            }`}>
              <MapPin className="w-4 h-4" />
            </div>
            <div className={`flex-1 h-1 mx-4 ${
              currentStep >= 3 ? 'bg-blue-600' : 'bg-gray-200'
            }`} />
            <div className={`flex items-center justify-center w-8 h-8 rounded-full ${
              currentStep >= 3 ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'
            }`}>
              <Building className="w-4 h-4" />
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="p-6">
          {/* Etapa 1: Dados Pessoais */}
          {currentStep === 1 && (
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Nome Completo *
                  </label>
                  <input
                    type="text"
                    value={formData.nome}
                    onChange={(e) => handleInputChange('nome', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="Nome completo do colaborador"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Nome Social
                  </label>
                  <input
                    type="text"
                    value={formData.nomeSocial}
                    onChange={(e) => handleInputChange('nomeSocial', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="Nome social (opcional)"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Email *
                  </label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                    <input
                      type="email"
                      value={formData.email}
                      onChange={(e) => handleInputChange('email', e.target.value)}
                      className="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      placeholder="email@exemplo.com"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Telefone *
                  </label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                    <input
                      type="text"
                      value={formData.telefone}
                      onChange={(e) => handleInputChange('telefone', formatTelefone(e.target.value))}
                      className="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      placeholder="(11) 99999-9999"
                      maxLength={15}
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    CPF *
                  </label>
                  <input
                    type="text"
                    value={formData.cpf}
                    onChange={(e) => handleInputChange('cpf', formatCpf(e.target.value))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="000.000.000-00"
                    maxLength={14}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Nível *
                  </label>
                  <select
                    value={formData.nivel}
                    onChange={(e) => handleInputChange('nivel', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="colaborador">Colaborador</option>
              
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Senha *
                  </label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                    <input
                      type="password"
                      value={formData.senha}
                      onChange={(e) => handleInputChange('senha', e.target.value)}
                      className="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      placeholder="Senha de acesso"
                    />
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Etapa 2: Endereço */}
          {currentStep === 2 && (
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Título do Endereço *
                  </label>
                  <select
                    value={formData.titulo}
                    onChange={(e) => handleInputChange('titulo', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="Residencial">Residencial</option>
                    <option value="Comercial">Comercial</option>
                    <option value="Correspondência">Correspondência</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    CEP *
                  </label>
                  <input
                    type="text"
                    value={formData.cep}
                    onChange={(e) => {
                      const formatted = formatCep(e.target.value);
                      handleInputChange('cep', formatted);
                      if (formatted.replace(/\D/g, '').length === 8) {
                        buscarCep(formatted.replace(/\D/g, ''));
                      }
                    }}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="00000-000"
                    maxLength={9}
                  />
                </div>

                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Logradouro *
                  </label>
                  <input
                    type="text"
                    value={formData.logradouro}
                    onChange={(e) => handleInputChange('logradouro', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="Rua, Avenida, etc."
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Número *
                  </label>
                  <input
                    type="text"
                    value={formData.numero}
                    onChange={(e) => handleInputChange('numero', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="123"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Complemento
                  </label>
                  <input
                    type="text"
                    value={formData.complemento}
                    onChange={(e) => handleInputChange('complemento', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="Apto, Sala, etc."
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Bairro *
                  </label>
                  <input
                    type="text"
                    value={formData.bairro}
                    onChange={(e) => handleInputChange('bairro', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="Nome do bairro"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Cidade *
                  </label>
                  <input
                    type="text"
                    value={formData.cidade}
                    onChange={(e) => handleInputChange('cidade', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="Nome da cidade"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Estado *
                  </label>
                  <input
                    type="text"
                    value={formData.estado}
                    onChange={(e) => handleInputChange('estado', e.target.value.toUpperCase())}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="SP"
                    maxLength={2}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    País *
                  </label>
                  <input
                    type="text"
                    value={formData.pais}
                    onChange={(e) => handleInputChange('pais', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="Brasil"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Etapa 3: Revisão */}
          {currentStep === 3 && (
            <div className="space-y-6">
              <div className="bg-gray-50 rounded-lg p-4">
                <h3 className="text-lg font-medium text-gray-900 mb-4">Dados Pessoais</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="font-medium text-gray-600">Nome:</span>
                    <p className="text-gray-900">{formData.nome}</p>
                  </div>
                  {formData.nomeSocial && (
                    <div>
                      <span className="font-medium text-gray-600">Nome Social:</span>
                      <p className="text-gray-900">{formData.nomeSocial}</p>
                    </div>
                  )}
                  <div>
                    <span className="font-medium text-gray-600">Email:</span>
                    <p className="text-gray-900">{formData.email}</p>
                  </div>
                  <div>
                    <span className="font-medium text-gray-600">Telefone:</span>
                    <p className="text-gray-900">{formData.telefone}</p>
                  </div>
                  <div>
                    <span className="font-medium text-gray-600">CPF:</span>
                    <p className="text-gray-900">{formData.cpf}</p>
                  </div>
                  <div>
                    <span className="font-medium text-gray-600">Nível:</span>
                    <p className="text-gray-900">{formData.nivel}</p>
                  </div>
                </div>
              </div>

              <div className="bg-gray-50 rounded-lg p-4">
                <h3 className="text-lg font-medium text-gray-900 mb-4">Endereço</h3>
                <div className="text-sm">
                  <p className="text-gray-900">
                    <span className="font-medium text-gray-600">Endereço:</span> {formData.logradouro}, {formData.numero}
                    {formData.complemento && `, ${formData.complemento}`}
                  </p>
                  <p className="text-gray-900 mt-1">
                    <span className="font-medium text-gray-600">Bairro:</span> {formData.bairro}
                  </p>
                  <p className="text-gray-900 mt-1">
                    <span className="font-medium text-gray-600">Cidade:</span> {formData.cidade} - {formData.estado}
                  </p>
                  <p className="text-gray-900 mt-1">
                    <span className="font-medium text-gray-600">CEP:</span> {formData.cep}
                  </p>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between p-6 border-t bg-gray-50">
          <div>
            {currentStep > 1 && (
              <button
                onClick={() => setCurrentStep(currentStep - 1)}
                disabled={loading}
                className="px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors disabled:opacity-50"
              >
                Voltar
              </button>
            )}
          </div>
          
          <div className="flex items-center gap-3">
            <button
              onClick={onClose}
              disabled={loading}
              className="px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors disabled:opacity-50"
            >
              Cancelar
            </button>
            
            {currentStep < 3 ? (
              <button
                onClick={() => setCurrentStep(currentStep + 1)}
                disabled={!isStepValid() || loading}
                className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Próximo
              </button>
            ) : (
              <button
                onClick={handleSubmit}
                disabled={loading}
                className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                {loading && (
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                )}
                {loading ? 'Cadastrando...' : 'Cadastrar Colaborador'}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default CadastroColaboradorModal;