import React, { useState, useEffect } from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import Select from 'react-select';
import JKTooltip from '../common/JKTooltip';
import PropTypes from 'prop-types';
import { getGenres, getInstruments } from '../../helpers/rest';
import { useForm, Controller, useFormState } from 'react-hook-form';
import { useDispatch } from 'react-redux';
import { fetchPeople } from '../../store/features/peopleSlice';

const JKPeopleSearch = props => {
  const { show, setShow, resetFilter, setResetFilter } = props;
  const [instruments, setInstruments] = useState([]);
  const [genres, setGenres] = useState([]);

  const dispatch = useDispatch();

  const { register, handleSubmit, setValue, control, reset } = useForm({
    defaultValues: {
      latency_good: true,
      latency_fair: true,
      latency_high: false,
      proficiency_beginner: true,
      proficiency_intermediate: true,
      proficiency_expert: true,
      instruments: [],
      joined_within_days: '-1',
      active_within_days: '-1'
    }
  });

  const {isDirty} = useFormState({control});

  const toggle = () => setShow(!show);

  const fetchInstruments = async () => {
    await getInstruments()
      .then(response => {
        if (response.ok) {
          return response.json();
        }
      })
      .then(data => {
        //console.log(data);
        setInstruments(
          data.map(instrument => {
            return {
              value: instrument.id,
              label: instrument.description
            };
          })
        );
      })
      .catch(error => console.log(error));
  };

  const fetchGenres = async () => {
    await getGenres()
      .then(response => {
        if (response.ok) {
          return response.json();
        }
      })
      .then(data => {
        //console.log(data);
        setGenres(
          data.map(genre => {
            return {
              value: genre.id,
              label: genre.description
            };
          })
        );
      })
      .catch(error => {
        console.log(error);
      });
  };

  useEffect(() => {
    if(resetFilter){
      reset()
      setResetFilter(false)
    }
  }, [resetFilter])

  useEffect(() => {
    fetchGenres();
    fetchInstruments();
  }, []);

  const submitForm = event => {
    event.preventDefault();
    handleSubmit(onSubmit)();
    setShow(false);
  };

  const onSubmit = (data) => {
    let genres = []
    let joined_within_days, active_within_days = ''
    
    if(data.genres){
      genres = data.genres.map(genre => genre.value)
    }
    joined_within_days = data.joined_within_days.value;
    active_within_days = data.active_within_days.value;
    
    const updatedData = {...data, genres, joined_within_days, active_within_days}
    
    try {
      dispatch(fetchPeople({data: updatedData, page: 1}))  
    } catch (error) {
      console.log('Error fetching people', error);
    }

  };

  const lastActiveOpts = [
    { value: '', label: 'Any Range' },
    { value: '1', label: 'Within Last 1 Day' },
    { value: '7', label: 'Within Last 7 Days' },
    { value: '30', label: 'Within Last 30 Days' },
    { value: '90', label: 'Within Last 90 Days' }
  ];

  const joinedOpts = [
    { value: '', label: 'Any Range' },
    { value: '1', label: 'Within Last 1 Day' },
    { value: '7', label: 'Within Last 7 Days' },
    { value: '30', label: 'Within Last 30 Days' },
    { value: '90', label: 'Within Last 90 Days' }
  ];

  return (
  
    <Modal isOpen={show} toggle={toggle} className="mw-100 mx-1 mr-1 ml-1 mx-md-5 mr-md-5 ml-md-5 mx-xl-10 mr-xl-10 ml-xl-10" data-testid="modalUpdateSearch">
        <ModalHeader toggle={toggle}>Update Search</ModalHeader>
        <ModalBody>
          <div className="px-4 pb-4">
            <form>
              <div className="row justify-content-start mt-2">
                {/* first column */}
                <div className="col-12 col-md-6 mb-3 mb-md-0">
                  <div className="row justify-content-start">
                    <div className="col-6">
                      <label className="form-label">
                        Latency{' '}
                        <JKTooltip title="Use these checkboxes to search for other musicians by the estimated amount of latency between you and them. Latency is the amount of time it takes for each of your computers to process audio, plus the time it takes for this digital audio to move over the Internet between you." />
                      </label>
                      <div className="form-check">
                        <input
                          {...register('latency_good')}
                          type="checkbox"
                          className="form-check-input"
                          defaultChecked={!isDirty}
                          onChange={e => setValue('latency_good', e.target.checked)}
                        />
                        <label className="form-check-label">Good (less than 40ms)</label>
                      </div>
                      <div className="form-check">
                        <input
                          {...register('latency_fair')}
                          type="checkbox"
                          className="form-check-input"
                          defaultChecked={!isDirty}
                          onChange={e => setValue('latency_fair', e.target.checked)}
                        />
                        <label className="form-check-label">Fair (40-60ms)</label>
                      </div>
                      <div className="form-check">
                        <input
                          {...register('latency_high')}
                          type="checkbox"
                          className="form-check-input"
                          defaultChecked={isDirty}
                          onChange={e => setValue('latency_high', e.target.checked)}
                        />
                        <label className="form-check-label">Poor (more than 60ms)</label>
                      </div>
                    </div>

                    <div className="col-6">
                      <label className="form-label">
                        Skill Level <JKTooltip title="Use these checkboxes to search for other musicians by their skill level." />
                      </label>
                      <div className="form-check">
                        <input
                          {...register('proficiency_beginner')}
                          type="checkbox"
                          className="form-check-input"
                          defaultChecked={!isDirty}
                          onChange={e => setValue('proficiency_beginner', e.target.checked)}
                        />
                        <label className="form-check-label">Beginner</label>
                      </div>
                      <div className="form-check">
                        <input
                          {...register('proficiency_intermediate')}
                          type="checkbox"
                          className="form-check-input"
                          defaultChecked={!isDirty}
                          onChange={e => setValue('proficiency_intermediate', e.target.checked)}
                        />
                        <label className="form-check-label">Intermediate</label>
                      </div>
                      <div className="form-check">
                        <input
                          {...register('proficiency_expert')}
                          type="checkbox"
                          className="form-check-input"
                          defaultChecked={!isDirty}
                          onChange={e => setValue('proficiency_expert', e.target.checked)}
                        />
                        <label className="form-check-label">Expert</label>
                      </div>
                    </div>
                  </div>
                </div>

                {/* second column */}
                <div className="col-12 col-md-6">
                  <label className="form-label" htmlFor="instruments">
                    Instruments{' '}
                    <JKTooltip title="Use these checkboxes to search for other musicians who play particular instruments. If you do not select any instruments, we search for any/all instruments. If you select multiple instruments, we search for musicians who play any of these instruments." />
                  </label>
                  <div className="choices">
                    <Controller
                      name="instruments"
                      control={control}
                      render={({ field }) => (
                        <Select {...field} options={instruments} isMulti closeMenuOnSelect={false} id="selInstruments" />
                      )}
                    />
                  </div>
                  <label className="form-label" htmlFor="genres">
                    Genres{' '}
                    <JKTooltip title="Use these checkboxes to search for other musicians who enjoy playing particular musical genres/styles. If you do not select any genres, we search for any/all genres. If you select multiple genres, we search for musicians who play any of these genres." />
                  </label>
                  <div className="choices">
                  <Controller
                      name="genres"
                      control={control}
                      render={({ field }) => (
                        <Select {...field} options={genres} isMulti closeMenuOnSelect={false} id="selGenres" />
                      )}
                    />
                  </div>
                  <label className="form-label" htmlFor="lastActive">
                    Last Active <JKTooltip title="Use this list to search for other musicians who have been active on JamKazam within a specified time period. More recent activity makes it more likely they will respond if you message or request to connect." />
                  </label>
                  <div className="choices">
                    <Controller
                      name="active_within_days"
                      control={control}
                      render={({ field }) => (
                        <Select {...field } options={lastActiveOpts} id="selLastActive" />
                      )}
                    />
                  </div>
                  <label className="form-label" htmlFor="joined">
                    Joined JamKazam <JKTooltip title="Use this list to search for other musicians based on when they joined JamKazam. This can be useful for finding and connecting with newer users." />
                  </label>
                  <div className="choices">
                    <Controller 
                      name="joined_within_days"
                      control={control}
                      render={({ field}) => (
                        <Select {...field} options={joinedOpts} id="selJoinedWithin" />
                      )}
                    />
                  </div>
                </div>
              </div>
            </form>
          </div>
        </ModalBody>
        <ModalFooter>
          <Button color="outline-primary" onClick={toggle}>
            Cancel
          </Button>{' '}
          <Button color="primary" onClick={submitForm} data-testid="btnSubmitSearch">
            Search
          </Button>
        </ModalFooter>
      </Modal>
    
  );
};

JKPeopleSearch.propTypes = {
  show: PropTypes.bool,
  setShow: PropTypes.func,
  //setPeople: PropTypes.func
};

JKPeopleSearch.defaultProps = {
  show: false
};

export default JKPeopleSearch;
