import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, Image, ActivityIndicator, ScrollView } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { Colors } from 'src/theme';
import { Input } from 'src/components';
import { storage, StoreType } from 'src/storage';
import { PostCreateGroup, usePostCreateGroupMutation } from '@api/chat';
import { API_HOST } from 'src/constants';
import { AvatarWithInitials } from 'src/components';
import * as ImagePicker from 'expo-image-picker';
import * as yup from 'yup';
import Checkbox from 'expo-checkbox';

import { FlashList } from '@shopify/flash-list';
import { useSheetRouter } from 'react-native-actions-sheet';

import CloseIcon from 'assets/icons/close.svg';
import CameraIcon from 'assets/icons/messages/camera.svg';
import { Formik } from 'formik';
import { useGroupChatStore } from 'src/stores/groupChatStore';
import { NAVIGATION_PAGES } from 'src/types';
import { chatStyles as styles } from './styles';

const ProfileSchema = yup.object({
  name: yup
    .string()
    .required('name is required')
    .min(3, 'group name should be at least 3 characters'),
  description: yup.string().optional().max(8000, 'description should not exceed 8000 characters'),
  users: yup.array().min(1, 'select at least 1 member').required('members are required')
});

const RouteAddGroup = () => {
  const router = useSheetRouter('search-modal');
  const token = storage.get('token', StoreType.STRING) as string;
  const navigation = useNavigation();

  const {
    selectedUsers,
    removeUser,
    image,
    setImage,
    groupName,
    setGroupName,
    description,
    setDescription,
    canEdit,
    canSend,
    canAdd,
    setCanEdit,
    setCanSend,
    setCanAdd
  } = useGroupChatStore();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const { mutate: createGroup } = usePostCreateGroupMutation();

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1
    });

    if (!result.canceled) {
      setImage(result.assets[0]);
    }
  };

  const renderUserItem = ({ item }: { item: any }) => {
    return (
      <View style={styles.selectedUserContainer}>
        <View style={styles.userContainer}>
          <TouchableOpacity onPress={() => removeUser(item.user_id)} style={styles.removeIcon}>
            <CloseIcon width={10} height={10} fill={Colors.WHITE} />
          </TouchableOpacity>
          {item.avatar ? (
            <Image source={{ uri: API_HOST + item.avatar }} style={styles.selectedAvatar} />
          ) : (
            <AvatarWithInitials
              text={`${item.first_name[0] ?? ''}${item.last_name[0] ?? ''}`}
              flag={API_HOST + item.flag1}
              size={60}
              fontSize={21}
              borderColor={Colors.LIGHT_GRAY}
              borderWidth={1}
            />
          )}
        </View>
      </View>
    );
  };

  return (
    <Formik
      validationSchema={ProfileSchema}
      initialValues={{
        name: groupName,
        description,
        users: selectedUsers
      }}
      onSubmit={async (values) => {
        setIsSubmitting(true);
        const groupData: PostCreateGroup = {
          token,
          name: values.name,
          description: values.description,
          users: selectedUsers.map((user) => +user.user_id),
          admins: [],
          members_can_edit_settings: canEdit ? 1 : 0,
          members_can_send_messages: canSend ? 1 : 0,
          members_can_add_new_members: canAdd ? 1 : 0
        };

        if (image && image.uri) {
          groupData.group_avatar = {
            type: image.type || 'image',
            uri: image.uri,
            name: image.uri.split('/').pop()!
          };
        }

        await createGroup(groupData, {
          onSuccess: (res) => {
            setIsSubmitting(false);
            navigation.navigate(
              ...([
                NAVIGATION_PAGES.GROUP_CHAT,
                {
                  group_token: res.groupToken,
                  name: values.name,
                  avatar: res.groupAvatar,
                  userType: 'normal'
                }
              ] as never)
            );
            router?.close();
          },
          onError: () => {
            setIsSubmitting(false);
          }
        });
      }}
    >
      {(props) => {
        useEffect(() => {
          props.setFieldValue('users', selectedUsers);
        }, [selectedUsers]);

        return (
          <View style={styles.container}>
            <View style={styles.header}>
              <TouchableOpacity
                onPress={() => {
                  router?.goBack();
                }}
                style={{
                  paddingTop: 16,
                  paddingBottom: 6,
                  paddingHorizontal: 6
                }}
              >
                <Text style={styles.headerText}>Back</Text>
              </TouchableOpacity>
              {isSubmitting ? (
                <View
                  style={{
                    paddingTop: 10,
                    paddingHorizontal: 10
                  }}
                >
                  <ActivityIndicator size="small" color={Colors.DARK_BLUE} />
                </View>
              ) : (
                <TouchableOpacity
                  style={{
                    paddingTop: 16,
                    paddingBottom: 6,
                    paddingHorizontal: 6
                  }}
                  onPress={() => props.handleSubmit()}
                >
                  <Text style={styles.headerText}>Save</Text>
                </TouchableOpacity>
              )}
            </View>

            <ScrollView
              showsVerticalScrollIndicator={false}
              style={{ flex: 1 }}
              contentContainerStyle={{ gap: 16 }}
            >
              <View style={styles.photoContainer}>
                <TouchableOpacity style={styles.photoContainer} onPress={pickImage}>
                  {!image && (
                    <>
                      <View style={[styles.groupPhoto, { backgroundColor: Colors.FILL_LIGHT }]}>
                        <CameraIcon width={36} height={36} fill={Colors.LIGHT_GRAY} />
                      </View>
                      <Text style={styles.photoText}>Add photo</Text>
                    </>
                  )}
                  {image && (
                    <>
                      <Image
                        source={{ uri: image.uri }}
                        style={{
                          width: 80,
                          height: 80,
                          borderRadius: 40,
                          borderWidth: 1,
                          borderColor: Colors.FILL_LIGHT
                        }}
                      />
                      <Text style={styles.photoText}>Change photo</Text>
                    </>
                  )}
                </TouchableOpacity>
              </View>

              <Input
                placeholder="Add group name"
                value={props.values.name}
                inputMode={'text'}
                onChange={(text) => {
                  props.handleChange('name')(text);
                  setGroupName(text);
                }}
                onBlur={props.handleBlur('name')}
                header="Group name"
                formikError={props.touched.name && props.errors.name}
              />

              <Input
                placeholder="Add group description"
                value={props.values.description}
                onChange={(text) => {
                  props.handleChange('description')(text);
                  setDescription(text);
                }}
                onBlur={props.handleBlur('description')}
                header="Description"
                multiline
                height={58}
                formikError={props.touched.description && props.errors.description}
              />

              <View>
                <Text style={styles.title}>Members can</Text>

                <View style={styles.optionsContainer}>
                  <TouchableOpacity style={styles.option} onPress={() => setCanEdit(!canEdit)}>
                    <Text style={styles.optionText}>Edit group settings</Text>
                    <Checkbox
                      style={{ backgroundColor: Colors.WHITE, borderRadius: 4 }}
                      color={Colors.DARK_BLUE}
                      value={canEdit}
                      onValueChange={setCanEdit}
                    />
                  </TouchableOpacity>

                  <TouchableOpacity style={styles.option} onPress={() => setCanSend(!canSend)}>
                    <Text style={styles.optionText}>Send messages</Text>
                    <Checkbox
                      style={{ backgroundColor: Colors.WHITE, borderRadius: 4 }}
                      color={Colors.DARK_BLUE}
                      value={canSend}
                      onValueChange={setCanSend}
                    />
                  </TouchableOpacity>

                  <TouchableOpacity style={styles.option} onPress={() => setCanAdd(!canAdd)}>
                    <Text style={styles.optionText}>Add new members</Text>
                    <Checkbox
                      style={{ backgroundColor: Colors.WHITE, borderRadius: 4 }}
                      color={Colors.DARK_BLUE}
                      value={canAdd}
                      onValueChange={setCanAdd}
                    />
                  </TouchableOpacity>
                </View>
              </View>
              <View>
                <Text style={styles.title}>Members: {selectedUsers.length}</Text>
                {selectedUsers.length > 0 ? (
                  <View
                    style={[
                      styles.usersRow,
                      props.errors.users ? { borderColor: Colors.RED, borderWidth: 1 } : {}
                    ]}
                  >
                    <FlashList
                      viewabilityConfig={{
                        waitForInteraction: true,
                        itemVisiblePercentThreshold: 50,
                        minimumViewTime: 1000
                      }}
                      scrollEnabled={false}
                      data={selectedUsers}
                      renderItem={renderUserItem}
                      keyExtractor={(item) => item.user_id.toString()}
                      estimatedItemSize={100}
                      extraData={selectedUsers}
                      showsVerticalScrollIndicator={false}
                      contentContainerStyle={styles.selectedUsersList}
                      numColumns={4}
                    />
                  </View>
                ) : null}
                {props.errors.users && (
                  <Text
                    style={[styles.textError, selectedUsers.length > 0 ? { marginTop: -18 } : {}]}
                  >
                    select at least 1 member
                  </Text>
                )}
              </View>
            </ScrollView>
          </View>
        );
      }}
    </Formik>
  );
};

export default RouteAddGroup;
