import { FontAwesome5, FontAwesome } from '@expo/vector-icons';
import { useNavigation, useRoute } from '@react-navigation/native';
import { FlashList } from '@shopify/flash-list';
import React, { useLayoutEffect, useState } from 'react';
import { View, Text } from 'react-native';

import Button from '../../../../../../../../components/Button/Button';
import Dropdown, { DropdownCard } from '../../../../../../../../components/Dropdown/Dropdown';
import MenuList from '../../../../../../../../components/List/MenuList';
import Loader from '../../../../../../../../components/Loader/Loader';
import ConfirmationModal from '../../../../../../../../components/Modal/ConfirmationModal';
import SortingModal from '../../../../../../../../components/Modal/SortingModal';
import { NavProps, RouteProps } from '../../../../../../../../components/Routes/Routes';
import TagGroup from '../../../../../../../../components/TagGroup/TagGroup';
import {
  EVENT_PARTICIPANTS_SORTING,
  SORT_DIRECTION,
  SORT_DIRECTION_TAG,
  SORT_TAG,
} from '../../../../../../../../constants/sorting';
import { getDateAsString } from '../../../../../../../../helpers/stringHelpers';
import {
  useEventDetail,
  useParticipantGeneralDeletePost,
  useParticipants,
} from '../../../../../../../../hooks/useEvents';
import { useFilterButtons } from '../../../../../../../../hooks/useFilterButtons';
import useSortList from '../../../../../../../../hooks/useSortList';
import { useUserInfo } from '../../../../../../../../hooks/useStorage';
import EventParticipantsFilterModal from './components/EventParticipantsFilterModal';

