
import React, { useState } from 'react';
import { Fornecedor } from '../types';
import TrashIcon from './icons/TrashIcon';
import PencilIcon from './icons/PencilIcon';
import CheckIcon from './icons/CheckIcon';
import XMarkIcon from './icons/XMarkIcon';

interface GerenciarFornecedoresModalProps {
  fornecedores: Fornecedor[];
  onAdd: (nome: string) => void;
  onDelete: (id: string) => void;
  onEdit: (id: string, newName: string) => void;
  onClose: () => void;
}

const GerenciarFornecedoresModal: React.FC<GerenciarFornecedoresModalProps> = ({ fornecedores, onAdd, onDelete, onEdit, onClose }) => {
  const [newFornecedor, setNewFornecedor] = useState('');
  const [error, setError] = useState('');

  const [editingId, setEditingId] = useState<string | null>(null);
  const [editingName, setEditingName] = useState('');
  const [editError, setEditError] = useState('');

  const handleAddSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const nomeTrimmedUpper = newFornecedor.trim().toUpperCase();

    if (!nomeTrimmedUpper) {
      setError('O nome do fornecedor não pode ser vazio.');
      return;
    }
    if (fornecedores.some(f => f.nome.toUpperCase() === nomeTrimmedUpper)) {
        setError('Este fornecedor já existe.');
        return;
    }

    setError('');
    onAdd(nomeTrimmedUpper);
    setNewFornecedor('');
  };

  const handleEditStart = (fornecedor: Fornecedor) => {
    setEditingId(fornecedor.id);
    setEditingName(fornecedor.nome);
    setEditError('');
  };

  const handleEditCancel = () => {
    setEditingId(null);
    setEditingName('');
    setEditError('');
  };

  const handleEditSave = () => {
    const nameTrimmedUpper = editingName.trim().toUpperCase();

    if (!nameTrimmedUpper) {
        setEditError('O nome não pode ser vazio.');
        return;
    }
    if (fornecedores.some(f => f.id !== editingId && f.nome.toUpperCase() === nameTrimmedUpper)) {
        setEditError('Este fornecedor já existe.');
        return;
    }

    if (editingId) {
        onEdit(editingId, nameTrimmedUpper);
    }
    handleEditCancel();
  };

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-primary-dark border border-primary-medium rounded-2xl shadow-2xl shadow-primary-light/10 w-full max-w-lg p-6 sm:p-8 transform transition-all duration-300 scale-95 animate-fade-in-up flex flex-col max-h-[80vh]">
        <div className="flex justify-between items-center mb-6 flex-shrink-0">
          <h2 className="text-2xl font-bold text-white">Gerenciar Fornecedores</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-white transition-colors text-3xl">&times;</button>
        </div>
        
        <form onSubmit={handleAddSubmit} className="flex gap-2 mb-4 flex-shrink-0">
          <input
            type="text"
            value={newFornecedor}
            onChange={(e) => {
              setNewFornecedor(e.target.value.toUpperCase());
              if(error) setError('');
            }}
            placeholder="NOME DO NOVO FORNECEDOR"
            className={`flex-grow bg-primary-dark/50 border rounded-lg px-3 py-2 text-white focus:ring-2 transition placeholder:text-gray-500 ${
                error ? 'border-red-500 focus:ring-red-500' : 'border-primary-medium focus:ring-primary-light'
            }`}
          />
          <button type="submit" className="px-5 py-2 rounded-lg font-semibold text-primary-dark bg-primary-light hover:bg-opacity-90 transition-colors">
            Adicionar
          </button>
        </form>
        {error && <p className="text-red-400 text-sm -mt-2 mb-4">{error}</p>}
        
        <div className="overflow-y-auto space-y-2 pr-2 -mr-2">
            {fornecedores.length > 0 ? (
                fornecedores.map(f => (
                    <div key={f.id} className="flex justify-between items-center bg-primary-medium/20 p-3 rounded-lg min-h-[52px]">
                        {editingId === f.id ? (
                        <>
                            <div className="flex-grow mr-2">
                                <input
                                    type="text"
                                    value={editingName}
                                    onChange={e => setEditingName(e.target.value.toUpperCase())}
                                    className="w-full bg-primary-dark/80 border border-primary-light rounded-md px-2 py-1 text-white focus:ring-1 focus:ring-primary-light"
                                    autoFocus
                                    onKeyDown={e => {
                                        if (e.key === 'Enter') handleEditSave();
                                        if (e.key === 'Escape') handleEditCancel();
                                    }}
                                />
                                {editError && <p className="text-red-400 text-xs mt-1">{editError}</p>}
                            </div>
                            <div className="flex items-center gap-2">
                                <button onClick={handleEditSave} className="text-green-400 hover:text-green-300 transition-colors" aria-label="Salvar alteração">
                                    <CheckIcon className="w-6 h-6" />
                                </button>
                                <button onClick={handleEditCancel} className="text-gray-400 hover:text-white transition-colors" aria-label="Cancelar edição">
                                    <XMarkIcon className="w-6 h-6" />
                                </button>
                            </div>
                        </>
                    ) : (
                        <>
                            <p className="text-gray-200">{f.nome}</p>
                            <div className="flex items-center gap-3">
                                <button onClick={() => handleEditStart(f)} className="text-primary-light hover:text-opacity-80 transition-colors" aria-label={`Editar ${f.nome}`}>
                                    <PencilIcon className="w-5 h-5" />
                                </button>
                                <button onClick={() => onDelete(f.id)} className="text-red-500 hover:text-red-400 transition-colors" aria-label={`Excluir ${f.nome}`}>
                                    <TrashIcon className="w-5 h-5" />
                                </button>
                            </div>
                        </>
                    )}
                    </div>
                ))
            ) : (
                <p className="text-gray-400 text-center py-4">Nenhum fornecedor cadastrado.</p>
            )}
        </div>

      </div>
    </div>
  );
};

export default GerenciarFornecedoresModal;
