import React, { useEffect, useState } from 'react';
import { View, Text, Switch, Platform, Linking } from 'react-native';
import * as Notifications from 'expo-notifications';

import { Header, PageWrapper, MenuButton, WarningModal } from '../../../../components';
import { NAVIGATION_PAGES } from '../../../../types';
import { Colors } from '../../../../theme';

import UserPenIcon from '../../../../../assets/icons/user-pen.svg';
import UserPlusIcon from '../../../../../assets/icons/user-plus.svg';
import BellIcon from '../../../../../assets/icons/bell.svg';
import MailIcon from '../../../../../assets/icons/mail.svg';
import FAQIcon from '../../../../../assets/icons/faq.svg';
import DocumentIcon from '../../../../../assets/icons/document.svg';
import ShieldIcon from '../../../../../assets/icons/shield.svg';
import ExitIcon from '../../../../../assets/icons/exit.svg';
import UserXMark from '../../../../../assets/icons/user-xmark.svg';

import type { MenuButtonType } from '../../../../types/components';
import { StoreType, storage } from 'src/storage';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { useDeleteUserMutation } from '@api/app';

const Settings = () => {
  const { mutate: deleteUser } = useDeleteUserMutation();
  const token = storage.get('token', StoreType.STRING) as string;
  const [isSubscribed, setIsSubscribed] = useState(false);
  const [shouldOpenWarningModal, setShouldOpenWarningModal] = useState(false);
  const navigation = useNavigation();
  const [modalInfo, setModalInfo] = useState({
    visible: false,
    type: 'confirm',
    message: '',
    action: () => {}
  });

  const openModal = (type: string, message: string, action: any) => {
    setModalInfo({
      visible: true,
      type,
      message,
      action
    });
  };

  const closeModal = () => {
    setModalInfo({ ...modalInfo, visible: false });
  };

  const buttons: MenuButtonType[] = [
    {
      label: 'Edit Profile',
      icon: <UserPenIcon fill={Colors.DARK_BLUE} width={20} height={20} />,
      buttonFn: (navigation) => {
        navigation.navigate(NAVIGATION_PAGES.EDIT_PERSONAL_INFO);
      }
    },
    // {
    //   label: 'Invite a Friend',
    //   icon: <UserPlusIcon fill={Colors.DARK_BLUE} width={20} height={20} />
    // },
    // {
    //   label: 'Notification',
    //   icon: <BellIcon fill={Colors.DARK_BLUE} width={20} height={20} />
    // },
    {
      label: 'Contact Us',
      icon: <MailIcon fill={Colors.DARK_BLUE} width={20} height={20} />,
      buttonFn: () => Linking.openURL('https://nomadmania.com/contact/')
    },
    // {
    //   label: 'FAQs',
    //   icon: <FAQIcon fill={Colors.DARK_BLUE} width={20} height={20} />
    // },
    {
      label: 'Terms & Conditions',
      icon: <DocumentIcon fill={Colors.DARK_BLUE} width={20} height={20} />,
      buttonFn: () => Linking.openURL('https://nomadmania.com/terms/')
    },
    // {
    //   label: 'Privacy Notice',
    //   icon: <ShieldIcon fill={Colors.DARK_BLUE} width={20} height={20} />
    // },
    {
      label: 'Logout',
      icon: <ExitIcon fill={Colors.RED} width={20} height={20} />,
      red: true,
      buttonFn: () => openModal('confirm', 'Are you sure you want to logout?', handleLogout)
    },
    {
      label: 'Delete account',
      icon: <UserXMark fill={Colors.RED} width={20} height={20} />,
      red: true,
      buttonFn: () =>
        openModal('confirm', 'Are you sure you want to delete your account?', handleDeleteAccount)
    }
  ];

  useEffect(() => {
    const subscribed = (storage.get('subscribed', StoreType.BOOLEAN) as boolean) ?? false;
    setIsSubscribed(subscribed);
  }, []);

  const handleLogout = () => {
    storage.remove('token');
    storage.remove('uid');
    navigation.dispatch(
      CommonActions.reset({
        index: 1,
        routes: [{ name: NAVIGATION_PAGES.WELCOME }]
      })
    );
  };

  const handleDeleteAccount = () => {
    deleteUser({ token }, { onSuccess: handleLogout });
  };

  const handleSubscribe = async () => {
    const token = await registerForPushNotificationsAsync();
    if (token) {
      console.log(token);
      storage.set('subscribed', true);
      setIsSubscribed(true);

      Notifications.addNotificationReceivedListener((notification) => {
        console.log('notification', notification);
      });

      Notifications.addNotificationResponseReceivedListener((response) => {
        const data = response.notification.request.content.data;
        console.log('data', data);
      });
    }
  };

  const toggleSwitch = () => {
    if (isSubscribed) {
      storage.set('subscribed', false);
      storage.remove('deviceToken');
      setIsSubscribed(false);
    } else {
      setModalInfo({
        visible: true,
        type: 'success',
        message:
          'To use this feature we need your permission to access your notifications. If you press OK your system will ask you to confirm permission to receive notifications from NomadMania.',
        action: () => setShouldOpenWarningModal(true)
      });
    }
  };

  async function registerForPushNotificationsAsync() {
    let token;
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      setModalInfo({
        visible: true,
        type: 'success',
        message:
          'NomadMania app needs notification permissions to function properly. Open settings?',
        action: () =>
          Platform.OS === 'ios' ? Linking.openURL('app-settings:') : Linking.openSettings()
      });
      return null;
    }
    token = (await Notifications.getDevicePushTokenAsync()).data;

    if (Platform.OS === 'android') {
      Notifications.setNotificationChannelAsync('default', {
        name: 'default',
        importance: Notifications.AndroidImportance.MAX,
        vibrationPattern: [0, 250, 250, 250],
        lightColor: '#FF231F7C'
      });
    }
    storage.set('deviceToken', token);

    return token;
  }

  return (
    <PageWrapper>
      <Header label={'Settings'} />
      {buttons.map((button, index) => (
        <MenuButton
          key={index}
          label={button.label}
          icon={button.icon}
          red={button.red}
          buttonFn={button.buttonFn}
        />
      ))}
      {/* <View
        style={{
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
          marginTop: 20,
          alignItems: 'center'
        }}
      >
        <Text style={{ color: Colors.DARK_BLUE, fontSize: 16, fontWeight: 'bold' }}>
          Notifications
        </Text>
        <Switch
          trackColor={{ false: Colors.LIGHT_GRAY, true: Colors.DARK_BLUE }}
          thumbColor={Colors.WHITE}
          onValueChange={toggleSwitch}
          value={isSubscribed}
        />
      </View> */}
      <WarningModal
        isVisible={modalInfo.visible}
        onClose={closeModal}
        onModalHide={() => {
          if (shouldOpenWarningModal) {
            setShouldOpenWarningModal(false);
            handleSubscribe();
          }
        }}
        type={modalInfo.type}
        message={modalInfo.message}
        action={() => {
          modalInfo.action();
          closeModal();
        }}
      />
    </PageWrapper>
  );
};

export default Settings;
