import React, { useState, useEffect } from 'react';
import { LaboratorioFormData } from '@/hooks/useLaboratorios';
import { LaboratorioBff } from '@/services/laboratorioApiService';

interface LaboratorioFormProps {
  onSubmit: (data: LaboratorioFormData) => Promise<boolean>;
  onCancel?: () => void;
  initialData?: LaboratorioBff | null;
  loading?: boolean;
}

const LaboratorioForm: React.FC<LaboratorioFormProps> = ({
  onSubmit,
  onCancel,
  initialData,
  loading = false
}) => {
  const [formData, setFormData] = useState<LaboratorioFormData>({
    nome: ''
  });
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    if (initialData) {
      setFormData({ nome: initialData.nome || '' });
    } else {
      setFormData({ nome: '' });
    }
  }, [initialData]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const success = await onSubmit(formData);
    
    if (success) {
      setMessage({ 
        type: 'success', 
        text: initialData ? '🔄 Laboratório atualizado com sucesso!' : '🎉 Laboratório cadastrado com sucesso!' 
      });
      
      if (!initialData) {
        setFormData({ nome: '' });
      }
      
      setTimeout(() => setMessage(null), 3000);
    } else {
      setMessage({ 
        type: 'error', 
        text: initialData ? 'Erro ao atualizar laboratório' : 'Erro ao cadastrar laboratório' 
      });
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    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 Laboratório' : ' Novo Laboratório'}
        </h2>
        <p className="text-gray-600">
          {initialData ? 'Atualize os dados do laboratório.' : 'Cadastre um novo laborató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>
          <label htmlFor="nome" className="block text-sm font-medium text-gray-700 mb-2">
            Nome do Laboratório *
          </label>
          <input
            type="text"
            id="nome"
            name="nome"
            value={formData.nome}
            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 text-gray-900 bg-white"
            placeholder="Digite o nome do laboratório"
          />
        </div>

        <div className="flex gap-4">
          <button
            type="submit"
            disabled={loading || !formData.nome.trim()}
            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
              ? initialData
                ? 'Atualizando...'
                : 'Criando...'
              : initialData
              ? 'Atualizar'
              : 'Criar Laboratório'}
          </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>

        {loading && (
          <div className="flex items-center justify-center text-sm text-gray-600">
            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
            {initialData ? 'Atualizando laboratório...' : 'Criando laboratório...'}
          </div>
        )}
      </form>
    </div>
  );
};

export default LaboratorioForm;