import React, { FC, useCallback, useEffect, useState } from 'react';
import {
  ScrollView,
  Text,
  TouchableOpacity,
  View,
  Image,
  StyleSheet,
  Linking,
  useWindowDimensions
} from 'react-native';
import {
  CommonActions,
  NavigationProp,
  useFocusEffect,
  useNavigation
} from '@react-navigation/native';
import RenderHtml, { defaultHTMLElementModels } from 'react-native-render-html';

import { storage, StoreType } from 'src/storage';
import {
  PageWrapper,
  Header,
  Loading,
  Input,
  WarningModal,
  CustomImageViewer
} from 'src/components';
import {
  usePostGetGroupMembersQuery,
  usePostGetGroupSettingsQuery,
  usePostLeaveGroupMutation,
  usePostRemoveGroupFromListMutation,
  usePostSetMuteForGroupMutation
} from '@api/chat';
import { Colors } from 'src/theme';
import { API_HOST } from 'src/constants';
import GroupIcon from 'assets/icons/messages/group-chat.svg';
import { getFontSize } from 'src/utils';
import ExitIcon from 'assets/icons/messages/exit.svg';
import TrashIcon from 'assets/icons/travels-screens/trash-solid.svg';
import BellSlashIcon from 'assets/icons/messages/bell-slash.svg';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import EditIcon from 'assets/icons/travels-screens/pen-to-square.svg';
import UserPlusIcon from 'assets/icons/user-plus.svg';
import { NAVIGATION_PAGES } from 'src/types';
import { SheetManager } from 'react-native-actions-sheet';
import EditGroupModal from '../Components/EditGroupModal';
import { useBottomTabBarHeight } from '@react-navigation/bottom-tabs';
import AddNomadsModal from '../Components/AddNomadsModal';
import UserOptionsModal from '../Components/UserOptionsModal';
import { RankingDropdown } from '../../TravellersScreen/utils/types';
import { FlashList } from '@shopify/flash-list';
import { Profile } from '../Components/Profile';
import { dataRanking } from '../../TravellersScreen/utils';

type Props = {
  navigation: NavigationProp<any>;
  route: any;
};

