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 {
  CAMP_PARTICIPANTS_SORTING,
  CAMP_SORTING,
  SORT_DIRECTION,
  SORT_DIRECTION_TAG,
  SORT_TAG,
} from '../../../../../../../../constants/sorting';
import { getDateAsString } from '../../../../../../../../helpers/stringHelpers';
import {
  useCampDetail,
  useParticipantCampDeletePost,
  useParticipants,
  usePersonAllEventCampMultiGet,
} from '../../../../../../../../hooks/useCamps';
import { useFilterButtons } from '../../../../../../../../hooks/useFilterButtons';
import useSortList from '../../../../../../../../hooks/useSortList';
import { useUserInfo } from '../../../../../../../../hooks/useStorage';
import CampParticipantsFilterModal from './components/CampParticipantsFilterModal';

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

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

  const { refetch: refetchMultiList } = usePersonAllEventCampMultiGet(
    userInfo.token,
    id,
    !detail.isEditable || !isRelation,
  );

  const refetch = () => {
    refetchList();
    refetchMultiList();
  };

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

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

  const [sort, setSort] = useState(CAMP_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, CAMP_PARTICIPANTS_SORTING);
  const filteredList = sortedList.filter(item => {
    if (name.length) {
      return item.name.toLowerCase().includes(name.toLowerCase());
    }
    return true;
  });

  useLayoutEffect(() => {
    navigation.setOptions({
      title: campName,
    });
  }, [navigation, campName]);

  const hasAccess = !list?.length || list[0].hasPersonAccess;

  return (
    <View className="mx-4 mb-4 flex-1 justify-start bg-primary-bg">
      {!isLoading ? (
        <>
          {hasAccess && detail.isEditable && isRelation ? (
            <Dropdown title="Další operace">
              <MenuList
                items={[
                  {
                    title: 'Přidat účastníka (vyhledat osobu)',
                    icon: <FontAwesome5 name="plus" size={24} />,
                    onPress: () => navigation.navigate('CampParticipantAddSearch', { campId: id }),
                  },
                  {
                    title: 'Přidat účastníka (zadat novou osobu)',
                    icon: <FontAwesome5 name="plus" size={24} />,
                    onPress: () => navigation.navigate('CampParticipantAddNew', { campId: id }),
                  },
                  {
                    title: 'Přidat účastníka (výběrem z oddílu)',
                    icon: <FontAwesome5 name="plus" size={24} />,
                    onPress: () => navigation.navigate('CampParticipantAddUnit', { campId: id }),
                  },
                  {
                    title: 'Statistika účastníků',
                    icon: <FontAwesome name="bar-chart" size={24} />,
                    onPress: () => navigation.navigate('CampParticipantsStats', { id, campName }),
                  },
                ]}
              />
            </Dropdown>
          ) : (
            <MenuList
              classNames="mt-4"
              items={[
                {
                  title: 'Statistika účastníků',
                  icon: <FontAwesome name="bar-chart" size={24} />,
                  onPress: () => navigation.navigate('CampParticipantsStats', { id, campName }),
                },
              ]}
            />
          )}
          <TagGroup
            classNames="mt-2"
            items={[
              `${SORT_TAG} ${CAMP_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: 'Skutečný počet dnů:',
                        value: item.days || ' ',
                        dropdown: true,
                      },
                      {
                        title: 'Předpokládaná účast:',
                        value: item.isEstimate ? 'Ano' : 'Ne',
                        dropdown: true,
                      },
                      {
                        title: 'Skutečná účast:',
                        value: item.isReal ? 'Ano' : 'Ne',
                        dropdown: true,
                      },
                      {
                        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('CampParticipantEdit', {
                                    id: item.id,
                                    personName: item.name || '',
                                    isEstimate: item.isEstimate,
                                    isReal: item.isReal,
                                    note: item.note,
                                    days: item.days,
                                    campId: 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 táboru"
        text="Opravdu se chcete odstranit účastníka z táboru?"
        onConfirm={() => deleteParticipant(selectedParticipantId)}
      />
      <SortingModal
        isVisible={sortModalVisible}
        setIsVisible={setSortModalVisible}
        values={CAMP_PARTICIPANTS_SORTING}
        selectedValue={sort}
        setSelectedValue={setSort}
        selectedDirection={sortDirection}
        setSelectedDirection={setSortDirection}
      />
      <CampParticipantsFilterModal
        isVisible={filterModalVisible}
        setIsVisible={setFilterModalVisible}
        name={name}
        setName={setName}
      />
    </View>
  );
};

export default CampParticipants;
