import React, { useState, useEffect } from 'react';
import { Models } from 'appwrite';
import { CarrinhoFormData } from '@/hooks/useCarrinhos';
import { usuarioService } from '@/services/usuarioService';

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

const CarrinhoForm: React.FC<CarrinhoFormProps> = ({
  onSubmit,
  onCancel,
  initialData,
  loading = false
}) => {
  // Inicializar com valores padrão para evitar problemas de input controlado/não controlado
  const [formData, setFormData] = useState<CarrinhoFormData>({
    usuarios: '',
    itens: [],
    quantidade: []
  });
  const [itemsText, setItemsText] = useState('');
  const [quantText, setQuantText] = useState('');
  const [usuariosList, setUsuariosList] = useState<Models.Document[]>([]);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    if (initialData) {
      const usuarios = (initialData as any).usuarios || '';
      const itens = (initialData as any).itens || [];
      const quantidade = (initialData as any).quantidade || [];
      
      setFormData({
        usuarios,
        itens,
        quantidade
      });
      setItemsText(itens.join('\n'));
      setQuantText(quantidade.join('\n'));
    } else {
      // Resetar para valores padrão
      setFormData({ usuarios: '', itens: [], quantidade: [] });
      setItemsText('');
      setQuantText('');
    }
  }, [initialData]);

  useEffect(() => {
    const loadUsuarios = async () => {
      try {
        const res = await usuarioService.listar(1, 50);
        if (res.success) {
          setUsuariosList(res.documents);
        }
      } catch (error) {
        console.error('Erro ao carregar usuários:', error);
      }
    };
    loadUsuarios();
  }, []);

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

    const itens = itemsText.split('\n').filter(i => i.trim() !== '');
    const quantidade = quantText
      .split('\n')
      .map(q => parseInt(q, 10))
      .filter(q => !isNaN(q));

    const success = await onSubmit({ ...formData, itens, quantidade });

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

      if (!initialData) {
        setFormData({ usuarios: '', itens: [], quantidade: [] });
        setItemsText('');
        setQuantText('');
      }

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

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    if (name === 'itens') {
      setItemsText(value);
    } else if (name === 'quantidade') {
      setQuantText(value);
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
    if (message) setMessage(null);
  };

  return (
    <div className="max-w-2xl mx-auto bg-white p-6 rounded-lg shadow-md">
      <h2 className="text-2xl font-bold mb-6 text-gray-800">
        {initialData ? '✏️ Editar Carrinho' : 'Cadastrar Novo Carrinho'}
      </h2>

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

      <form onSubmit={handleSubmit} className="space-y-6">
        <div>
          <label htmlFor="usuarios" className="block text-sm font-medium text-gray-700 mb-2">
            Usuário *
          </label>
          <select
            id="usuarios"
            name="usuarios"
            value={formData.usuarios} // Sempre controlado
            onChange={handleInputChange}
            required
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">Selecione um usuário</option>
            {usuariosList.map((usuario) => (
              <option key={usuario.$id} value={usuario.$id}>
                {(usuario as any)['nome-civil'] || (usuario as any)['nome-social'] || usuario.$id}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label htmlFor="itens" className="block text-sm font-medium text-gray-700 mb-2">
            Itens (um por linha) *
          </label>
          <textarea
            id="itens"
            name="itens"
            value={itemsText} // Sempre controlado
            onChange={handleInputChange}
            rows={4}
            required
            placeholder="Digite os itens, um por linha"
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>

        <div>
          <label htmlFor="quantidade" className="block text-sm font-medium text-gray-700 mb-2">
            Quantidades (uma por linha, correspondente aos itens) *
          </label>
          <textarea
            id="quantidade"
            name="quantidade"
            value={quantText} // Sempre controlado
            onChange={handleInputChange}
            rows={4}
            required
            placeholder="Digite as quantidades, uma por linha"
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>

        <div className="flex gap-4 pt-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:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center"
          >
            {loading ? (
              <div className="flex items-center justify-center">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                {initialData ? 'Atualizando...' : 'Cadastrando...'}
              </div>
            ) : (
              initialData ? '🔄 Atualizar Carrinho' : 'Cadastrar Carrinho'
            )}
          </button>

          {onCancel && (
            <button
              type="button"
              onClick={onCancel}
              className="px-6 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
            >
              Cancelar
            </button>
          )}
        </div>
      </form>
    </div>
  );
};

export default CarrinhoForm;