const GroupSettingScreen: FC<Props> = ({ navigation, route }) => {
  const token = storage.get('token', StoreType.STRING) as string;
  const groupToken = route.params.groupToken;
  const insets = useSafeAreaInsets();
  const tabBarHeight = useBottomTabBarHeight();
  const [canSeeMembers, setCanSeeMembers] = useState(false);
  const { data, refetch } = usePostGetGroupSettingsQuery(token, groupToken, true);
  const { data: members, refetch: refetchMembers } = usePostGetGroupMembersQuery(
    token,
    groupToken,
    canSeeMembers
  );

  const [fullSizeImageVisible, setFullSizeImageVisible] = useState(false);
  const [muted, setMuted] = useState(false);
  const [modalState, setModalState] = useState({
    isWarningVisible: false,
    title: '',
    buttonTitle: '',
    message: '',
    action: () => {}
  });
  const [cacheKey, setCacheKey] = useState(Date.now());
  const { mutateAsync: muteGroup } = usePostSetMuteForGroupMutation();
  const { mutateAsync: leaveGroup } = usePostLeaveGroupMutation();
  const { mutateAsync: removeGroupFromList } = usePostRemoveGroupFromListMutation();

  const [confirmedValueRanking, setConfirmedValueRanking] = useState<RankingDropdown | null>();

  useFocusEffect(
    useCallback(() => {
      navigation.getParent()?.setOptions({
        tabBarStyle: {
          display: 'none'
        }
      });
    }, [token])
  );

  useEffect(() => {
    if (data && data.settings) {
      setCanSeeMembers(data.settings.members_can_see_members === 1 || data.settings.admin === 1);
      setMuted(data.settings.muted === 1);
    }
  }, [data]);

  const handleMute = async () => {
    await muteGroup(
      {
        token,
        value: muted ? 0 : 1,
        group_token: groupToken
      },
      {
        onSuccess: () => {
          setMuted(!muted);
        }
      }
    );
  };

  const handleLeaveGroup = async () => {
    if (!data) return;

    setModalState({
      isWarningVisible: true,
      title: `Leave group ${data.settings.name}`,
      buttonTitle: 'Leave',
      message: `Are you sure you want to leave ${data.settings.name}?`,
      action: async () => {
        await leaveGroup(
          {
            token,
            group_token: groupToken
          },
          {
            onSuccess: () => {
              navigation.navigate(NAVIGATION_PAGES.CHATS_LIST);
            }
          }
        );
      }
    });
  };

  const handleDeleteGroup = async () => {
    if (!data) return;

    setModalState({
      isWarningVisible: true,
      title: `Delete ${data.settings.name}`,
      buttonTitle: 'Delete',
      message: `Are you sure you want to delete this group chat?\nThis action will remove the chat from your history, but it won't affect other participants.`,
      action: async () => {
        await removeGroupFromList(
          {
            token,
            group_token: groupToken
          },
          {
            onSuccess: () => {
              navigation.navigate(NAVIGATION_PAGES.CHATS_LIST);
            }
          }
        );
      }
    });
  };

  const openEditModal = () => {
    if (!data) return;

    SheetManager.show('edit-group-modal', {
      payload: {
        settings: data.settings,
        members: data.settings.admin === 1 ? members?.settings : [],
        token,
        groupToken,
        refetch,
        refetchMembers,
        setCacheKey,
        cacheKey
      } as any
    });
  };

  if (!data) return <Loading />;

  return (
    <PageWrapper>
      <Header
        label={data.settings.name}
        rightElement={
          data.settings.members_can_edit_settings === 1 || data.settings.admin === 1 ? (
            <TouchableOpacity style={{ padding: 6 }} onPress={openEditModal}>
              <EditIcon fill={Colors.DARK_BLUE} width={18} height={18} />
            </TouchableOpacity>
          ) : null
        }
      />
      <ScrollView
        showsVerticalScrollIndicator={false}
        style={{ flex: 1 }}
        contentContainerStyle={{
          paddingBottom: insets.bottom + tabBarHeight,
          justifyContent: 'space-between',
          flexGrow: 1
        }}
      >
        <View style={{ gap: 16 }}>
          <View style={styles.photoContainer}>
            <TouchableOpacity
              style={styles.photoContainer}
              onPress={() => setFullSizeImageVisible(true)}
              disabled={!data.settings.avatar}
            >
              {!data.settings.avatar ? (
                <GroupIcon width={80} height={80} fill={Colors.LIGHT_GRAY} />
              ) : (
                <Image
                  source={{
                    uri: `${API_HOST}${data.settings.avatar}?cacheBust=${cacheKey}`
                  }}
                  style={{
                    width: 80,
                    height: 80,
                    borderRadius: 40,
                    borderWidth: 1,
                    borderColor: Colors.FILL_LIGHT
                  }}
                />
              )}
            </TouchableOpacity>
            <Text style={styles.bigText}>{data.settings.name}</Text>
          </View>

          {data.settings?.description_html ? (
            <View>
              <Text
                style={{
                  color: Colors.DARK_BLUE,
                  fontSize: getFontSize(14),
                  fontFamily: 'redhat-700',
                  marginBottom: 8
                }}
              >
                Description
              </Text>
              <View style={{ borderRadius: 6, backgroundColor: Colors.FILL_LIGHT, padding: 10 }}>
                <WebDisplay html={data.settings.description_html} />
              </View>
            </View>
          ) : data.settings.description ? (
            <Input
              editable={false}
              value={data.settings.description}
              header="Description"
              multiline
              height={58}
            />
          ) : null}

          <View style={{ gap: 8, marginBottom: 16 }}>
            <View
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}
            >
              <Text style={styles.title}>{data.settings?.member_count} nomads</Text>
              {data.settings.members_can_add_new_members === 1 || data.settings.admin === 1 ? (
                <TouchableOpacity
                  style={{ padding: 6, paddingRight: 0 }}
                  onPress={() =>
                    SheetManager.show('add-nomads-modal', {
                      payload: { refetchMembers, groupToken, refetch } as any
                    })
                  }
                >
                  <UserPlusIcon fill={Colors.ORANGE} height={18} width={23} />
                </TouchableOpacity>
              ) : null}
            </View>

            {canSeeMembers && members ? (
              <View>
                <FlashList
                  viewabilityConfig={{
                    waitForInteraction: true,
                    itemVisiblePercentThreshold: 50,
                    minimumViewTime: 1000
                  }}
                  data={
                    data.settings.member_count > 4
                      ? members.settings.slice(0, 4)
                      : (members.settings ?? [])
                  }
                  renderItem={({ item, index }) => (
                    <Profile
                      admin={item.admin}
                      canChangeAdmin={data.settings.admin === 1}
                      groupToken={groupToken}
                      refetch={refetch}
                      refetchMembers={refetchMembers}
                      setIsWarningVisible={setModalState}
                      userId={item.uid}
                      key={index}
                      index={index}
                      first_name={item.ranking_data?.first_name ?? item.name}
                      last_name={item.ranking_data?.last_name ?? ''}
                      avatar={
                        item.ranking_data?.avatar
                          ? '/img/avatars/' + item.ranking_data?.avatar
                          : (item.avatar ?? null)
                      }
                      date_of_birth={item.ranking_data?.age}
                      homebase_flag={'/img/flags_new/' + item.ranking_data?.flag1}
                      homebase2_flag={
                        item.ranking_data?.flag2
                          ? '/img/flags_new/' + item.ranking_data?.flag2
                          : null
                      }
                      score={[
                        item.ranking_data?.score_nm ?? 1,
                        item.ranking_data?.score_un ?? 1,
                        item.ranking_data?.score_unp ?? 1,
                        item.ranking_data?.score_dare,
                        item.ranking_data?.score_tcc,
                        item.ranking_data?.score_deep,
                        item.ranking_data?.score_slow,
                        item.ranking_data?.score_yes,
                        item.ranking_data?.score_kye,
                        item.ranking_data?.score_whs,
                        item.ranking_data?.score_tbt
                      ]}
                      active_score={
                        confirmedValueRanking
                          ? confirmedValueRanking.value - 1
                          : dataRanking[0].value - 1
                      }
                      tbt_score={item.ranking_data?.score_tbt}
                      tbt_rank={item.ranking_data?.rank_tbt}
                      badge_tbt={item.ranking_data?.badge_tbt}
                      badge_1281={item.ranking_data?.badge_1281}
                      badge_un={item.ranking_data?.badge_un}
                      badge_un_25={item.ranking_data?.badge_un_25}
                      badge_un_50={item.ranking_data?.badge_un_50}
                      badge_un_75={item.ranking_data?.badge_un_75}
                      badge_un_100={item.ranking_data?.badge_un_100}
                      badge_un_150={item.ranking_data?.badge_un_150}
                      badge_premium={item.ranking_data?.badge_premium}
                      auth={item.ranking_data?.auth}
                    />
                  )}
                  keyExtractor={(item) => item.uid.toString()}
                  showsVerticalScrollIndicator={false}
                />

                {data.settings.member_count > 4 ? (
                  <TouchableOpacity
                    style={{ padding: 8, alignItems: 'center', paddingTop: 0 }}
                    onPress={() =>
                      navigation.navigate(
                        ...([
                          NAVIGATION_PAGES.MEMBERS_LIST,
                          { groupToken, canChangeAdmin: data.settings.admin === 1 }
                        ] as never)
                      )
                    }
                  >
                    <Text
                      style={{
                        color: Colors.DARK_BLUE,
                        fontSize: getFontSize(12),
                        fontWeight: '700'
                      }}
                    >
                      All nomads...
                    </Text>
                  </TouchableOpacity>
                ) : null}
              </View>
            ) : null}
          </View>
        </View>

        <View style={{ gap: 16 }}>
          <View style={styles.optionsContainer}>
            <TouchableOpacity style={styles.option} onPress={handleMute}>
              <Text style={styles.optionText}>{muted ? 'Unmute' : 'Mute'}</Text>
              <BellSlashIcon fill={Colors.DARK_BLUE} />
            </TouchableOpacity>
          </View>

          <View style={[styles.optionsContainer, { paddingVertical: 0, gap: 0 }]}>
            <TouchableOpacity
              style={[styles.option, styles.dangerOption]}
              onPress={handleLeaveGroup}
            >
              <Text style={[styles.optionText, styles.dangerText]}>Leave group chat</Text>
              <ExitIcon fill={Colors.RED} width={16} />
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.option, styles.dangerOption]}
              onPress={handleDeleteGroup}
            >
              <Text style={[styles.optionText, styles.dangerText]}>Delete group chat</Text>
              <TrashIcon fill={Colors.RED} width={18} height={18} />
            </TouchableOpacity>
          </View>
        </View>
      </ScrollView>

      <WarningModal
        type={'delete'}
        isVisible={modalState.isWarningVisible}
        buttonTitle={modalState.buttonTitle}
        message={modalState.message}
        action={modalState.action}
        onClose={() => setModalState({ ...modalState, isWarningVisible: false })}
        title={modalState.title}
      />
      <CustomImageViewer
        images={[{ uri: `${API_HOST}${data.settings.avatar_full}?cacheBust=${cacheKey}` }]}
        imageIndex={0}
        visible={fullSizeImageVisible}
        onRequestClose={() => setFullSizeImageVisible(false)}
        backgroundColor={Colors.DARK_BLUE}
      />
      <EditGroupModal />
      <AddNomadsModal />
      <UserOptionsModal />
    </PageWrapper>
  );
};

