import React, { useState, useRef, useEffect } from 'react';
import { Modal, ModalHeader, ModalBody, ModalFooter, Button, Table, Row, Col } from 'reactstrap';
import JKJamTracksAutoComplete from '../jamtracks/JKJamTracksAutoComplete';
import { autocompleteJamTracks, getPurchasedJamTracks } from '../../helpers/rest';

const JKSessionJamTrackModal = ({ isOpen, toggle, onJamTrackSelect }) => {
  const [inputValue, setInputValue] = useState('');
  const [showDropdown, setShowDropdown] = useState(false);
  const [jamTracks, setJamTracks] = useState([]);
  const [selected, setSelected] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(false);
  const page = useRef(1);
  const PER_PAGE = 10;

  // Update input value when selected changes (similar to JKJamTracksFilter)
  useEffect(() => {
    if (selected) {
      const displayValue = selected.type === 'artist' ? selected.original_artist : selected.name;
      setInputValue(displayValue);
    }
  }, [selected]);

  const queryOptions = (selected) => {
    const options = {
      per_page: PER_PAGE,
      page: page.current,
    };

    if (typeof selected === 'string') {
      options.search = selected;
      return options;
    }

    if (selected.type === 'artist') {
      options.artist = selected.original_artist;
    } else {
      options.song = selected.name;
    }

    return options;
  };

  const handleOnSelect = async (selected) => {
    page.current = 1;
    setJamTracks([]);
    setSearchTerm('');
    setSelected(selected);
    setShowDropdown(false); // Hide dropdown after selection
    const params = queryOptions(selected);
    await fetchJamTracks(params);
  };

  const handleOnEnter = async (queryStr) => {
    page.current = 1;
    setJamTracks([]);
    setSelected(null);
    setSearchTerm(queryStr);
    const params = queryOptions(queryStr);
    await fetchJamTracks(params);
  };

  const handleSearch = () => {
    if (inputValue.trim()) {
      handleOnEnter(inputValue.trim());
    }
  };

  const fetchJamTracks = async (options) => {
    try {
      setLoading(true);
      const resp = await getPurchasedJamTracks(options);
      const data = await resp.json();
      setJamTracks(prev => [...prev, ...data.jamtracks]);
      page.current = page.current + 1;
    } catch (error) {
      console.error('Error fetching jam tracks:', error);
    } finally {
      setLoading(false);
    }
  };

  // Load purchased JamTracks when modal opens
  useEffect(() => {
    if (isOpen) {
      loadPurchasedJamTracks();
    } else {
      // Reset state when modal closes
      setJamTracks([]);
      setInputValue('');
      setSelected(null);
      setSearchTerm('');
      page.current = 1;
    }
  }, [isOpen]);

  const loadPurchasedJamTracks = async () => {
    try {
      setLoading(true);
      const resp = await getPurchasedJamTracks({ start: 0, search: '', append: false });
      const data = await resp.json();
      setJamTracks(data.jamtracks || []);
    } catch (error) {
      console.error('Error loading purchased jam tracks:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleShopJamTracks = () => {
    // TODO: Implement shop functionality - could open external link or navigate to shop page
    console.log('Shop JamTracks clicked');
    window.open('/jamtracks', '_blank');
  };

  return (
    <Modal isOpen={isOpen} toggle={toggle} size="lg">
      <ModalHeader toggle={toggle}>Open JamTrack</ModalHeader>
      <ModalBody>
        <Row className="mb-3">
          <Col md={9}>
            <JKJamTracksAutoComplete
              fetchFunc={autocompleteJamTracks}
              onSelect={handleOnSelect}
              onEnter={handleOnEnter}
              showDropdown={showDropdown}
              setShowDropdown={setShowDropdown}
              inputValue={inputValue}
              setInputValue={setInputValue}
              inputPlaceholder="Search for JamTracks..."
            />
          </Col>
          <Col md={3} className="align-items-end">
            <Button color="secondary" outline onClick={handleSearch} className="w-100">
              Search
            </Button>
          </Col>
        </Row>
        <Table bordered striped className="fs-0" >
          <thead className="bg-200 text-900">
            <tr>
              <th>Song</th>
              <th>Original Artist</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan="2" className="text-center">
                  <div className="spinner-border spinner-border-sm" role="status">
                    <span className="sr-only">Loading...</span>
                  </div>
                  <span className="ml-2">Searching...</span>
                </td>
              </tr>
            ) : jamTracks.length > 0 ? (
              jamTracks.map((jamTrack, index) => (
                <tr key={jamTrack.id || index}>
                  <td>
                    <a
                      href="#"
                      onClick={(e) => {
                        e.preventDefault();
                        if (onJamTrackSelect) {
                          onJamTrackSelect(jamTrack);
                        }
                        toggle(); // Close modal after selection
                      }}
                      style={{ color: '#007bff', textDecoration: 'none' }}
                    >
                      {jamTrack.name}
                    </a>
                  </td>
                  <td>{jamTrack.original_artist}</td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan="2" className="text-center text-muted">
                  {searchTerm || selected ? 'No results found. Try a different search.' : 'Search for JamTracks above.'}
                </td>
              </tr>
            )}
          </tbody>
        </Table>
      </ModalBody>
      <ModalFooter>
        <Button color="primary" onClick={handleShopJamTracks}>
          Shop JamTracks
        </Button>
        <Button color="secondary" outline onClick={toggle}>
          Cancel
        </Button>
      </ModalFooter>
    </Modal>
  );
};

export default JKSessionJamTrackModal;
