import React, { useMemo, useState } from 'react';

import VerticalSplit from '../../components/VerticalSplit';
import { useMeshCoreData } from './MeshCoreContext';
import MeshCorePacketDetailsPane from './MeshCorePacketDetailsPane';
import MeshCorePacketTable from './MeshCorePacketTable';

const MeshCorePacketsView: React.FC = () => {
  const { packets, streamReady } = useMeshCoreData();
  const [selectedHash, setSelectedHash] = useState<string | null>(null);

  const selectedPacket = useMemo(() => {
    if (!selectedHash) {
      return null;
    }
    return packets.find((packet) => packet.hash === selectedHash) ?? null;
  }, [packets, selectedHash]);

  return (
    <VerticalSplit
      ratio="2:1"
      left={(
        <MeshCorePacketTable
          packets={packets}
          selectedHash={selectedHash}
          onSelect={(packet) => setSelectedHash(packet.hash)}
          onClearSelection={() => setSelectedHash(null)}
          streamReady={streamReady}
        />
      )}
      right={(
        <MeshCorePacketDetailsPane
          packet={selectedPacket}
          streamReady={streamReady}
        />
      )}
    />
  );
};

export default MeshCorePacketsView;