const EventParticipants = () => {
  const { id, eventName, isRelation } = useRoute<RouteProps<'EventParticipants'>>().params;
  const navigation = useNavigation<NavProps>();
  const [userInfo] = useUserInfo();
  const [expandedId, setExpandedId] = useState<string>('');

  const { list, isLoading, refetchList } = useParticipants(userInfo.token, id);
  const { detail } = useEventDetail(userInfo.token, id);

  const { mutate: deleteParticipant } = useParticipantGeneralDeletePost(
    userInfo.token,
    refetchList,
  );
  const [isDeletedModalVisible, setIsDeletedModalVisible] = useState(false);
  const [selectedParticipantId, setSelectedParticipantId] = useState('');

  const [filterModalVisible, setFilterModalVisible] = useState(false);
  const [sortModalVisible, setSortModalVisible] = useState(false);

  const [sort, setSort] = useState(EVENT_PARTICIPANTS_SORTING[0].label);
  const [sortDirection, setSortDirection] = useState(SORT_DIRECTION[0].label);
  const [name, setName] = useState('');

  useFilterButtons(setSortModalVisible, setFilterModalVisible);

  const sortedList = useSortList(list || [], sortDirection, sort, EVENT_PARTICIPANTS_SORTING);
  const filteredList = sortedList.filter(item => {
    if (name.length) {
      return item.name.toLowerCase().includes(name.toLowerCase());
    }
    return true;
  });

  useLayoutEffect(() => {
    navigation.setOptions({
      title: eventName,
    });
  }, [navigation, eventName]);
  const hasAccess = (!list?.length || list[0].hasPersonAccess) && isRelation;

  return (
    <View className="mx-4 mb-4 flex-1 justify-start bg-primary-bg">
      {!isLoading ? (
        <>
          {hasAccess && detail.isEditable ? (
            <Dropdown title="Další operace">
              <MenuList
                items={[
                  {
                    title: 'Přidat účastníka (vyhledat osobu)',
                    icon: <FontAwesome5 name="plus" size={24} />,
                    onPress: () =>
                      navigation.navigate('EventParticipantAddSearch', { eventId: id }),
                  },
                  {
                    title: 'Přidat účastníka (zadat novou osobu)',
                    icon: <FontAwesome5 name="plus" size={24} />,
                    onPress: () => navigation.navigate('EventParticipantAddNew', { eventId: id }),
                  },
                  {
                    title: 'Statistika účastníků',
                    icon: <FontAwesome name="bar-chart" size={24} />,
                    onPress: () =>
                      navigation.navigate('EventParticipantsStats', { id, eventName, hasAccess }),
                  },
                ]}
              />
            </Dropdown>
          ) : (
            <MenuList
              classNames="mt-4"
              items={[
                {
                  title: 'Statistika účastníků',
                  icon: <FontAwesome name="bar-chart" size={24} />,
                  onPress: () =>
                    navigation.navigate('EventParticipantsStats', { id, eventName, hasAccess }),
                },
              ]}
            />
          )}
          <TagGroup
            classNames="mt-2"
            items={[
              `${SORT_TAG} ${
                EVENT_PARTICIPANTS_SORTING.find(s => s.label === sort)?.displayName ?? ''
              }`,
              `${SORT_DIRECTION_TAG} ${sortDirection}`,
              ...(name.length ? [`Název: ${name}`] : []),
            ]}
          />
          <View className="flex-1 space-y-4">
            {filteredList?.length ? (
              <FlashList
                estimatedItemSize={100}
                data={filteredList}
                extraData={expandedId}
                keyExtractor={(item, index) => `${item.id}-${index}`}
                renderItem={({ item, index }) => (
                  <DropdownCard
                    title={item.name}
                    expandedId={expandedId}
                    setExpandedId={setExpandedId}
                    currentId={`${item.id}-${index}`}
                    logo={item.photo || 'user'}
                    items={[
                      {
                        title: 'Kategorie:',
                        value: item.category || ' ',
                      },
                      {
                        title: 'Datum narození:',
                        value: item.birthday.length
                          ? getDateAsString(new Date(item.birthday))
                          : ' ',
                      },
                      {
                        title: 'Adresa:',
                        value: item.address || ' ',
                      },
                      {
                        title: 'Věk:',
                        value: item.age || ' ',
                      },
                      {
                        title: 'Poznámka:',
                        value: item.note || ' ',
                        dropdown: true,
                      },
                    ]}
                  >
                    {item.hasPersonAccess && (
                      <>
                        <View className="flex-1 flex-row justify-end pb-4 pr-3">
                          {detail.isEditable && isRelation && (
                            <>
                              <Button
                                classNames="py-1 pl-5"
                                variant="text"
                                onPress={() => {
                                  setSelectedParticipantId(item.id);
                                  setIsDeletedModalVisible(true);
                                }}
                              >
                                Smazat
                              </Button>
                              <Button
                                classNames="py-1 pl-5"
                                variant="text"
                                onPress={() =>
                                  navigation.navigate('EventParticipantEdit', {
                                    id: item.id,
                                    personName: item.name || '',
                                    note: item.note,
                                    days: item.days,
                                    eventId: id,
                                  })
                                }
                              >
                                Upravit
                              </Button>
                            </>
                          )}
                          <Button
                            classNames="py-1 pl-5"
                            variant="text"
                            onPress={() =>
                              navigation.navigate('PersonDetail', {
                                id: item.personId,
                                isFromCatalog: true,
                              })
                            }
                          >
                            Detail
                          </Button>
                        </View>
                      </>
                    )}
                  </DropdownCard>
                )}
              />
            ) : (
              <Text className="mt-4 rounded bg-secondary-bg p-4">
                Pro daná kritéria nebyly nalezeny žádné akce.
              </Text>
            )}
          </View>
        </>
      ) : (
        <Loader />
      )}
      <ConfirmationModal
        isVisible={isDeletedModalVisible}
        setIsVisible={setIsDeletedModalVisible}
        title="Odstranit účastníka akce"
        text="Opravdu se chcete odstranit účastníka z akce?"
        onConfirm={() => deleteParticipant(selectedParticipantId)}
      />
      <SortingModal
        isVisible={sortModalVisible}
        setIsVisible={setSortModalVisible}
        values={EVENT_PARTICIPANTS_SORTING}
        selectedValue={sort}
        setSelectedValue={setSort}
        selectedDirection={sortDirection}
        setSelectedDirection={setSortDirection}
      />
      <EventParticipantsFilterModal
        isVisible={filterModalVisible}
        setIsVisible={setFilterModalVisible}
        name={name}
        setName={setName}
      />
    </View>
  );
};

export default EventParticipants;