const WebDisplay = React.memo(function WebDisplay({ html }: { html: string }) {
  const { width: windowWidth } = useWindowDimensions();
  const contentWidth = windowWidth * 0.9;

  const navigation = useNavigation();
  const token = storage.get('token', StoreType.STRING) as string;

  const processedHtml = React.useMemo(() => {
    let updatedHtml = html;
    const hrefRegex = /href="((?!http)[^"]+)"/g;

    const normalizePath = (path: string): string => {
      const segments = path.split('/').filter(Boolean);
      const resolved: string[] = [];

      for (const segment of segments) {
        if (segment === '..') resolved.pop();
        else if (segment !== '.') resolved.push(segment);
      }

      return '/' + resolved.join('/');
    };

    updatedHtml = updatedHtml.replace(hrefRegex, (match, rawPath) => {
      const normalizedPath = normalizePath(rawPath);
      const fullUrl = `${API_HOST}${normalizedPath}`;
      if (normalizedPath.includes('shop')) {
        const separator = fullUrl.includes('?') ? '&' : '?';
        return `href="${fullUrl}${separator}token=${encodeURIComponent(token)}"`;
      }
      return `href="${fullUrl}"`;
    });

    return updatedHtml;
  }, [html, token]);

  return (
    <RenderHtml
      contentWidth={contentWidth}
      source={{ html: processedHtml }}
      renderersProps={{
        a: {
          onPress: (_event, href) => {
            if (!href) return;

            const eventMatch = href.match(/event\/([^/?#]+)/);
            if (eventMatch?.[1]) {
              navigation.dispatch(
                CommonActions.reset({
                  index: 1,
                  routes: [
                    {
                      name: 'DrawerApp',
                      state: {
                        routes: [
                          {
                            name: NAVIGATION_PAGES.IN_APP_EVENTS_TAB,
                            state: {
                              routes: [
                                { name: NAVIGATION_PAGES.EVENTS },
                                {
                                  name: NAVIGATION_PAGES.EVENT,
                                  params: { url: eventMatch[1] }
                                }
                              ]
                            }
                          }
                        ]
                      }
                    }
                  ]
                })
              );
              return;
            }

            if (href.includes(`${API_HOST}/map/`)) {
              const lonMatch = href.match(/lon=([0-9.-]+)/);
              const latMatch = href.match(/lat=([0-9.-]+)/);
              if (lonMatch && latMatch) {
                const lon = parseFloat(lonMatch[1]);
                const lat = parseFloat(latMatch[1]);

                navigation.dispatch(
                  CommonActions.reset({
                    index: 1,
                    routes: [
                      {
                        name: 'DrawerApp',
                        state: {
                          routes: [
                            {
                              name: NAVIGATION_PAGES.IN_APP_MAP_TAB,
                              state: {
                                routes: [
                                  { name: NAVIGATION_PAGES.EVENTS },
                                  {
                                    name: NAVIGATION_PAGES.MAP_TAB,
                                    params: { lon, lat }
                                  }
                                ]
                              }
                            }
                          ]
                        }
                      }
                    ]
                  })
                );
                return;
              }
            }

            Linking.openURL(href);
          }
        }
      }}
      tagsStyles={{
        a: {
          color: '#ED9334',
          textDecorationLine: 'none',
          fontWeight: '500'
        }
      }}
      customHTMLElementModels={defaultHTMLElementModels}
    />
  );
});

const styles = StyleSheet.create({
  photoContainer: {
    alignItems: 'center',
    gap: 8
  },
  groupPhoto: {
    width: 80,
    height: 80,
    borderRadius: 40,
    alignItems: 'center',
    justifyContent: 'center'
  },
  bigText: {
    color: Colors.DARK_BLUE,
    fontSize: getFontSize(18),
    fontFamily: 'montserrat-700'
  },
  userItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 8,
    paddingHorizontal: 12,
    backgroundColor: Colors.FILL_LIGHT,
    gap: 8,
    borderRadius: 8
  },
  avatar: {
    width: 36,
    height: 36,
    borderRadius: 18,
    borderWidth: 1,
    borderColor: Colors.LIGHT_GRAY
  },
  userName: {
    color: Colors.DARK_BLUE,
    fontSize: getFontSize(14),
    fontFamily: 'montserrat-700'
  },
  title: {
    color: Colors.DARK_BLUE,
    fontSize: getFontSize(14),
    fontFamily: 'redhat-700'
  },
  optionsContainer: {
    paddingVertical: 10,
    paddingHorizontal: 8,
    gap: 16,
    borderRadius: 8,
    backgroundColor: Colors.FILL_LIGHT
  },
  option: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  optionText: {
    fontSize: getFontSize(12),
    fontWeight: '600',
    color: Colors.DARK_BLUE
  },
  dangerOption: {
    paddingVertical: 10,
    borderBottomWidth: 1,
    borderBlockColor: Colors.WHITE
  },
  dangerText: {
    color: Colors.RED
  }
});

export default GroupSettingScreen;
