import { useTest } from "@/api/tests";
import { useStartTestMutation } from "@/api/userTests";
import Question from "@/components/question";
import Test from "@/components/test";
import { ButtonText } from "@/components/ui/button";
import Content from "@/components/ui/content";
import CustomButton from "@/components/ui/custom-button";
import getErrorAxiosMessage from "@/utils/get-error-axios-message";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { View } from "react-native";
import { useToast } from "react-native-toast-notifications";

const TestScreen = () => {
  const { id: idParam } = useLocalSearchParams<{ id: string }>();
  const id = +idParam;
  const { data, isLoading } = useTest(id);
  const { mutate, isPending } = useStartTestMutation();
  const toast = useToast();

  if (!data)
    return (
      <>
        <Stack.Screen options={{ title: `Test #${id}` }} />
        <Content>{isLoading && <Test />}</Content>
      </>
    );

  const handleStartTest = () => {
    mutate(
      {
        test_id: data.id,
      },
      {
        onSuccess: (data) => {
          router.push(`/user-tests/doing/${data.id}`);
        },
        onError: (error) => {
          toast.show(getErrorAxiosMessage(error), { type: "danger" });
        },
      }
    );
  };

  return (
    <>
      <Stack.Screen options={{ title: `Test #${id}` }} />
      <Content>
        <View className="mb-3">
          <Test test={data} />
        </View>

        {data.is_available && (
          <CustomButton
            className="mb-3"
            onPress={handleStartTest}
            isLoading={isPending}
          >
            <ButtonText>Start Test</ButtonText>
          </CustomButton>
        )}

        <View className="gap-4">
          {data.questions?.map((question) => (
            <Question key={question.id} question={question} onPress={() => router.push(`/questions/${question.id}`)} />
          ))}
        </View>
      </Content>
    </>
  );
};

export default TestScreen;
