import { useEffect, useState } from 'react';
import { Box, Heading, HStack, Icon, Image, Text, useToast, VStack } from '@gluestack-ui/themed';
import { useNavigation, useRoute } from '@react-navigation/native';
import { ArrowLeft } from 'lucide-react-native';
import { ScrollView, TouchableOpacity } from 'react-native';

import { api } from '@services/api';
import { AppError } from '@utils/AppError';
import { ExerciseDTO } from '@dtos/ExerciseDTO';
import { AppNavigatorRoutesProps } from '@routes/app.routes';

import BodySvg from '@assets/body.svg';
import SeriesSvg from '@assets/series.svg';
import RepetitionSvg from '@assets/repetitions.svg';

import { Button } from '@components/Button';
import { ToastMessage } from '@components/ToastMessage';
import { Loading } from '@components/Loading';

type RouteParams = {
  exerciseId: string;
};

export function Exercise() {
  const [sendingExerciseRegister, setSendingExerciseRegister] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  const [exercise, setExercise] = useState<ExerciseDTO>({} as ExerciseDTO);

  const navigation = useNavigation<AppNavigatorRoutesProps>();
  const toast = useToast();

  const route = useRoute();
  const { exerciseId } = route.params as RouteParams;

  function handleGoBack() {
    navigation.goBack();
  }

  async function fetchExerciseData() {
    try {
      setIsLoading(true);
      const response = await api.get(`/exercises/${exerciseId}`);
      setExercise(response.data);
    } catch (error) {
      const isAppError = error instanceof AppError;
      const title = isAppError
        ? error.message
        : 'Não foi possível carregar os detalhes do exercício.';
      toast.show({
        placement: 'top',
        render: ({ id }) => (
          <ToastMessage id={id} title={title} action="error" onClose={() => toast.close(id)} />
        ),
      });
    } finally {
      setIsLoading(false);
    }
  }
  async function handleExerciseHistoryRegister() {
    try {
      setSendingExerciseRegister(true);

      await api.post('/history', { exercise_id: exerciseId });

      toast.show({
        placement: 'top',
        render: ({ id }) => (
          <ToastMessage
            id={id}
            title="Parabéns! Exercício registrado no seu hitórico."
            action="success"
            onClose={() => toast.close(id)}
          />
        ),
      });

      navigation.navigate('History');
    } catch (error) {
      const isAppError = error instanceof AppError;
      const title = isAppError ? error.message : 'Não foi possível registrar o exercício.';
      toast.show({
        placement: 'top',
        render: ({ id }) => (
          <ToastMessage id={id} title={title} action="error" onClose={() => toast.close(id)} />
        ),
      });
    } finally {
      setSendingExerciseRegister(false);
    }
  }

  useEffect(() => {
    fetchExerciseData();
  }, [exerciseId]);

  return (
    <VStack flex={1}>
      <VStack px="$8" bg="$gray600" pt="$12">
        <TouchableOpacity onPress={handleGoBack}>
          <Icon as={ArrowLeft} color="$green500" size="xl" />
        </TouchableOpacity>

        <HStack alignItems="center" justifyContent="space-between" mt="$4" mb="$8">
          <Heading color="$gray100" fontSize="$lg" flexShrink={1}>
            {exercise.name}
          </Heading>

          <HStack alignItems="center">
            <BodySvg />
            <Text color="$gray200" ml="$1" textTransform="capitalize">
              {exercise.group}
            </Text>
          </HStack>
        </HStack>
      </VStack>

      {isLoading ? (
        <Loading />
      ) : (
        <ScrollView
          showsVerticalScrollIndicator={false}
          contentContainerStyle={{ paddingBottom: 32 }}>
          <VStack p="$8">
            <Image
              source={{ uri: `${api.defaults.baseURL}/exercise/demo/${exercise.demo}` }}
              alt="imagem do exercício"
              mb="$3"
              resizeMode="cover"
              rounded="$lg"
              w="$full"
              h="$80"
            />

            <Box bg="$gray600" rounded="$md" pb="$4" px="$4">
              <HStack alignItems="center" justifyContent="space-around" mb="$6" mt="$5">
                <HStack>
                  <SeriesSvg />
                  <Text color="$gray200" ml="$2">
                    {exercise.series} séries
                  </Text>
                </HStack>

                <HStack>
                  <RepetitionSvg />
                  <Text color="$gray200" ml="$2">
                    {exercise.repetitions} repetições
                  </Text>
                </HStack>
              </HStack>

              <Button
                title="Marcar como realizado"
                isLoading={sendingExerciseRegister}
                onPress={handleExerciseHistoryRegister}
              />
            </Box>
          </VStack>
        </ScrollView>
      )}
    </VStack>
  );
}
