import { useQuestion } from "@/api";
import { QuestionTypes, QuestionVariant } from "@/api/types";
import Question from "@/components/question";
import Answer from "@/components/ui/answer";
import { Button, ButtonText } from "@/components/ui/button";
import Content from "@/components/ui/content";
import { Divider } from "@/components/ui/divider";
import { Stack, useLocalSearchParams } from "expo-router";
import { useState } from "react";
import { View } from "react-native";

const QuestionScreen = () => {
  const { id: idParam } = useLocalSearchParams<{ id: string }>();
  const id = +idParam;
  const { data, isLoading } = useQuestion(id);
  const [withCorrect, setWithCorrect] = useState(false);

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

  const answers: QuestionVariant[] = data.variants?.length
    ? data.variants
    : [
        {
          id: 1,
          text: data.correct_answers[0] as string,
        },
      ];

  const displayAnswers =
    (data.type === QuestionTypes.Text && withCorrect) ||
    data.type !== QuestionTypes.Text;

  const withCorrectBtnText = withCorrect ? "ON" : "OFF";

  return (
    <>
      <Stack.Screen options={{ title: `Question #${id}` }} />
      <Content>
        <Question question={data} withMeta={true} />

        <Divider className="mt-5 mb-5" />

        <View className="gap-4">
          {displayAnswers &&
            answers.map((answer) => (
              <Answer
                key={answer.id}
                answer={answer}
                isTextType={data.type === "text"}
                correctAnswers={data.correct_answers}
                displayCorrect={withCorrect}
              />
            ))}

          <Button
            action="secondary"
            onPress={() => setWithCorrect(!withCorrect)}
          >
            <ButtonText>Display answers: {withCorrectBtnText}</ButtonText>
          </Button>
        </View>
      </Content>
    </>
  );
};

export default QuestionScreen;
