import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  Row,
  Col,
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  Form,
  FormGroup,
  Label,
  Input,
  Alert
} from 'reactstrap';
import { useJamServerContext } from '../../context/JamServerContext';
import useRecordingHelpers from '../../hooks/useRecordingHelpers';
import { AUDIO_STORE_TYPE_MIX_AND_STEMS, AUDIO_STORE_TYPE_MIX_ONLY, RECORD_TYPE_AUDIO, RECORD_TYPE_BOTH } from '../../helpers/globals.js';
import { toast } from 'react-toastify';
import { selectIsRecording, setRecordingStopped } from '../../store/features/sessionUISlice';

const JKSessionRecordingModal = ({ isOpen, toggle }) => {
  const dispatch = useDispatch();
  const { jamClient } = useJamServerContext();
  const recordingHelpers = useRecordingHelpers(jamClient);

  // Form state
  const [recordingType, setRecordingType] = useState(RECORD_TYPE_AUDIO);
  const [audioStoreType, setAudioStoreType] = useState(AUDIO_STORE_TYPE_MIX_AND_STEMS['key']);
  const [recordingName, setRecordingName] = useState('')
  const [audioFormat, setAudioFormat] = useState('')

  const [videoSource, setVideoSource] = useState('webcam-only');
  const [includeChat, setIncludeChat] = useState(false);
  const [availableVideoSources, setAvailableVideoSources] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  // Recording state from Redux (shared across components)
  const isRecording = useSelector(selectIsRecording);
  const isStarting = recordingHelpers.startingRecording;
  const isStopping = recordingHelpers.stoppingRecording;

  // Video source options (matching web project)
  const videoSourceOptions = [
    { key: 'webcam-only', text: 'Record my webcam only' },
    { key: 'webcam-only-2', text: 'Record my 2nd webcam only' },
    { key: 'desktop-only', text: 'Record my computer desktop' },
    { key: 'video-window', text: 'Record session video window' }
  ];

  //On mount get the audio store type from backend and set the radio button accordingly using jamClient.GetAudioRecordingPreference()
  useEffect(() => {
    let ignore = false;

    const fetchAudioStoreType = async () => {
      try {
        if (jamClient) {
          const pref = await jamClient.GetAudioRecordingPreference();
          if (!ignore) {
            if (AUDIO_STORE_TYPE_MIX_AND_STEMS['backendValues'].includes(pref)) {
              setAudioStoreType(AUDIO_STORE_TYPE_MIX_AND_STEMS['key']);
            } else if (AUDIO_STORE_TYPE_MIX_ONLY['backendValues'].includes(pref)) {
              setAudioStoreType(AUDIO_STORE_TYPE_MIX_ONLY['key']);
            }
          }
        }
      } catch (error) {
        if (!ignore) {
          console.error('Error fetching audio store type preference:', error);
        }
      }
    };

    fetchAudioStoreType();

    return () => {
      ignore = true;
    };
  }, [jamClient]);

  // Load available video sources when modal opens
  useEffect(() => {
    let ignore = false;

    const loadSources = async () => {
      if (isOpen && jamClient) {
        try {
          if (jamClient.getOpenVideoSources) {
            const openSources = await jamClient.getOpenVideoSources();
            if (!ignore) {
              console.log('Available video sources:', openSources);

              // Map backend sources to frontend options
              const sources = [];
              if (openSources?.webcam1) sources.push(1); // WebCamRecordActive
              if (openSources?.webcam2) sources.push(3); // WebCam2RecordActive
              if (openSources?.screen_capture) sources.push(4); // DesktopRecordActive
              if (openSources?.session_video) sources.push(2); // ScreenRecordActive

              setAvailableVideoSources(sources);
            }
          }
        } catch (error) {
          if (!ignore) {
            console.error('Error loading video sources:', error);
          }
        }
      }
    };

    loadSources();

    return () => {
      ignore = true;
    };
  }, [isOpen, jamClient]);

  const handleStartStopRecording = async () => {
    setIsLoading(true);
    setError(null);
    try {
      if (isRecording) {
        // Stop recording
        await recordingHelpers.stopRecording();
        dispatch(setRecordingStopped());
      } else {
        // Validate recording name
        if (!recordingName || recordingName.trim() === '') {
          setError('Please enter a recording name.');
          setIsLoading(false);
          return;
        }

        // Start recording
        const recordVideo = recordingType === 'audio-video';
        let recordVideoType = 0; // NoVideoRecordActive

        if (recordVideo) {
          // Map video source selection to backend values
          switch (videoSource) {
            case 'webcam-only':
              recordVideoType = 1; // WebCamRecordActive
              break;
            case 'webcam-only-2':
              recordVideoType = 3; // WebCam2RecordActive
              break;
            case 'desktop-only':
              recordVideoType = 4; // DesktopRecordActive
              break;
            case 'video-window':
              recordVideoType = 2; // ScreenRecordActive
              break;
          }

          // Validate video source availability
          if (!availableVideoSources.includes(recordVideoType)) {
            setError(`Selected video source "${videoSourceOptions.find(opt => opt.key === videoSource)?.text}" is not available.`);
            setIsLoading(false);
            return;
          }
        }

        const recordSettings = {
          recordingType: recordVideo ? RECORD_TYPE_BOTH : RECORD_TYPE_AUDIO,
          recordVideo: recordVideo,
          recordChat: includeChat,
          videoType: recordVideoType
        };

        const recording = await recordingHelpers.startRecording(recordSettings);
        if (!recording) {
          setError('Failed to start recording. Please try again.');
          setIsLoading(false);
          return;
        }
        // Don't update Redux here - wait for native client callback (HandleRecordingStartResult)
        // to confirm recording has actually started before showing "Recording" on toolbar
        setIsLoading(false);
        setRecordingName('');
        setAudioFormat('');
        handleCancel();

      }
    } catch (error) {
      console.error('Recording operation failed:', error);
      setError('Failed to start/stop recording. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

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

  const getRecordingButtonText = () => {
    if (isStarting) return 'Starting Recording...';
    if (isStopping) return 'Stopping Recording...';
    if (isRecording) return 'Stop Recording';
    return 'Start Recording';
  };

  const getRecordingButtonColor = () => {
    if (isRecording) return 'danger';
    return 'success';
  };

  // Filter available video options
  const availableVideoOptions = videoSourceOptions.filter(option => {
    switch (option.key) {
      case 'webcam-only':
        return availableVideoSources.includes(1);
      case 'webcam-only-2':
        return availableVideoSources.includes(3);
      case 'desktop-only':
        return availableVideoSources.includes(4);
      case 'video-window':
        return availableVideoSources.includes(2);
      default:
        return false;
    }
  });

  const onRecordingTypeChange = async (e) => {
    const selectedType = e.target.value;
    setRecordingType(selectedType);

    if (selectedType === RECORD_TYPE_BOTH) {
      const obsAvailable = await jamClient.IsOBSAvailable();
      if (!obsAvailable) {
        //alert("OBS Studio is required for video recording. Please install OBS Studio and try again.");
        toast.warn("OBS Studio is required for video recording. Please install OBS Studio and try again.")
        setRecordingType(RECORD_TYPE_AUDIO);
      }
    }
  };

  const onAudioStoreTypeChange = (e) => {
    const value = e.target.value;
    if (value === AUDIO_STORE_TYPE_MIX_AND_STEMS['key']) {
      jamClient.SetAudioRecordingPreference(AUDIO_STORE_TYPE_MIX_AND_STEMS['backendValues'][0]);
    } else if (value === AUDIO_STORE_TYPE_MIX_ONLY['key']) {
      jamClient.SetAudioRecordingPreference(AUDIO_STORE_TYPE_MIX_ONLY['backendValues'][0]);
    }
    setAudioStoreType(value);
  }

  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">
        Make Recording
      </ModalHeader>
      <ModalBody>
        <div className="recording-start-stop">
          {/* Recording Type Selection */}
          <Form>
            <Row>
              <Col xs="12" md="4" lg="3"><label htmlFor="">Record</label></Col>
              <Col>
                <FormGroup tag="fieldset">
                  <div style={{ display: 'block', minHeight: '1.5rem', paddingLeft: '1.5rem' }}>
                    <Label check>
                      <Input
                        type="radio"
                        name="recordingType"
                        value="audio-only"
                        checked={recordingType === 'audio-only'}
                        onChange={onRecordingTypeChange}
                        disabled={isRecording || isStarting || isStopping}
                      />
                      Audio only
                    </Label>
                  </div>
                  <div style={{ display: 'block', minHeight: '1.5rem', paddingLeft: '1.5rem' }}>
                    <Label check>
                      <Input
                        type="radio"
                        name="recordingType"
                        value="audio-video"
                        checked={recordingType === 'audio-video'}
                        onChange={onRecordingTypeChange}
                        disabled={isRecording || isStarting || isStopping}
                      />
                      Audio and video
                    </Label>
                  </div>
                </FormGroup>
              </Col>
            </Row>
            <Row>
              <Col xs="12" md="4" lg="3"><label htmlFor="">Audio Files</label></Col>
              <Col>
                <FormGroup tag="fieldset">
                  <div style={{ display: 'block', minHeight: '1.5rem', paddingLeft: '1.5rem' }}>
                    <Label check>
                      <Input
                        type="radio"
                        name="audioStoreType"
                        value={AUDIO_STORE_TYPE_MIX_AND_STEMS['key']}
                        checked={AUDIO_STORE_TYPE_MIX_AND_STEMS['key'] === audioStoreType}
                        onChange={onAudioStoreTypeChange}
                        disabled={isRecording || isStarting || isStopping}
                      />
                      Session mix & individual parts (streams)
                    </Label>
                  </div>
                  <div style={{ display: 'block', minHeight: '1.5rem', paddingLeft: '1.5rem' }}>
                    <Label check>
                      <Input
                        type="radio"
                        name="audioStoreType"
                        value={AUDIO_STORE_TYPE_MIX_ONLY['key']}
                        checked={AUDIO_STORE_TYPE_MIX_ONLY['key'] === audioStoreType}
                        onChange={(e) => setAudioStoreType(e.target.value)}
                        disabled={isRecording || isStarting || isStopping}
                      />
                      Session mix only
                    </Label>
                  </div>
                </FormGroup>
              </Col>
            </Row>
            <Row>
              <Col xs="12" md="4" lg="3"><label htmlFor="name">Name</label></Col>
              <Col>
                <Input
                  type="text"
                  name="name"
                  id="name"
                  placeholder="Recording Name"
                  value={recordingName}
                  onChange={(e) => setRecordingName(e.target.value)}
                  disabled={isRecording || isStarting || isStopping}
                />
              </Col>
            </Row>
            <Row className='mt-2'>
              <Col xs="12" md="4" lg="3"><label htmlFor="description">Audio Format</label></Col>
              <Col>
                <Input
                  type="select"
                  name="description"
                  id="description"
                  value={audioFormat}
                  onChange={(e) => setAudioFormat(e.target.value)}
                  disabled={isRecording || isStarting || isStopping}
                >
                  <option value="wav">WAV</option>
                  <option value="mp3">MP3</option>
                  <option value="flac">FLAC</option>
                </Input>
              </Col>
            </Row>
            <Row className='mt-2'>
              <Col xs="12" md="4" lg="3"><label htmlFor="voiceChat">Voice Chat</label></Col>
              <Col>
                <FormGroup tag="fieldset">
                  <div style={{  }}>
                    <Label >
                      <Input
                        type="checkbox"
                        checked={includeChat}
                        onChange={(e) => setIncludeChat(e.target.checked)}
                        disabled={isRecording || isStarting || isStopping}
                        name="includeChat"
                      />
                      Include voice chat in recording
                      </Label>
                  </div>
                </FormGroup>

              </Col>
            </Row>
            <Row className='mt-2'>
              <Col xs="12" md="4" lg="3"><label htmlFor="videoFormat">Video Format</label></Col>
              <Col>
                <Input
                  disabled={recordingType === RECORD_TYPE_AUDIO || isRecording || isStarting || isStopping}
                  type='select'
                  name=""
                >
                  <option value="">MP4</option>
                  <option value="">FLC</option>
                </Input>
              </Col>
            </Row>
          </Form>

          {/* Error Message */}
          {error && (
            <Alert color="danger" className="mt-3">
              {error}
            </Alert>
          )}
        </div>
      </ModalBody>
      <ModalFooter>
        <Button
          color={getRecordingButtonColor()}
          onClick={handleStartStopRecording}
          disabled={isLoading || isStarting || isStopping}
        >
          {getRecordingButtonText()}
        </Button>
        <Button color="secondary" onClick={handleCancel} disabled={isLoading}>
          Close
        </Button>
      </ModalFooter>
    </Modal>
  );
};

export default JKSessionRecordingModal;
