import React, { useState, useEffect } from 'react';
import { Models } from 'appwrite';
import { UsuarioFormData } from '@/hooks/useUsuarios';

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

const UsuarioForm: React.FC<UsuarioFormProps> = ({
  onSubmit,
  onCancel,
  initialData,
  loading = false,
}) => {
  
  
  const [formData, setFormData] = useState<UsuarioFormData>({
    'nome-civil': '',
    'nome-social': '',
    cpf: '',
    'auth-id-appwrite': '',
    enderecos: [],
    empresas: [],
    email: '',
  });
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    if (initialData) {
      setFormData({
        'nome-civil': initialData['nome-civil'] || '',
        'nome-social': initialData['nome-social'] || '',
        cpf: initialData.cpf || '',
        'auth-id-appwrite': initialData['auth-id-appwrite'] || '',
        enderecos: initialData.enderecos || [],
        empresas: initialData.empresas || [],
        email: initialData.email || '',
      });
    } else {
      setFormData({
        'nome-civil': '',
        'nome-social': '',
        cpf: '',
        'auth-id-appwrite': '',
        enderecos: [],
        empresas: [],
        email: '',
      });
    }
  }, [initialData]);

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

    const payload = { ...formData, cpf: formData.cpf.replace(/\D/g, '') };
    const success = await onSubmit(payload);

    if (success) {
      setMessage({
        type: 'success',
        text: initialData ? '🔄 Usuário atualizado com sucesso!' : '🎉 Usuário cadastrado com sucesso!',
      });

      if (!initialData) {
        setFormData({
          'nome-civil': '',
          'nome-social': '',
          cpf: '',
          'auth-id-appwrite': '',
          enderecos: [],
          empresas: [],
          email: '',
        });
      }

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

  const formatCpf = (val: string) => {
    const digits = val.replace(/\D/g, '').slice(0, 11);
    return digits
      .replace(/(\d{3})(\d)/, '$1.$2')
      .replace(/(\d{3})(\d)/, '$1.$2')
      .replace(/(\d{3})(\d{1,2})$/, '$1-$2');
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    const val = name === 'cpf' ? formatCpf(value) : value;
    setFormData(prev => ({ ...prev, [name]: val }));
    if (message) setMessage(null);
  };

  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 Usuário' : ' Novo Usuário'}
        </h2>
        <p className="text-gray-600">
          {initialData ? 'Atualize os dados do usuário.' : 'Cadastre um novo usuário 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="nome-civil" className="block text-sm font-medium text-gray-700 mb-2">
              Nome Civil *
            </label>
            <input
              type="text"
              id="nome-civil"
              name="nome-civil"
              value={formData['nome-civil']}
              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="Digite o nome civil"
            />
          </div>
          <div>
            <label htmlFor="nome-social" className="block text-sm font-medium text-gray-700 mb-2">
              Nome Social *
            </label>
            <input
              type="text"
              id="nome-social"
              name="nome-social"
              value={formData['nome-social']}
              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="Digite o nome social"
            />
          </div>
          <div>
            <label htmlFor="cpf" className="block text-sm font-medium text-gray-700 mb-2">
              CPF *
            </label>
            <input
              type="text"
              id="cpf"
              name="cpf"
              value={formData.cpf}
              onChange={handleInputChange}
              required
              maxLength={11}
              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="Digite o CPF"
            />
          </div>
          <div>
            <label htmlFor="auth-id-appwrite" className="block text-sm font-medium text-gray-700 mb-2">
              Auth ID (Appwrite) *
            </label>
            <input
              type="text"
              id="auth-id-appwrite"
              name="auth-id-appwrite"
              value={formData['auth-id-appwrite']}
              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="ID de autenticação"
            />
          </div>
          <div>
            <label htmlFor="enderecos" className="block text-sm font-medium text-gray-700 mb-2">
              Endereço (ID) *
            </label>
            <input
              type="text"
              id="enderecos"
              name="enderecos"
              value={formData.enderecos}
              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="ID do endereço"
            />
          </div>
          <div>
            <label htmlFor="empresas" className="block text-sm font-medium text-gray-700 mb-2">
              Empresa (ID) *
            </label>
            <input
              type="text"
              id="empresas"
              name="empresas"
              value={formData.empresas}
              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="ID da empresa"
            />
          </div>
          <div>
            <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-2">
              Email *
            </label>
            <input
              type="email"
              id="email"
              name="email"
              value={formData.email}
              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="Digite o email"
            />
          </div>
        </div>

        <div className="flex gap-4">
          <button
            type="submit"
            disabled={loading}
            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 UsuarioForm;
