// frontend/src/components/ModalAnadirRam.tsx
import React, { useState, useCallback, useEffect } from 'react';
import styles from './SimpleTable.module.css';
import AutocompleteInput from './AutocompleteInput';
import { memoriaRamService } from '../services/apiService';
import type { MemoriaRam } from '../types/interfaces';

interface Props {
  onClose: () => void;
  onSave: (ram: { slot: string, tamano: number, fabricante?: string, velocidad?: number, partNumber?: string }) => void;
}

const ModalAnadirRam: React.FC<Props> = ({ onClose, onSave }) => {
  const [ram, setRam] = useState({
    slot: '',
    tamano: '',
    fabricante: '',
    velocidad: '',
    partNumber: ''
  });

  const [allRamModules, setAllRamModules] = useState<MemoriaRam[]>([]);

  useEffect(() => {
    memoriaRamService.getAll()
      .then(setAllRamModules)
      .catch(err => console.error("No se pudieron cargar los módulos de RAM", err));
  }, []);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setRam(prev => ({ ...prev, [name]: value }));
  };

  const fetchRamSuggestions = useCallback(async () => {
    return allRamModules.map(r =>
      `${r.fabricante || 'Desconocido'} | ${r.tamano}GB | ${r.velocidad ? r.velocidad + 'MHz' : 'N/A'}`
    );
  }, [allRamModules]);

  useEffect(() => {
    const selectedSuggestion = ram.partNumber;

    const match = allRamModules.find(s =>
      `${s.fabricante || 'Desconocido'} | ${s.tamano}GB | ${s.velocidad ? s.velocidad + 'MHz' : 'N/A'}` === selectedSuggestion
    );

    if (match) {
      setRam(prev => ({
        ...prev,
        fabricante: match.fabricante || '',
        tamano: match.tamano.toString(),
        velocidad: match.velocidad?.toString() || '',
        partNumber: match.partNumber || ''
      }));
    }
  }, [ram.partNumber, allRamModules]);


  const handleSave = () => {
    onSave({
      slot: ram.slot,
      tamano: parseInt(ram.tamano, 10),
      fabricante: ram.fabricante || undefined,
      velocidad: ram.velocidad ? parseInt(ram.velocidad, 10) : undefined,
      partNumber: ram.partNumber || undefined,
    });
  };

  return (
    <div className={`${styles.modalOverlay} ${styles['modalOverlay--nested']}`}>
      <div className={styles.modal}>
        <h3>Añadir Módulo de RAM</h3>

        <label>Slot (Requerido)</label>
        <input type="text" name="slot" value={ram.slot} onChange={handleChange} className={styles.modalInput} placeholder="Ej: DIMM0" />

        <label>Buscar Módulo Existente (Opcional)</label>
        <AutocompleteInput
          mode="static"
          name="partNumber"
          value={ram.partNumber}
          onChange={handleChange}
          className={styles.modalInput}
          fetchSuggestions={fetchRamSuggestions}
          placeholder="Clic para ver todos o escribe para filtrar"
        />

        <label>Tamaño (GB) (Requerido)</label>
        <input type="number" name="tamano" value={ram.tamano} onChange={handleChange} className={styles.modalInput} placeholder="Ej: 8" />

        <label>Fabricante</label>
        <input type="text" name="fabricante" value={ram.fabricante} onChange={handleChange} className={styles.modalInput} />

        <label>Velocidad (MHz)</label>
        <input type="number" name="velocidad" value={ram.velocidad} onChange={handleChange} className={styles.modalInput} />

        <div className={styles.modalActions}>
          <button onClick={handleSave} className={`${styles.btn} ${styles.btnPrimary}`} disabled={!ram.slot || !ram.tamano}>Guardar</button>
          <button onClick={onClose} className={`${styles.btn} ${styles.btnSecondary}`}>Cancelar</button>
        </div>
      </div>
    </div>
  );
};

export default ModalAnadirRam;