import React, { useState, useEffect } from 'react';
import {
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  Form,
  FormGroup,
  Label,
  Input,
  Spinner,
} from 'reactstrap';
import { useJamClient } from '../../context/JamClientContext';
import JKSessionPluginFoldersModal from './JKSessionPluginFoldersModal';

const JKSessionPluginModal = ({ isOpen, toggle, trackNumber = 1 }) => {
  const jamClient = useJamClient();
  const [selectedPlugin, setSelectedPlugin] = useState('');
  const [availablePlugins, setAvailablePlugins] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [loadingText, setLoadingText] = useState('');
  const [showInfoDialog, setShowInfoDialog] = useState(false);
  const [infoMessage, setInfoMessage] = useState('');
  const [showFoldersModal, setShowFoldersModal] = useState(false);

  useEffect(() => {
    if (isOpen) {
      loadAvailablePlugins();
    }
  }, [isOpen]);

  const loadAvailablePlugins = async () => {
    try {
      setIsLoading(true);

      // Load the audio profile configuration first to restore saved VST assignments
      const profileName = await jamClient.LastUsedProfileName();
      if (profileName) {
        await jamClient.FTUELoadAudioConfiguration(profileName);
      }

      // Always try to load VST assignments from profile after loading profile config
      const isVstLoaded = await jamClient.IsVstLoaded();
      if (!isVstLoaded) {
        await jamClient.VSTLoad();
        // Give the native client time to load the VST
        await new Promise(resolve => setTimeout(resolve, 500));
      }

      const pluginsResponse = await jamClient.VSTListVsts();
      const plugins = pluginsResponse?.vsts || [];
      setAvailablePlugins(plugins);

      // Load current track assignments
      const assignmentsResponse = await jamClient.VSTListTrackAssignments();
      const assignments = assignmentsResponse?.vsts || [];

      const targetTrackIndex = trackNumber - 1;
      const currentAssignment = assignments.find(assignment => assignment.track === targetTrackIndex);

      if (currentAssignment) {
        setSelectedPlugin(currentAssignment.file || '');
      } else {
        setSelectedPlugin('');
      }
    } catch (error) {
      console.error('Failed to load VST plugins:', error);
      setAvailablePlugins([]);
      setSelectedPlugin('');
    } finally {
      setIsLoading(false);
    }
  };

  const handlePluginChange = async (event) => {
    const pluginFile = event.target.value;
    setSelectedPlugin(pluginFile);

    const selectedPluginObj = availablePlugins.find(plugin =>
      plugin.file === pluginFile || plugin.id === pluginFile
    );

    if (pluginFile && selectedPluginObj) {
      try {
        // Establish profile context first
        const profileName = await jamClient.LastUsedProfileName();
        if (profileName) {
          await jamClient.FTUELoadAudioConfiguration(profileName);
        }

        // Set the VST assignment
        await jamClient.VSTSetTrackAssignment(selectedPluginObj, trackNumber - 1);

        // Save the entire profile to persist VST assignment
        // FTUESave(true) persists the profile to disk
        try {
          await jamClient.FTUESave(true);
        } catch (saveError) {
          console.warn('FTUESave failed:', saveError);
        }
      } catch (error) {
        console.error('Failed to assign VST plugin:', error);
      }
    }
  };

  const handleOpenPluginApp = async () => {
    try {
      await jamClient.VSTShowHideGui(true, trackNumber - 1);
    } catch (error) {
      console.error('Failed to open plugin GUI:', error);
    }
  };

  const handleScanPlugins = async () => {
    try {
      setLoadingText('scanning');
      setIsLoading(true);
      await jamClient.VSTScan("window.ConfigureTracksStore.onVstScanComplete");
      setIsLoading(false);
      setLoadingText('');
      loadAvailablePlugins();
      setInfoMessage('Scan completed');
      setShowInfoDialog(true);
    } catch (error) {
      console.error('Failed to scan for plugins:', error);
      setIsLoading(false);
      setLoadingText('');
    }
  };

  const handleManageFolders = () => {
    setShowFoldersModal(true);
  };

  const toggleFoldersModal = () => {
    setShowFoldersModal(!showFoldersModal);
  };

  const handleClearPluginList = async () => {
    if (window.confirm('Are you sure you want to clear the plugin list?')) {
      try {
        setLoadingText('clearing');
        setIsLoading(true);
        await jamClient.VSTClearAll();
        setAvailablePlugins([]);
        setSelectedPlugin('');
        setIsLoading(false);
        setLoadingText('');
        setInfoMessage('Clear completed');
        setShowInfoDialog(true);
      } catch (error) {
        console.error('Failed to clear plugin list:', error);
        setIsLoading(false);
        setLoadingText('');
      }
    }
  };

  const closeInfoDialog = () => {
    setShowInfoDialog(false);
    setInfoMessage('');
  };

  return (
    <>
      <Modal isOpen={isOpen} toggle={toggle} modalClassName="theme-modal" contentClassName="border" size="md">
        <ModalHeader toggle={toggle} className="bg-light d-flex flex-between-center border-bottom-0">
          VST/AU Virtual Instrument
        </ModalHeader>
        <ModalBody>
          <Form>
            <FormGroup>
              <Label for="pluginSelect">VST/AU Plugin:</Label>
              <Input
                type="select"
                id="pluginSelect"
                value={selectedPlugin}
                onChange={handlePluginChange}
                disabled={isLoading}
              >
                <option value="">Select a plugin...</option>
                {availablePlugins.map((plugin, index) => (
                  <option key={index} value={plugin.file || plugin}>
                    {plugin.name || plugin}
                  </option>
                ))}
              </Input>
            </FormGroup>

            <FormGroup className="text-center">
              <Button
                color="primary"
                onClick={handleOpenPluginApp}
                disabled={!selectedPlugin}
              >
                Open Plugin
              </Button>
            </FormGroup>

            <FormGroup>
              <Label>Manage Plugins:</Label>
              <div className="d-flex flex-column">
                <div className="d-flex align-items-center mb-2">
                  <a
                    href="#"
                    onClick={(e) => { e.preventDefault(); handleScanPlugins(); }}
                    style={{ color: '#007bff', textDecoration: 'none' }}
                    disabled={isLoading}
                  >
                    Scan for new or updated plugins
                  </a>
                  {isLoading && loadingText === 'scanning' && (
                    <div className="ml-2 d-flex align-items-center">
                      <Spinner size="sm" className="mr-1" />
                      scanning
                    </div>
                  )}
                </div>
                <a
                  href="#"
                  onClick={(e) => { e.preventDefault(); handleManageFolders(); }}
                  className="mb-2"
                  style={{ color: '#007bff', textDecoration: 'none' }}
                  disabled={isLoading}
                >
                  Manage folders for plugin scans
                </a>
                <div className="d-flex align-items-center mb-2">
                  <a
                    href="#"
                    onClick={(e) => { e.preventDefault(); handleClearPluginList(); }}
                    style={{ color: '#007bff', textDecoration: 'none' }}
                    disabled={isLoading}
                  >
                    Clear plugin list
                  </a>
                  {isLoading && loadingText === 'clearing' && (
                    <div className="ml-2 d-flex align-items-center">
                      <Spinner size="sm" className="mr-1" />
                      clearing
                    </div>
                  )}
                </div>
              </div>
            </FormGroup>
          </Form>
        </ModalBody>
        <ModalFooter>
          <Button color="secondary" onClick={toggle}>
            Close
          </Button>
        </ModalFooter>
      </Modal>

      <Modal isOpen={showInfoDialog} toggle={closeInfoDialog} modalClassName="theme-modal" contentClassName="border" size="sm" centered>
        <ModalBody className="text-center">
          <p>{infoMessage}</p>
          <Button color="primary" onClick={closeInfoDialog}>
            Close
          </Button>
        </ModalBody>
      </Modal>

      <JKSessionPluginFoldersModal
        isOpen={showFoldersModal}
        toggle={toggleFoldersModal}
      />
    </>
  );
};

export default JKSessionPluginModal;
