import React, { useState, useEffect } from 'react';
import { Models } from 'appwrite';
import { EnderecoData } from '@/services/enderecoService';

interface EnderecoFormProps {
  onSubmit: (data: EnderecoData) => Promise<boolean>;
  onCancel?: () => void;
  initialData?: Models.Document | null;
  loading?: boolean;
}

const EnderecoForm: React.FC<EnderecoFormProps> = ({
  onSubmit,
  onCancel,
  initialData,
  loading = false
}) => {
  const [formData, setFormData] = useState<EnderecoData>({
    titulo: '',
    cep: '',
    logradouro: '',
    bairro: '',
    numero: '',
    complemento: '',
    cidade: '',
    estado: '',
    pais: '',
    latitude: 0,
    longitude: 0
  });
  const [cepError, setCepError] = useState<string | null>(null);
  const [lastCepFetched, setLastCepFetched] = useState<string>('');
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    if (initialData) {
      setFormData({
        titulo: initialData.titulo || '',
        cep: initialData.cep || '',
        logradouro: initialData.logradouro || '',
        bairro: initialData.bairro || '',
        numero: initialData.numero || '',
        complemento: initialData.complemento || '',
        cidade: initialData.cidade || '',
        estado: initialData.estado || '',
        pais: initialData.pais || '',
        latitude: Number(initialData.latitude) || 0,
        longitude: Number(initialData.longitude) || 0
      });
    } else {
      setFormData({
        titulo: '',
        cep: '',
        logradouro: '',
        bairro: '',
        numero: '',
        complemento: '',
        cidade: '',
        estado: '',
        pais: '',
        latitude: 0,
        longitude: 0
      });
    }
  }, [initialData]);

  useEffect(() => {
    const digits = formData.cep.replace(/\D/g, '');
    if (digits.length === 8 && digits !== lastCepFetched) {
      const fetchData = async () => {
        try {
          const res = await fetch(
            `https://lernu-backend-dev.rede5.com.br/viacep/${digits}`
          );
          if (!res.ok) {
            throw new Error('CEP inválido');
          }
          const data = await res.json();
          setFormData(prev => ({
            ...prev,
            logradouro: data.logradouro || '',
            bairro: data.bairro || '',
            cidade: data.cidade || '',
            estado: data.estado || ''
          }));
          setLastCepFetched(digits);
          setCepError(null);
        } catch (err) {
          console.error('Erro ao buscar CEP:', err);
          setCepError('CEP não encontrado.');
        }
      };
      fetchData();
    }
  }, [formData.cep, lastCepFetched]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const success = await onSubmit(formData);

    if (success) {
      setMessage({
        type: 'success',
        text: initialData ? '🔄 Endereço atualizado com sucesso!' : '🎉 Endereço cadastrado com sucesso!'
      });

      if (!initialData) {
        setFormData({
          titulo: '',
          cep: '',
          logradouro: '',
          bairro: '',
          numero: '',
          complemento: '',
          cidade: '',
          estado: '',
          pais: '',
          latitude: 0,
          longitude: 0
        });
      }

      setTimeout(() => setMessage(null), 3000);
    } else {
      setMessage({
        type: 'error',
        text: initialData ? 'Erro ao atualizar endereço' : 'Erro ao cadastrar endereço'
      });
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    let newValue = value;

    if (name === 'cep') {
      const digits = value.replace(/\D/g, '').slice(0, 8);
      newValue = digits.length > 5 ? `${digits.slice(0, 5)}-${digits.slice(5)}` : digits;
    }

    setFormData(prev => ({
      ...prev,
      [name]: name === 'latitude' || name === 'longitude' ? Number(newValue) : newValue
    }));

    if (message) setMessage(null);
  };

  const isValid =
    formData.titulo.trim() &&
    formData.cep.trim() &&
    formData.logradouro.trim() &&
    formData.bairro.trim() &&
    formData.numero.trim() &&
    formData.complemento.trim() &&
    formData.cidade.trim() &&
    formData.estado.trim() &&
    formData.pais.trim();

  return (
    <div className="bg-white rounded-lg shadow-md p-6">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-900 mb-2">
          {initialData ? '✏️ Editar Endereço' : ' Novo Endereço'}
        </h2>
        <p className="text-gray-600">
          {initialData ? 'Atualize os dados do endereço.' : 'Cadastre um novo endereço na plataforma SaveInMed.'}
        </p>
      </div>

      {message && (
        <div className={`mb-4 p-4 rounded-md ${
          message.type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'
        }`}>
          {message.text}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label htmlFor="titulo" className="block text-sm font-medium text-gray-700 mb-2">
              Título *
            </label>
            <input
              type="text"
              id="titulo"
              name="titulo"
              value={formData.titulo}
              onChange={handleInputChange}
              required
              disabled={loading}
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
              placeholder="Ex: Matriz"
            />
          </div>
          <div>
            <label htmlFor="cep" className="block text-sm font-medium text-gray-700 mb-2">
              CEP *
            </label>
            <input
              type="text"
              id="cep"
              name="cep"
              value={formData.cep}
              onChange={handleInputChange}
              required
              maxLength={9}
              pattern="\d{5}-\d{3}"
              disabled={loading}
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
            placeholder="00000-000"
          />
          {cepError && (
            <p className="text-red-600 text-sm mt-1">{cepError}</p>
          )}
        </div>
        <div>
          <label htmlFor="logradouro" className="block text-sm font-medium text-gray-700 mb-2">
            Logradouro *
          </label>
          <input
            type="text"
            id="logradouro"
            name="logradouro"
            value={formData.logradouro}
            onChange={handleInputChange}
            required
            disabled={loading}
            className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
            placeholder="Rua"
          />
        </div>
        <div>
          <label htmlFor="bairro" className="block text-sm font-medium text-gray-700 mb-2">
            Bairro *
          </label>
          <input
            type="text"
            id="bairro"
            name="bairro"
            value={formData.bairro}
            onChange={handleInputChange}
            required
            disabled={loading}
            className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
            placeholder="Bairro"
          />
        </div>
        <div>
          <label htmlFor="numero" className="block text-sm font-medium text-gray-700 mb-2">
            Número *
          </label>
            <input
              type="text"
              id="numero"
              name="numero"
              value={formData.numero}
              onChange={handleInputChange}
              required
              disabled={loading}
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
              placeholder="123"
            />
          </div>
          <div>
            <label htmlFor="complemento" className="block text-sm font-medium text-gray-700 mb-2">
              Complemento *
            </label>
            <input
              type="text"
              id="complemento"
              name="complemento"
              value={formData.complemento}
              onChange={handleInputChange}
              required
              disabled={loading}
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
              placeholder="Apto, sala, etc"
            />
          </div>
          <div>
            <label htmlFor="cidade" className="block text-sm font-medium text-gray-700 mb-2">
              Cidade *
            </label>
            <input
              type="text"
              id="cidade"
              name="cidade"
              value={formData.cidade}
              onChange={handleInputChange}
              required
              disabled={loading}
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
              placeholder="Cidade"
            />
          </div>
          <div>
            <label htmlFor="estado" className="block text-sm font-medium text-gray-700 mb-2">
              Estado *
            </label>
            <input
              type="text"
              id="estado"
              name="estado"
              value={formData.estado}
              onChange={handleInputChange}
              required
              disabled={loading}
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
              placeholder="Estado"
            />
          </div>
          <div>
            <label htmlFor="pais" className="block text-sm font-medium text-gray-700 mb-2">
              País *
            </label>
            <input
              type="text"
              id="pais"
              name="pais"
              value={formData.pais}
              onChange={handleInputChange}
              required
              disabled={loading}
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
              placeholder="Brasil"
            />
          </div>
          <div>
            <label htmlFor="latitude" className="block text-sm font-medium text-gray-700 mb-2">
              Latitude *
            </label>
            <input
              type="number"
              id="latitude"
              name="latitude"
              step="any"
              value={formData.latitude}
              onChange={handleInputChange}
              required
              disabled={loading}
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
            />
          </div>
          <div>
            <label htmlFor="longitude" className="block text-sm font-medium text-gray-700 mb-2">
              Longitude *
            </label>
            <input
              type="number"
              id="longitude"
              name="longitude"
              step="any"
              value={formData.longitude}
              onChange={handleInputChange}
              required
              disabled={loading}
              className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
            />
          </div>
        </div>

        <div className="flex gap-4">
          <button
            type="submit"
            disabled={loading || !isValid}
            className="flex-1 bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors cursor-pointer"
          >
            {loading ? '⏳ Processando...' : (initialData ? '🔄 Atualizar' : '➕ Cadastrar')}
          </button>

          {onCancel && (
            <button
              type="button"
              onClick={onCancel}
              disabled={loading}
              className="flex-1 bg-gray-600 text-white py-2 px-4 rounded-md hover:bg-gray-700 focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors cursor-pointer"
            >
              ❌ Cancelar
            </button>
          )}
        </div>
      </form>
    </div>
  );
};

export default EnderecoForm;
