import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { SInfoTitle } from '../../../common/s-components/s-info-title';
import { Touchable } from '../../../common/components/touchable';
import { togglePopup } from '../../../common/utils/swipeable-popup-service';
import { SButtonContainer } from '../../../charts/s-components/s-button-container';
import { SText } from '../../../common/s-components/typography/s-text';
import { SPopupSelectorTitle } from '../../../common/s-components/popup-selector/s-popup-selector-title';
import { SBox } from '../../../common/s-components/layout/s-box';
import { Switch } from '../../../common/components/switch';
import { SFilterLine } from '../../s-components/s-filter-line';
import { SFilterLabel } from '../../s-components/s-filter-label';
import { Checkbox } from '../../../common/components/checkbox';
import { SFilterCheckboxItem } from '../../s-components/s-filter-checkbox-item';
import { NEntityInfinite } from '../../../common/types';
import TEntityConfig = NEntityInfinite.TEntityConfig;
import { PopupPressableRow } from './popup-pressable-row';

type TProps = {
  id: string;
  title: string;
  onSubmit: (config: TEntityConfig) => void;
  config: TEntityConfig;
  renderInfo?: () => any;
};

export const PopupFilter: React.FC<TProps> = props => {
  const { id, title, config, onSubmit, renderInfo } = props;
  const {
    starredTracks,
    starredPlaylistsUpdate,
    selectedChartsUpdates,
  } = config;

  const [playlistUpdateChecked, setPlaylistUpdateChecked] = useState<boolean>(
    Array.isArray(starredTracks) && starredTracks.includes('playlist_update')
  );
  const [chartUpdateChecked, setChartUpdateChecked] = useState<boolean>(
    Array.isArray(starredTracks) && starredTracks.includes('chart_update')
  );
  const [starredTracksChecked, setStarredTracksChecked] = useState<boolean>(
    playlistUpdateChecked || chartUpdateChecked
  );
  const [starredPlaylistsChecked, setStarredPlaylistsChecked] = useState<
    boolean
  >(() => {
    if (typeof starredPlaylistsUpdate === 'boolean') {
      return starredPlaylistsUpdate;
    }
    return false;
  });
  const [selectedChartsChecked, setSelectedChartsChecked] = useState<boolean>(
    () => {
      if (typeof selectedChartsUpdates === 'boolean') {
        return selectedChartsUpdates;
      }
      return false;
    }
  );

  useEffect(() => {
    setStarredTracksChecked(playlistUpdateChecked || chartUpdateChecked);
  }, [playlistUpdateChecked, chartUpdateChecked]);

  const handleStarredTracksChange = () => {
    const currentStarredTracksValue = starredTracksChecked;
    setStarredTracksChecked(prevState => !prevState);
    setPlaylistUpdateChecked(!currentStarredTracksValue);
    setChartUpdateChecked(!currentStarredTracksValue);
  };

  const handlePlaylistUpdateChecked = useCallback(() => {
    setPlaylistUpdateChecked(prevState => !prevState);
  }, []);

  const handleChartUpdateChecked = useCallback(() => {
    setChartUpdateChecked(prevState => !prevState);
  }, []);

  const playlistCheckbox = useMemo(
    () => (
      <SFilterCheckboxItem ml={24}>
        <SBox mt={1}>
          <Checkbox
            disabled={!starredTracksChecked}
            onPress={handlePlaylistUpdateChecked}
            checked={playlistUpdateChecked}
            isLight
          />
        </SBox>
        <SFilterLabel disabled={!starredTracksChecked} pl={16}>
          Playlist Related Updates
        </SFilterLabel>
      </SFilterCheckboxItem>
    ),
    [playlistUpdateChecked, starredTracksChecked]
  );

  const chartCheckbox = useMemo(
    () => (
      <SFilterCheckboxItem pl={24}>
        <Checkbox
          disabled={!starredTracksChecked}
          onPress={handleChartUpdateChecked}
          checked={chartUpdateChecked}
          isLight
        />
        <SFilterLabel disabled={!starredTracksChecked} pl={16}>
          Chart Related Updates
        </SFilterLabel>
      </SFilterCheckboxItem>
    ),
    [chartUpdateChecked, starredTracksChecked]
  );

  const handleDone = () => {
    const updatedStarredTracks = [];
    if (chartUpdateChecked) {
      updatedStarredTracks.push('chart_update');
    }
    if (playlistUpdateChecked) {
      updatedStarredTracks.push('playlist_update');
    }

    const updatedConfig = {
      ...config,
      starredTracks: updatedStarredTracks,
      starredPlaylistsUpdate: starredPlaylistsChecked,
      selectedChartsUpdates: selectedChartsChecked,
    };

    onSubmit(updatedConfig);
  };

  const [pressedDone, setPressedDone] = useState(false);
  const isBtnDisabled =
    !starredTracksChecked && !starredPlaylistsChecked && !selectedChartsChecked;
  const btnColor = isBtnDisabled
    ? 'columbiaBlue'
    : pressedDone
    ? 'malibu2'
    : 'azureRadiance';

  return (
    <SBox px={16} pb={12} pt={2}>
      <SPopupSelectorTitle>
        <SInfoTitle mt={8}>{title}</SInfoTitle>
        <Touchable
          testID="popup-filter"
          onPress={() => {
            if (isBtnDisabled) return;

            handleDone();
            togglePopup(id);
          }}
          onPressIn={() => {
            setPressedDone(true);
          }}
          onPressOut={() => {
            setPressedDone(false);
          }}
        >
          <SButtonContainer>
            <SText semibold color={btnColor}>
              Done
            </SText>
          </SButtonContainer>
        </Touchable>
      </SPopupSelectorTitle>
      {renderInfo ? renderInfo() : null}
      <>
        <SFilterLine>
          <SFilterLabel>Starred Tracks</SFilterLabel>
          <Switch
            checked={starredTracksChecked}
            onChange={handleStarredTracksChange}
            isLight
          />
        </SFilterLine>
        <PopupPressableRow onPress={handlePlaylistUpdateChecked}>
          {playlistCheckbox}
        </PopupPressableRow>
        <PopupPressableRow onPress={handleChartUpdateChecked}>
          {chartCheckbox}
        </PopupPressableRow>
      </>
      <SFilterLine>
        <SFilterLabel>Starred Playlists Updates</SFilterLabel>
        <Switch
          checked={starredPlaylistsChecked}
          onChange={() => setStarredPlaylistsChecked(prevState => !prevState)}
          isLight
        />
      </SFilterLine>
      <SFilterLine>
        <SFilterLabel>Selected Charts Updates</SFilterLabel>
        <Switch
          checked={selectedChartsChecked}
          onChange={() => setSelectedChartsChecked(prevState => !prevState)}
          isLight
        />
      </SFilterLine>
    </SBox>
  );
};
