import { FontAwesome5 } from '@expo/vector-icons';
import { useNavigation, useRoute } from '@react-navigation/native';
import cn from 'classnames';
import React, { useLayoutEffect } from 'react';
import { View, Text, TouchableOpacity, Image, ScrollView } from 'react-native';

import Title from '../../../../../../../../components/List/components/Title';
import Loader from '../../../../../../../../components/Loader/Loader';
import { NavProps, RouteProps } from '../../../../../../../../components/Routes/Routes';
import { CANDIDATE_GROUPS } from '../../../../../../../../constants/custom';
import { useCandidates, useCongressDetail } from '../../../../../../../../hooks/useCongress';
import { useUserInfo } from '../../../../../../../../hooks/useStorage';
import { CandidateAllResponse } from '../../../../../../../../services/api/APIS/Events/types';

const CandidateTable = ({
  candidates,
}: {
  candidates: (CandidateAllResponse & { photo: string })[];
}) => {
  const navigation = useNavigation<NavProps>();
  return (
    <View className="mb-4">
      {candidates?.length ? (
        <View className="space-y-4">
          {candidates?.map(item => (
            <TouchableOpacity
              key={item.id}
              onPress={() =>
                navigation.navigate('CongressCandidateDetail', { id: item.id, photo: item.photo })
              }
              className="rounded bg-secondary-bg p-2"
            >
              <View className="flex flex-row items-center py-2">
                <View className="flex items-center">
                  {!item.photo?.length ? (
                    <FontAwesome5 name="user" size={50} color="black" />
                  ) : (
                    <Image
                      className="h-[60px] w-[60px] rounded"
                      source={{ uri: `data:image/png;base64,${item.photo}` }}
                    />
                  )}
                </View>
                <Text className="p-2 font-panton text-lg font-bold text-primary">
                  {item.person}
                </Text>
              </View>
              <View>
                {[
                  ...(item?.personWith
                    ? [
                        {
                          title: 'S kým kandiduje:',
                          value: item?.personWith,
                        },
                      ]
                    : []),
                  {
                    title: 'Funkce, na kterou kandiduje:',
                    value: item?.congressFunction,
                  },
                ]?.map((row, index) => (
                  <View key={index}>
                    {row && (
                      <>
                        <View
                          className={cn('flex-row justify-between p-2', {
                            'rounded-sm bg-primary-bg': index % 2 === 0,
                          })}
                        >
                          <Text>{row?.title}</Text>
                          <Text className="flex-1 flex-wrap text-right">{row?.value}</Text>
                        </View>
                      </>
                    )}
                  </View>
                ))}
              </View>
            </TouchableOpacity>
          ))}
        </View>
      ) : (
        <Text className="rounded bg-secondary-bg p-4">Tabulka neobsahuje žádná data.</Text>
      )}
    </View>
  );
};

const CongressCandidates = () => {
  const { id, eventName } = useRoute<RouteProps<'CongressCandidates'>>().params;
  const [userInfo] = useUserInfo();
  const navigation = useNavigation<NavProps>();

  const { list: candidates, isLoading: isCandidatesLoading } = useCandidates(userInfo.token, id);
  const { detail, isLoading: isDetailLoading } = useCongressDetail(userInfo.token, id);

  const isFuture = () => {
    const today = new Date();
    const endDate = new Date(detail.endDate || '');
    const alEnd = new Date(detail?.alternativeEndDate || '');
    return detail && (endDate > today || alEnd > today);
  };

  const isLoading = isCandidatesLoading || isDetailLoading;

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

  return (
    <View className="m-4 flex-1 justify-start bg-primary-bg">
      {!isLoading && candidates ? (
        <ScrollView>
          {CANDIDATE_GROUPS.map((group, index) => (
            <View key={index}>
              {((index === 0 && isFuture()) || index !== 0) && (
                <>
                  <Title classNames="mb-4" text={group.title} />
                  <CandidateTable
                    candidates={candidates.filter(
                      (can: { state: string }) => can.state === group.type,
                    )}
                  />
                </>
              )}
            </View>
          ))}
        </ScrollView>
      ) : (
        <Loader />
      )}
    </View>
  );
};

export default CongressCandidates;
