import React, { useState, useEffect, useRef } from 'react';
import { NotaFiscal, NFStatus, UserRole, Fornecedor } from '../types';

interface AddNFFormProps {
  onAdd: (nf: NotaFiscal) => void;
  onClose: () => void;
  fornecedores: Fornecedor[];
  onOpenGerenciarFornecedores: () => void;
}

const AddNFForm: React.FC<AddNFFormProps> = ({ onAdd, onClose, fornecedores, onOpenGerenciarFornecedores }) => {
  const [formData, setFormData] = useState({
    numeroNF: '',
    numeroPedido: '',
    fornecedor: '',
    dataPrevisao: '',
    numeroCTE: '',
    observacao: '',
  });

  const [errors, setErrors] = useState({
    numeroNF: '',
    numeroPedido: '',
    fornecedor: '',
    dataPrevisao: '',
  });

  const [fornecedorSuggestions, setFornecedorSuggestions] = useState<string[]>([]);
  const fornecedorInputRef = useRef<HTMLDivElement>(null);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    
    let processedValue = value;
    if (name === 'numeroPedido') {
        processedValue = value.replace(/\D/g, '').slice(0, 10);
    }

    if (name === 'fornecedor') {
        if (value.trim()) {
            const filtered = fornecedores
                .map(f => f.nome)
                .filter(nome => nome.toLowerCase().includes(value.toLowerCase()));
            setFornecedorSuggestions(filtered);
        } else {
            setFornecedorSuggestions([]);
        }
    }

    setFormData((prev) => ({ ...prev, [name]: processedValue }));
    
    if (errors[name as keyof typeof errors]) {
        setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  const handleSuggestionClick = (suggestion: string) => {
    setFormData(prev => ({ ...prev, fornecedor: suggestion }));
    setFornecedorSuggestions([]);
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
        if (fornecedorInputRef.current && !fornecedorInputRef.current.contains(event.target as Node)) {
            setFornecedorSuggestions([]);
        }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
        document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  
  const validateForm = () => {
    const newErrors = { numeroNF: '', numeroPedido: '', fornecedor: '', dataPrevisao: '' };
    let isValid = true;

    if (!formData.numeroNF.trim()) {
        newErrors.numeroNF = 'Nº da NF é obrigatório.';
        isValid = false;
    }
    if (!formData.fornecedor.trim()) {
        newErrors.fornecedor = 'Fornecedor é obrigatório.';
        isValid = false;
    }
    if (!formData.dataPrevisao) {
        newErrors.dataPrevisao = 'Previsão de Entrega é obrigatória.';
        isValid = false;
    }
    if (!formData.numeroPedido.trim()) {
        newErrors.numeroPedido = 'Nº do Pedido é obrigatório.';
        isValid = false;
    } else if (formData.numeroPedido.length !== 10) {
        newErrors.numeroPedido = 'Nº do Pedido deve conter 10 dígitos.';
        isValid = false;
    }

    setErrors(newErrors);
    return isValid;
  };


  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) {
        return;
    }

    const now = new Date().toISOString();
    const newNF: NotaFiscal = {
      id: crypto.randomUUID(),
      ...formData,
      status: NFStatus.PENDENTE,
      dataEmissao: now.split('T')[0],
      history: [{
        status: NFStatus.PENDENTE,
        date: now,
        user: UserRole.DILIGENCIADOR,
      }],
    };
    onAdd(newNF);
    onClose();
  };

  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">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-white">Adicionar Nova NF</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-white transition-colors text-3xl">&times;</button>
        </div>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <InputField label="Nº da NF *" name="numeroNF" value={formData.numeroNF} onChange={handleChange} error={errors.numeroNF} />
            <InputField label="Nº do Pedido *" name="numeroPedido" value={formData.numeroPedido} onChange={handleChange} error={errors.numeroPedido} maxLength={10} />
          </div>
          <div className="relative" ref={fornecedorInputRef}>
            <div className="flex justify-between items-center mb-1">
                <label htmlFor="fornecedor" className="block text-sm font-medium text-gray-300">Fornecedor *</label>
                <button 
                    type="button" 
                    onClick={onOpenGerenciarFornecedores}
                    className="text-xs font-medium text-primary-light hover:underline transition-all"
                >
                    Gerenciar Fornecedores
                </button>
            </div>
            <input
              id="fornecedor"
              name="fornecedor"
              value={formData.fornecedor}
              onChange={handleChange}
              autoComplete="off"
              className={`w-full bg-primary-dark/50 border rounded-lg px-3 py-2 text-white focus:ring-2 transition ${
                errors.fornecedor
                  ? 'border-red-500 focus:ring-red-500'
                  : 'border-primary-medium focus:ring-primary-light focus:border-primary-light'
              }`}
            />
            {errors.fornecedor && <p className="text-red-400 text-sm mt-1">{errors.fornecedor}</p>}
            {fornecedorSuggestions.length > 0 && (
              <ul className="absolute z-10 w-full bg-primary-medium border border-primary-light rounded-md mt-1 max-h-40 overflow-y-auto shadow-lg">
                {fornecedorSuggestions.map((suggestion, index) => (
                    <li 
                        key={index} 
                        onClick={() => handleSuggestionClick(suggestion)} 
                        className="px-4 py-2 cursor-pointer text-white hover:bg-primary-light hover:text-primary-dark transition-colors duration-150"
                    >
                        {suggestion}
                    </li>
                ))}
              </ul>
            )}
          </div>
          <InputField label="Previsão de Entrega *" name="dataPrevisao" type="date" value={formData.dataPrevisao} onChange={handleChange} error={errors.dataPrevisao} />
          <InputField label="Nº do CT-e (Opcional)" name="numeroCTE" value={formData.numeroCTE} onChange={handleChange} />
          <div>
            <label className="block text-sm font-medium text-gray-300 mb-1">Observação (Opcional)</label>
            <textarea
              name="observacao"
              value={formData.observacao}
              onChange={handleChange}
              rows={3}
              className="w-full bg-primary-dark/50 border border-primary-medium rounded-lg px-3 py-2 text-white focus:ring-2 focus:ring-primary-light focus:border-primary-light transition"
            ></textarea>
          </div>
          <div className="flex justify-end pt-4 space-x-3">
            <button type="button" onClick={onClose} className="px-6 py-2 rounded-full text-white bg-gray-600 hover:bg-gray-500 transition-colors">Cancelar</button>
            <button type="submit" className="px-6 py-2 rounded-full font-semibold text-primary-dark bg-primary-light hover:bg-opacity-90 transition-colors shadow-md shadow-primary-light/20">Salvar</button>
          </div>
        </form>
      </div>
    </div>
  );
};

// Helper component for form fields
interface InputFieldProps {
  label: string;
  name: string;
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  type?: string;
  error?: string;
  maxLength?: number;
  autoComplete?: string;
}

const InputField: React.FC<InputFieldProps> = ({ label, name, value, onChange, type = 'text', error, ...props }) => (
  <div>
    <label htmlFor={name} className="block text-sm font-medium text-gray-300 mb-1">{label}</label>
    <input
      type={type}
      id={name}
      name={name}
      value={value}
      onChange={onChange}
      className={`w-full bg-primary-dark/50 border rounded-lg px-3 py-2 text-white focus:ring-2 transition ${
          error 
          ? 'border-red-500 focus:ring-red-500' 
          : 'border-primary-medium focus:ring-primary-light focus:border-primary-light'
      }`}
      {...props}
    />
    {error && <p className="text-red-400 text-sm mt-1">{error}</p>}
  </div>
);

export default AddNFForm;