import {MyScreenContainer} from '@components/MyScreenContainer';
import {Image, ScrollView} from 'react-native';
import {View} from 'react-native';
import Avatar from '@assets/profile.png';
import {MyTitle} from '@components/MyTitle';
import {MyVerticalDivider} from '@components/MyDivider';
import {MyIcon} from '@components/MyIcon';
import {useNavigation} from '@react-navigation/native';
import {ProfileScreenNavigationProp} from '@navigation/tabs/main/ProfileTab';
import {MyIconInput} from '@components/MyInput';
import {useEffect, useLayoutEffect, useState} from 'react';
import {RootScreenNavigationProp} from '@navigation/navigation';
import {useSelector} from 'react-redux';
import {RootState} from '@redux/store';
import {Text} from '@gluestack-ui/themed';
import {MyTouchableOpacity} from '@components/MyTouchableOpacity';
import UserManager from '@user/UserManager';
import MyUserManager from '@user/MyUserManager';
import {apiBackendRequest, makeRequest} from '@helper/request';

function UserAvatar() {
  return (
    <Image
      source={Avatar}
      style={{height: 120, width: 120}}
      borderRadius={100}
    />
  );
}

export function ProfileOverview() {
  const lang = useSelector(
    (state: RootState) => state.appVariables.lang.profile.overview.statistics,
  );
  const user = UserManager.getUserSelector(
    useSelector(
      (state: RootState) => state.appVariables.preferences.selectedAccount,
    ),
  );

  return (
    <MyScreenContainer
      style={{
        flexDirection: 'column',
        alignItems: 'center',
        paddingTop: 10,
      }}>
      <View style={{paddingBottom: 10}}>
        <UserAvatar />
      </View>

      <MyTitle
        text={user.Username.data === undefined ? '' : user.Username.data}
      />

      <View style={{flexDirection: 'row', gap: 12}}>
        <Statistic title={lang.followers} value="0" />
        <MyVerticalDivider />
        <Statistic title={lang.following} value="0" />
        <MyVerticalDivider />
        <Statistic title={lang.visited} value="0" />
      </View>
    </MyScreenContainer>
  );
}

interface StatisticProps {
  value: string;
  title: string;
}

function Statistic({value, title}: StatisticProps) {
  const currentTheme = useSelector(
    (state: RootState) => state.nonSaveVariables.theme.colors,
  );

  return (
    <MyTouchableOpacity>
      <View>
        <Text
          size="2xl"
          bold
          style={{
            color: currentTheme.secondary400,
            textAlign: 'center',
          }}>
          {value}
        </Text>
        <Text
          bold
          size="sm"
          style={{
            color: currentTheme.textLight100,
            textAlign: 'center',
          }}>
          {title}
        </Text>
      </View>
    </MyTouchableOpacity>
  );
}

export function ProfileSettings() {
  const lang = useSelector(
    (state: RootState) => state.appVariables.lang.profile.settings.overview,
  );
  const navigation = useNavigation<ProfileScreenNavigationProp>();
  const rootNavigation = useNavigation<RootScreenNavigationProp>();

  const user = UserManager.getUserSelector(
    useSelector(
      (state: RootState) => state.appVariables.preferences.selectedAccount,
    ),
  );

  /*
  <SettingsItem
    icon="phone-iphone"
    title={lang.accountData.phoneNumber}
    value="+49 1510 21334143"
  />
  */

  return (
    <MyScreenContainer
      scrollView
      style={{
        paddingTop: 10,
      }}>
      <View style={{alignItems: 'center'}}>
        <UserAvatar />
      </View>

      <SettingsItemContainer title={lang.accountData.title}>
        <SettingsItem
          icon="person"
          title={lang.accountData.accountName}
          value={user.AccountName === undefined ? '' : user.AccountName}
        />

        <SettingsItem
          icon="person"
          title={lang.accountData.username}
          value={user.Username.data === undefined ? '' : user.Username.data}
          onPress={() => navigation.navigate('UpdateUsername')}
        />
      </SettingsItemContainer>

      <SettingsItemContainer title={lang.changePassword.title}>
        <SettingsItem
          icon="lock"
          title={lang.changePassword.password}
          value={lang.changePassword.tapToChange}
          onPress={() => navigation.navigate('UpdatePassword')}
        />
      </SettingsItemContainer>

      <SettingsItemContainer title={lang.moreInfo.title}>
        <SettingsItem
          icon="help"
          title={lang.moreInfo.help}
          onPress={() => navigation.navigate('Help')}
        />

        <SettingsItem
          icon="info"
          title={lang.moreInfo.about}
          onPress={() => navigation.navigate('About')}
        />

        <SettingsItem
          icon="logout"
          title={lang.moreInfo.logout}
          onPress={() => {
            makeRequest({
              path: apiBackendRequest.LOGOUT,
              request: {},
              response: {},
            }).catch(reason => {
              console.log('logout failed, err: ', reason);
            });

            MyUserManager.logoutMyUser();
            rootNavigation.navigate('Registration', {screen: 'LoginPreview'});
          }}
        />
      </SettingsItemContainer>
    </MyScreenContainer>
  );
}

