import React, { useState, useEffect } from 'react';
import {
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  Table,
  Input,
} from 'reactstrap';
import { listInstruments, getInstrumentIcon45, convertClientInstrumentToServer, getInstrumentIcon45_inverted } from '../../helpers/utils';
import { server_to_client_instrument_map, ASSIGNMENT } from '../../helpers/globals';
import { useJamClient } from '../../context/JamClientContext';

const JKSessionInstrumentModal = ({ isOpen, toggle, onSave }) => {
  const jamClient = useJamClient();
  const [selectedInstrumentId, setSelectedInstrumentId] = useState(null);
  const [instruments, setInstruments] = useState([]);

  useEffect(() => {
    const fetchInstrument = async () => {
      if (isOpen) {
        // Get sorted list of instruments
        const instrumentList = listInstruments().sort((a, b) =>
          a.description.localeCompare(b.description)
        );
        setInstruments(instrumentList);

        // Get current instrument from backend (like web project)
        const trackNumber = ASSIGNMENT.TRACK1; // For user's own track
        const clientInstrument = await jamClient.TrackGetInstrument(trackNumber);

        // Map client instrument ID to our instrument list
        if (clientInstrument) {
          setSelectedInstrumentId(clientInstrument);
        }
      }
    };

    fetchInstrument();
  }, [isOpen, jamClient]);

  const handleSave = () => {
    if (selectedInstrumentId !== null) {
      onSave(selectedInstrumentId);
      toggle();
    }
  };

  const handleCancel = () => {
    toggle();
  };

  return (
    <Modal isOpen={isOpen} toggle={handleCancel} modalClassName="theme-modal" contentClassName="border" size="md">
      <ModalHeader toggle={handleCancel} className="bg-light d-flex flex-between-center border-bottom-0">
        Select Instrument
      </ModalHeader>
      <ModalBody style={{ maxHeight: '400px', overflowY: 'auto' }}>
        <Table striped hover className="fs--1">
          <tbody>
            {instruments.map((instrument) => (
              <tr
                key={instrument.id}
                onClick={() => setSelectedInstrumentId(instrument.id)}
                className={selectedInstrumentId === instrument.id ? 'table-active' : ''}
                style={{ cursor: 'pointer' }}
              >
                <td width={8} align='center'>
                  <Input
                    type="radio"
                    name="instrument"
                    value={instrument.id}
                    checked={selectedInstrumentId === instrument.id}
                    onChange={() => setSelectedInstrumentId(instrument.id)}
                    style={{ marginLeft: 3, marginRight: 6 }}
                  />
                </td>
                <td width={32}>
                  <img
                    height="32"
                    width="32"
                    src={getInstrumentIcon45_inverted(convertClientInstrumentToServer(instrument.id))}
                    alt={instrument.description}
                  />
                </td>
                <td>
                  {instrument.description}
                </td>
              </tr>
            ))}
          </tbody>
        </Table>
      </ModalBody>
      <ModalFooter>
        <Button
          variant="outline-info"
          outline
          onClick={handleCancel}>
          Cancel
        </Button>
        <Button color="primary" onClick={handleSave} disabled={selectedInstrumentId === null}>
          Save
        </Button>
      </ModalFooter>
    </Modal>
  );
};

export default JKSessionInstrumentModal;
