import AsyncStorage from '@react-native-community/async-storage';
import React, {useEffect, useLayoutEffect, useRef, useState} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {TouchableOpacity} from 'react-native-gesture-handler';
import {useSelector, useStore} from 'react-redux';
import {PROFILE_CUTOUT_TOP_Y} from '../../constants';
import {RootState} from '../../store/rootreducer';
import {ScreenType} from '../../types';
import {hasSeenBadgeTutorial, normalize} from '../../utils';
import BadgeDetailView from '../common/BadgeDetailView';
import Avatar from './Avatar';
import BadgeTutorial from './BadgeTutorial';
import FriendsCount from './FriendsCount';
import ProfileMoreInfoDrawer from './ProfileMoreInfoDrawer';
import UniversityIcon from './UniversityIcon';

type ProfileHeaderProps = {
  userXId: string | undefined;
  screenType: ScreenType;
  isBlocked: boolean;
  handleBlockUnblock: () => void;
  isPrivate?: boolean;
};

const ProfileHeader: React.FC<ProfileHeaderProps> = ({
  userXId,
  screenType,
  isBlocked,
  handleBlockUnblock,
  isPrivate,
}) => {
  const {
    profile: {name = '', university_class = 2021, university},
    user: {username: userXName = '', userId},
  } = useSelector((state: RootState) =>
    userXId ? state.userX[screenType][userXId] : state.user,
  );

  const {
    user: {username = ''},
  } = useSelector((state: RootState) => state.user);

  const state: RootState = useStore().getState();
  const loggedInUserId = state.user.user.userId;

  const [drawerVisible, setDrawerVisible] = useState(false);
  const [showBadgeView, setBadgeViewVisible] = useState(false);
  const [firstName, lastName] = [...name.split(' ')];

  const containerRef = useRef(null);
  const childRef = useRef(null);
  const [measure, setMeasure] = useState(null);
  const [showBadgeTutorial, setShowBadgeTutorial] = useState(false);

  useEffect(() => {
    const getBadgeTutorialAsync = async () => {
      const res = await AsyncStorage.getItem('hasSeenBadgeTutorial');
      if (res === 'true') {
        setShowBadgeTutorial(false);
      }
    };
    getBadgeTutorialAsync();
  });

  useLayoutEffect(() => {
    setTimeout(() => {
      measureUniversityIcon();
    }, 1000);
  }, []);

  const measureUniversityIcon = async () => {
    const badgeSeen = await hasSeenBadgeTutorial();
    if (!badgeSeen && containerRef.current && childRef.current) {
      childRef?.current?.measureLayout(
        containerRef.current,
        (left, top, width, height) => {
          console.log(left, top, width, height);
          setMeasure({left, top, width, height});
          setShowBadgeTutorial(true);
        },
        (error) => {
          setShowBadgeTutorial(false);
          console.log(error);
        },
      );
    }
  };

  return (
    <View ref={containerRef} style={styles.container}>
      <ProfileMoreInfoDrawer
        isOpen={drawerVisible}
        isBlocked={isBlocked}
        handleBlockUnblock={handleBlockUnblock}
        userXId={userXId}
        userXName={userXName}
        setIsOpen={setDrawerVisible}
      />
      {userId === loggedInUserId && measure && (
        <BadgeTutorial
          uniIconProps={{
            university: university,
            university_class: university_class,
            layout: measure,
          }}
          setShowBadgeTutorial={setShowBadgeTutorial}
        />
      )}
      <View style={styles.row}>
        <Avatar
          style={styles.avatar}
          userXId={userXId}
          screenType={screenType}
        />
        <View style={styles.header}>
          {name.length <= 16 ? (
            <Text style={styles.name}>{name}</Text>
          ) : (
            <View>
              <Text style={styles.name}>{firstName}</Text>
              <Text style={styles.name}>{lastName}</Text>
            </View>
          )}

          <View style={styles.friendsAndUniversity}>
            <FriendsCount screenType={screenType} userXId={userXId} />
            <TouchableOpacity
              onPress={() => {
                if (!isPrivate) {
                  setBadgeViewVisible(true);
                }
              }}>
              <View ref={childRef}>
                {userId === loggedInUserId && showBadgeTutorial === true ? (
                  <View style={styles.emptyContainer} />
                ) : (
                  <UniversityIcon
                    {...{
                      university,
                      university_class,
                      needsShadow: true,
                    }}
                  />
                )}
              </View>
            </TouchableOpacity>
            {showBadgeView && (
              <BadgeDetailView
                isEditable={userXName === username}
                userFullName={name}
                setBadgeViewVisible={setBadgeViewVisible}
              />
            )}
          </View>
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    top: PROFILE_CUTOUT_TOP_Y * 1.02,
    width: '100%',
    position: 'absolute',
  },
  row: {
    flexDirection: 'row',
  },
  header: {
    flexDirection: 'column',
    justifyContent: 'space-evenly',
    alignItems: 'center',
    marginRight: '15%',
    marginLeft: '5%',
    flex: 1,
  },
  avatar: {
    marginLeft: '3%',
    top: '-8%',
  },
  name: {
    fontSize: normalize(17),
    fontWeight: '500',
    alignSelf: 'center',
  },
  friendsAndUniversity: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-evenly',
    width: '100%',
    height: 50,
  },
  emptyContainer: {backgroundColor: 'white', width: 50, height: 50},
});

export default ProfileHeader;
