
import { useTests } from '@/api/tests';
import { TestResponse } from '@/api/types';
import useTaxonomyContext from '@/components/providers/taxonomy-provider/hook';
import Test from '@/components/test';
import { Button, ButtonText } from '@/components/ui/button';
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 { FontAwesome5 } from '@expo/vector-icons';
import { router } from 'expo-router';
import { useRef, useState } from 'react';
import { ScrollView, View } from 'react-native';

export default function TestsScreen() {
  const { categories } = useTaxonomyContext();
  
  const [category, setCategory] = useState<undefined|number>(undefined);
  const [page, setPage] = useState<number>(1);

  const { data: testsPagination, isLoading } = useTests({
    page: page,
    category_id: category
  });

  const scrollRef = useRef<ScrollView>(null);

  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'>Tests</ThemedText>

      <View className="mb-4 flex-row">
        <CustomSelect
          className="mr-2 flex-1"
          options={categoryOptions}
          noneOption={{ label: "All categories", value: "all" }}
          selectedValue={category ? `${category}` : undefined}
          onValueChange={handleChangeCategory}
          placeholder="Select category" />
        <Button onPress={() => router.push('/qr')}>
          <ButtonText><FontAwesome5 name="qrcode" size={18} /></ButtonText>
        </Button>
      </View>

      <PaginationList<TestResponse>
        pagination={testsPagination}
        isLoadingPage={isLoading}
        renderItem={(item) => (
          <Test test={item} onPress={() => router.push(`/tests/${item.id}`)} />
        )}
        skeleton={<Test />}
        currentPage={page}
        setCurrentPage={setPage}
        scrollView={scrollRef}
      />
    </Content>
  );
}
