import { ScrollView, View } from "react-native";

import { useQuestions } from "@/api";
import { QuestionResponse } from "@/api/types";
import useTaxonomyContext from "@/components/providers/taxonomy-provider/hook";
import Question from "@/components/question";
import Content from "@/components/ui/content";
import CustomSelect from "@/components/ui/custom-select";
import PaginationList from "@/components/ui/pagination-list";
import { ThemedText } from "@/components/ui/themed-text";
import getCategoryOptions from "@/utils/get-category-options";
import { router } from "expo-router";
import { useRef, useState } from "react";

export default function QuestionsScreen() {
  const [category, setCategory] = useState<undefined|number>(undefined);
  const [page, setPage] = useState<number>(1);
  const { categories } = useTaxonomyContext();
  const scrollRef = useRef<ScrollView>(null);
  const { data: questionsPagination, isLoading } = useQuestions({
    page: page,
    category_id: category
  });

  const categoryOptions = getCategoryOptions(categories);
  
  const handleChangeCategory = (value: string) => {
    setPage(1);
    if(value === "all")
      setCategory(undefined);
    else
      setCategory(+value);
  }

  return (
    <Content ref={scrollRef}>
      <ThemedText type="title" className="mb-3">
        Questions
      </ThemedText>

      <View className="mb-4">
        <CustomSelect 
          options={categoryOptions}
          noneOption={{ label: "All categories", value: "all" }}
          selectedValue={category ? `${category}` : undefined}
          onValueChange={handleChangeCategory}
          placeholder="Select category" />
      </View>

      <PaginationList<QuestionResponse>
        pagination={questionsPagination}
        renderItem={(item) => (
          <Question question={item} onPress={() => router.push(`/questions/${item.id}`)} withCategory={true} />
        )}
        skeleton={<Question />}
        currentPage={page}
        setCurrentPage={setPage}
        scrollView={scrollRef}
        isLoadingPage={isLoading}
      />
    </Content>
  );
}
