import React, { useCallback } from 'react';
import { Platform } from 'react-native';
import { SBox } from '../../common/s-components/layout/s-box';
import { Button } from '../../common/components/button';
import { ROUTES } from '../../app/constants';
import { TNotificationCategory, TNotificationConfig } from '../types';
import { fp as _ } from '../../common/utils/fp';
import { RefreshableView } from '../../common/components/refreshable-view';
import {
  onCategorySettingsToggle,
  // onDspSettingsToggle,
  onGlobalSettingsToggle,
  onNotificationSettingsReset,
} from '../../analytics';
import { NOTIFICATION_SETTINGS_ACTIONS, SECTION_VARIANT } from '../constants';
import { useNotificationSettings } from '../hooks/useNotificationSettings';
import { Section } from './section';
import { SH6 } from '../../common/s-components/typography/s-h6';
import { addSafeArea } from '../../common/transducers/transducers.device-dimension';
import { TRefreshableRenderer } from '../../common/types';
import { Header } from './header';
import { ViewNetworkFailed } from '../../common/components/view-network-failed';
import { ViewLoadFailed } from '../../common/components/view-load-failed';

type TProps = {};

const maxHeight = addSafeArea(60);
const isIOS = Platform.OS === 'ios';

export const NotificationsSettings: React.FC<TProps> = () => {
  const {
    entity,
    updateNotificationSettings,
    visibility,
    refresh,
  } = useNotificationSettings();

  const renderHeader: TRefreshableRenderer = ({ animationY, scrollToTop }) => {
    return <Header animationY={animationY} scrollToTop={scrollToTop} />;
  };

  const renderBody = useCallback(() => {
    const entityData = _.path('data', entity);
    const defaultSettings = _.path('data.default', entity);
    const settings = _.path(['data', 'data'], entity) as TNotificationConfig;
    const starredTracksChecked =
      _.path(['categories', 'starred_tracks', 'spotify'], settings) ||
      _.path(['categories', 'starred_tracks', 'apple'], settings);
    const starredTracksValue = _.path(
      ['categories', 'starred_tracks'],
      settings
    ) as TNotificationCategory;
    const starredPlaylistsChecked =
      _.path(['categories', 'starred_playlists', 'spotify'], settings) ||
      _.path(['categories', 'starred_playlists', 'apple'], settings);
    const starredPlaylistsValue = _.path(
      ['categories', 'starred_playlists'],
      settings
    );
    const starredChartsChecked =
      _.path(['categories', 'charts', 'spotify'], settings) ||
      _.path(['categories', 'charts', 'apple'], settings);
    const starredChartsValue = _.path(['categories', 'charts'], settings);

    const verticalOffsetOffline = isIOS ? 66 : -30;
    const verticalOffsetError = isIOS ? 64 : 30;

    return (
      <SBox position="relative" pt={maxHeight + 28} pb={70} flex={1}>
        {visibility.error && (
          <ViewLoadFailed
            variant="notification-settings"
            verticalOffset={verticalOffsetError}
          />
        )}

        {visibility.offline && (
          <ViewNetworkFailed verticalOffset={verticalOffsetOffline} />
        )}

        {visibility.data || entityData ? (
          <Section
            variant={SECTION_VARIANT.market}
            label="Notifications"
            checked={_.path(['notifications'], settings)}
            value={_.path(['markets'], settings)}
            onChange={(value: boolean) => {
              onGlobalSettingsToggle({
                global_toggler_updated_state: value ? 'On' : 'Off',
              });
              updateNotificationSettings(value, ['notifications']);
            }}
            renderDropdown={() => {
              return (
                <>
                  <SBox px={16} pt={23} pb={22}>
                    <SH6 textAlign="left">Categories</SH6>
                  </SBox>

                  <Section
                    variant={SECTION_VARIANT.starredTracks}
                    label="Starred Tracks"
                    checked={starredTracksChecked}
                    value={starredTracksValue}
                    onChange={(value: boolean) => {
                      onCategorySettingsToggle({
                        category_name: 'Starred tracks',
                        category_status_set: value ? 'On' : 'Off',
                      });
                      updateNotificationSettings(
                        {
                          spotify: value,
                          apple: value,
                        },
                        ['categories', 'starred_tracks']
                      );
                    }}
                    renderDropdown={() => {}}
                    description="Enable notifications for up-to-date starred tracks movement within charts and playlists"
                  />

                  <Section
                    variant={SECTION_VARIANT.starredPlaylists}
                    label="Starred Playlists"
                    checked={starredPlaylistsChecked}
                    value={starredPlaylistsValue}
                    onChange={(value: boolean) => {
                      onCategorySettingsToggle({
                        category_name: 'Starred playlists',
                        category_status_set: value ? 'On' : 'Off',
                      });
                      updateNotificationSettings(
                        {
                          spotify: value,
                          apple: value,
                        },
                        ['categories', 'starred_playlists']
                      );
                    }}
                    renderDropdown={() => {}}
                    description="Enable notifications to be alerted on all Starred Playlists updates."
                  />

                  <Section
                    variant={SECTION_VARIANT.starredCharts}
                    label="Charts"
                    checked={starredChartsChecked}
                    value={starredChartsValue}
                    onChange={(value: boolean) => {
                      onCategorySettingsToggle({
                        category_name: 'Charts',
                        category_status_set: value ? 'On' : 'Off',
                      });
                      updateNotificationSettings(
                        {
                          spotify: value,
                          apple: value,
                        },
                        ['categories', 'charts']
                      );
                    }}
                    renderDropdown={() => {}}
                    description="Enable notifications to be alerted on the selected Charts updates."
                  />

                  <SBox alignSelf="center">
                    <Button
                      disabled={_.isEqual(settings, defaultSettings)}
                      onPress={() => {
                        updateNotificationSettings(
                          null,
                          NOTIFICATION_SETTINGS_ACTIONS.reset
                        );
                        onNotificationSettingsReset();
                      }}
                      variant="request-2"
                      width={140}
                    >
                      Reset
                    </Button>
                  </SBox>
                </>
              );
            }}
          />
        ) : null}
      </SBox>
    );
  }, [entity, updateNotificationSettings]);

  return (
    <RefreshableView
      enableScroll={false}
      testID="notificationssettings-refreshable-view"
      renderHeader={renderHeader}
      renderBody={renderBody}
      name={ROUTES.notificationsettings}
      loading={visibility.refresh}
      onPullDown={() => refresh()}
      indicatorOffsetTop={maxHeight}
      withoutBottomTabNavigator
      withNativeDriver
    />
  );
};
