"use client";

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

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

interface Colaborador {
  id: string;
  identificador: string;
  nome: string;
  email: string;
  telefone: string;
  nivel: string;
  ativo: boolean;
  "registro-completo": boolean;
  "nome-social"?: string;
  cpf: string;
  enderecos: Endereco[];
  empresasDados: string[];
}

interface EditarColaboradorModalProps {
  colaborador: Colaborador;
  onClose: () => void;
  onSuccess: () => void;
}

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

const EditarColaboradorModal = ({ colaborador, onClose, onSuccess }: EditarColaboradorModalProps) => {
  const [currentTab, setCurrentTab] = useState<'dados' | 'endereco'>('dados');
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<FormData>({
    // Dados pessoais
    nome: colaborador.nome || "",
    email: colaborador.email || "",
    telefone: colaborador.telefone || "",
    cpf: colaborador.cpf || "",
    nomeSocial: colaborador["nome-social"] || "",
    identificador: colaborador.identificador || "",
    nivel: colaborador.nivel || "colaborador",
    ativo: colaborador.ativo,
    
    // Endereço (primeiro endereço se existir)
    titulo: colaborador.enderecos?.[0]?.titulo || "Residencial",
    cep: colaborador.enderecos?.[0]?.cep || "",
    logradouro: colaborador.enderecos?.[0]?.logradouro || "",
    numero: colaborador.enderecos?.[0]?.numero || "",
    complemento: colaborador.enderecos?.[0]?.complemento || "",
    cidade: colaborador.enderecos?.[0]?.cidade || "",
    estado: colaborador.enderecos?.[0]?.estado || "",
    pais: colaborador.enderecos?.[0]?.pais || "Brasil",
    bairro: colaborador.enderecos?.[0]?.bairro || ""
  });

  const handleInputChange = (field: keyof FormData, value: string | boolean) => {
    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);
    }
  };

  // Atualizar endereço
  const atualizarEndereco = async () => {
    if (!colaborador.enderecos?.[0]?.id) return;

    const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL!}/enderecos/${colaborador.enderecos[0].id}`, {
      method: 'PATCH',
      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 atualizar endereço');
    }
  };

  // Atualizar usuário
  const atualizarUsuario = async () => {
    // Criar payload básico
    const payload: any = {
      identificador: formData.email, // Usar email como identificador
      ativo: formData.ativo,
      superadmin: false,
      nome: formData.nome,
      email: formData.email,
      telefone: formData.telefone.replace(/\D/g, ''), // Remover formatação do telefone
      nivel: formData.nivel,
      "registro-completo": false, // Manter consistência com a criação
      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/${colaborador.id}`, {
      method: 'PATCH',
      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 atualizar usuário');
    }

    return await response.json();
  };

  // Submeter formulário
  const handleSubmit = async () => {
    try {
      setLoading(true);

      // 1. Atualizar endereço se existir
      if (colaborador.enderecos?.[0]?.id) {
        await atualizarEndereco();
      }
      
      // 2. Atualizar usuário
      await atualizarUsuario();

      onSuccess();
    } catch (error) {
      console.error('Erro ao atualizar colaborador:', error);
      alert('Erro ao atualizar 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">
              Editar Colaborador
            </h2>
            <p className="text-sm text-gray-600 mt-1">
              {colaborador.nome} - {colaborador.identificador}
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Tabs */}
        <div className="border-b border-gray-200">
          <nav className="flex space-x-8 px-6">
            <button
              onClick={() => setCurrentTab('dados')}
              className={`py-4 px-1 border-b-2 font-medium text-sm ${
                currentTab === 'dados'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              <div className="flex items-center">
                <User className="w-4 h-4 mr-2" />
                Dados Pessoais
              </div>
            </button>
            <button
              onClick={() => setCurrentTab('endereco')}
              className={`py-4 px-1 border-b-2 font-medium text-sm ${
                currentTab === 'endereco'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              <div className="flex items-center">
                <MapPin className="w-4 h-4 mr-2" />
                Endereço
              </div>
            </button>
          </nav>
        </div>

        {/* Content */}
        <div className="p-6">
          {/* Tab: Dados Pessoais */}
          {currentTab === 'dados' && (
            <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">
                    Identificador *
                  </label>
                  <input
                    type="text"
                    value={formData.identificador}
                    onChange={(e) => handleInputChange('identificador', 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="Identificador único"
                  />
                </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>
                    <option value="supervisor">Supervisor</option>
                    <option value="gerente">Gerente</option>
                    <option value="admin">Administrador</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Status *
                  </label>
                  <select
                    value={formData.ativo ? 'ativo' : 'inativo'}
                    onChange={(e) => handleInputChange('ativo', e.target.value === 'ativo')}
                    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="ativo">Ativo</option>
                    <option value="inativo">Inativo</option>
                  </select>
                </div>
              </div>
            </div>
          )}

          {/* Tab: Endereço */}
          {currentTab === 'endereco' && (
            <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>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end p-6 border-t bg-gray-50 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>
          
          <button
            onClick={handleSubmit}
            disabled={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 flex items-center gap-2"
          >
            {loading && (
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
            )}
            <Save className="w-4 h-4" />
            {loading ? 'Salvando...' : 'Salvar Alterações'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default EditarColaboradorModal;