import React, { useState, useEffect } from 'react';
import { Models } from 'appwrite';
import { FaturaFormData } from '@/hooks/useFaturas';
import { Plus } from 'lucide-react';

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

const FaturaForm: React.FC<FaturaFormProps> = ({
  onSubmit,
  onCancel,
  initialData,
  loading = false,
}) => {
  const [formData, setFormData] = useState<FaturaFormData>({ 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 ? '🔄 Fatura atualizada com sucesso!' : '🎉 Fatura cadastrada com sucesso!'
      });
      if (!initialData) {
        setFormData({ nome: '' });
      }
      setTimeout(() => setMessage(null), 3000);
    } else {
      setMessage({ type: 'error', text: initialData ? 'Erro ao atualizar fatura' : 'Erro ao cadastrar fatura' });
    }
  };

  const handleChange = (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 Fatura' : <><Plus className="w-5 h-5 inline-block mr-2" /> Nova Fatura</>}
        </h2>
        <p className="text-gray-600">
          {initialData ? 'Atualize os dados da fatura.' : 'Cadastre uma nova fatura 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 da Fatura *
          </label>
          <input
            type="text"
            id="nome"
            name="nome"
            value={formData.nome}
            onChange={handleChange}
            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: Fatura de Janeiro"
          />
        </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 FaturaForm;
