import { useMyTests } from "@/api/userTests";
import Content from "@/components/ui/content";
import CustomSelect from "@/components/ui/custom-select";
import UserTest from "@/components/user-test";
import { getUserTestStatus, TestStatus } from "@/utils/get-user-test-status";
import { router, Stack } from "expo-router";
import { useMemo, useState } from "react";
import { View } from "react-native";

const filterSelectOptions = [
  { label: TestStatus.Completed, value: TestStatus.Completed },
  { label: TestStatus.InProgress, value: TestStatus.InProgress },
  { label: TestStatus.Expired, value: TestStatus.Expired },
];

const MeUserTestsScreen = () => {
  const { data: userTests } = useMyTests();
  const [selectedStatus, setStatus] = useState<string>("all");
  const filteredUserTests = useMemo(() => {
    if(!userTests) return [];
    if(selectedStatus !== "all") {
      return userTests.filter((userTest) => getUserTestStatus(userTest) === selectedStatus);
    }
    return userTests;
  }, [userTests, selectedStatus]);

  if(!userTests)
    return (
      <>
        <Stack.Screen options={{ title: `My tests` }} />
        <Content>
          <UserTest />
        </Content>
      </>
    );

  return (
    <>
      <Stack.Screen options={{ title: `My tests` }} />
      <Content>
        <View className="mb-4">
          <CustomSelect
            options={filterSelectOptions}
            noneOption={{ label: "All tests", value: "all" }}
            placeholder="Filter by status"
            selectedValue={selectedStatus}
            onValueChange={(value) => setStatus(value)}
          />
        </View>

        {filteredUserTests.map((userTest) => (
          <View key={userTest.id} className="mb-3">
            <UserTest userTest={userTest} onPress={() => router.push(`/user-tests/${userTest.id}`)} />
          </View>
        ))}
      </Content>
    </>
  )
}

export default MeUserTestsScreen;