interface SettingsItemContainerProps {
  children: React.ReactNode;
  title: string;
}

function SettingsItemContainer({children, title}: SettingsItemContainerProps) {
  const currentTheme = useSelector(
    (state: RootState) => state.nonSaveVariables.theme.colors,
  );

  return (
    <View style={{marginTop: 12}}>
      <Text size="xs">{title}</Text>
      <View
        style={{
          padding: 12,
          borderRadius: 10,
          backgroundColor: currentTheme.backgroundDark300,
          marginTop: 4,
          gap: 16,
        }}>
        {children}
      </View>
    </View>
  );
}

interface SettingsItemProps {
  icon: string;
  title: string;
  value?: string;
  onPress?: () => void;
}

function SettingsItem({icon, title, value, onPress}: SettingsItemProps) {
  return (
    <MyTouchableOpacity
      style={{
        flexDirection: 'row',
        alignItems: 'center',
      }}
      disabled={!onPress}
      onPress={onPress}>
      <View style={{flexDirection: 'row', gap: 12, alignItems: 'center'}}>
        <MyIcon name={icon} size={32} />
        <View>
          {value ? (
            <>
              <Text size="sm">{title}</Text>
              <Text bold>{value}</Text>
            </>
          ) : (
            <Text bold>{title}</Text>
          )}
        </View>
      </View>
    </MyTouchableOpacity>
  );
}

export function UpdateUsername() {
  const lang = useSelector(
    (state: RootState) => state.appVariables.lang.profile.settings,
  );
  const currentTheme = useSelector(
    (state: RootState) => state.nonSaveVariables.theme.colors,
  );
  const navigation = useNavigation<ProfileScreenNavigationProp>();

  // TODO: get username from current logged in user
  const username = 'Max Mustermann';

  const [newUsername, setNewUsername] = useState(username);

  useEffect(() => {
    const changed = username !== newUsername;

    navigation.setOptions({
      headerRight: () =>
        changed ? (
          <MyTouchableOpacity onPress={() => navigation.goBack()}>
            <MyIcon
              name="done"
              size={24}
              color={!changed ? currentTheme.white : currentTheme.textLight100}
            />
          </MyTouchableOpacity>
        ) : (
          <></>
        ),
    });
  }, [navigation, newUsername]);

  return (
    <MyScreenContainer style={{paddingTop: 20}}>
      <MyIconInput
        iconName="person"
        text={lang.changeUsername.username}
        value={newUsername}
        onChangeText={text => {
          setNewUsername(text);
        }}
      />
      <Text color={currentTheme.textLight100} style={{marginTop: 12}}>
        {lang.changeUsername.info}
      </Text>
      <Text color={currentTheme.textLight100}>{lang.changeUsername.info2}</Text>
    </MyScreenContainer>
  );
}

export function UpdatePassword() {
  const lang = useSelector(
    (state: RootState) =>
      state.appVariables.lang.profile.settings.changePassword,
  );
  const currentTheme = useSelector(
    (state: RootState) => state.nonSaveVariables.theme.colors,
  );
  const navigation = useNavigation<RootScreenNavigationProp>();

  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [repeatNewPassword, setRepeatNewPassword] = useState('');

  useEffect(() => {
    const passwordChanged =
      currentPassword.length > 0 &&
      newPassword.length > 0 &&
      repeatNewPassword.length > 0 &&
      newPassword === repeatNewPassword;

    navigation.setOptions({
      headerRight: () =>
        passwordChanged ? (
          <MyTouchableOpacity
            onPress={() =>
              navigation.navigate('Registration', {screen: 'LoginPreview'})
            }>
            <MyIcon name="done" size={24} color={currentTheme.white} />
          </MyTouchableOpacity>
        ) : (
          <></>
        ),
    });
  }, [navigation, currentPassword, newPassword, repeatNewPassword]);

  return (
    <MyScreenContainer style={{paddingTop: 20}} scrollView>
      <View
        style={{
          borderRadius: 10,
          backgroundColor: currentTheme.backgroundDark300,
          marginTop: 4,
        }}>
        <MyIconInput
          iconName="lock"
          text={lang.currentPassword}
          secureTextEntry={true}
          value={currentPassword}
          onChangeText={text => setCurrentPassword(text)}
          disableContainer
        />
        <MyIconInput
          iconName="lock"
          text={lang.newPassword}
          secureTextEntry={true}
          value={newPassword}
          onChangeText={text => setNewPassword(text)}
          disableContainer
        />
        <MyIconInput
          iconName="lock"
          text={lang.repeatNewPassword}
          secureTextEntry={true}
          value={repeatNewPassword}
          onChangeText={text => setRepeatNewPassword(text)}
          disableContainer
        />
      </View>

      <Text color={currentTheme.textLight100} style={{marginTop: 12}}>
        {lang.info}
      </Text>
      <Text color={currentTheme.textLight100}>{lang.info2}</Text>
    </MyScreenContainer>
  );
}
