// src/components/TelegramasView.tsx
import { useState, useEffect } from 'react';
import { getListaTelegramas, getTelegramaPorId, type TelegramaDetalle } from '../services/api';

export const TelegramasView = () => {
  const [listaIds, setListaIds] = useState<string[]>([]);
  const [selectedTelegrama, setSelectedTelegrama] = useState<TelegramaDetalle | null>(null);
  const [loadingList, setLoadingList] = useState(true);
  const [loadingDetail, setLoadingDetail] = useState(false);

  useEffect(() => {
    const loadList = async () => {
      try {
        const ids = await getListaTelegramas();
        setListaIds(ids);
      } catch (error) {
        console.error("Error al cargar lista de telegramas", error);
      } finally {
        setLoadingList(false);
      }
    };
    loadList();
  }, []);

  const handleSelectTelegrama = async (mesaId: string) => {
    try {
        setLoadingDetail(true);
        const detalle = await getTelegramaPorId(mesaId);
        setSelectedTelegrama(detalle);
    } catch (error) {
        console.error(`Error al cargar telegrama ${mesaId}`, error);
    } finally {
        setLoadingDetail(false);
    }
  };

  return (
    <div style={{ display: 'flex', gap: '20px', height: '500px' }}>
      <div style={{ flex: 1, border: '1px solid #ccc', overflowY: 'auto' }}>
        <h4>Telegramas Disponibles</h4>
        {loadingList ? <p>Cargando...</p> : (
            <ul style={{ listStyle: 'none', padding: '10px' }}>
                {listaIds.map(id => (
                    <li key={id} onClick={() => handleSelectTelegrama(id)} style={{ cursor: 'pointer', padding: '5px', borderBottom: '1px solid #eee' }}>
                        Mesa: {id}
                    </li>
                ))}
            </ul>
        )}
      </div>
      <div style={{ flex: 3, border: '1px solid #ccc', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        {loadingDetail ? <p>Cargando telegrama...</p> : 
         selectedTelegrama ? (
            <iframe 
                src={`data:application/pdf;base64,${selectedTelegrama.contenidoBase64}`} 
                width="100%" 
                height="100%" 
                title={selectedTelegrama.id}
            />
         ) : <p>Seleccione un telegrama de la lista para visualizarlo.</p>
        }
      </div>
    </div>
  );
};