import { ExerciceServiceRef } from "@/api/services/service.ref";
import WorkoutCardComponent from "@/components/WorkoutCardComponent";
import { Workout } from "@/model/Workout";
import {useNavigation, useRouter} from "expo-router";
import React, { useEffect, useState } from "react";
import {FlatList, SafeAreaView, Text, TouchableOpacity, View} from "react-native";

export default function ExercicesScreen() {
  const [exercices, setExercices] = useState<Workout[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const router = useRouter();

  const exerciceService = ExerciceServiceRef;

  useEffect(() => {
    const fetchData = async () => {
      try {
        const data = await exerciceService.getExercices();
        setExercices(data);
      } catch (err: any) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return <Text className="text-white">Chargement...</Text>;
  }

  if (error) {
    return <Text className="text-red-500">Erreur : {error}</Text>;
  }

  return (
    <SafeAreaView>
      <FlatList
        data={exercices}
        keyExtractor={(item) => item.id ?? ""}
        renderItem={({ item }) => (
          <TouchableOpacity
            className="flex-1 m-2"
          >
            <WorkoutCardComponent exercise={item} background={"black"} />
          </TouchableOpacity>
        )}
      />
    </SafeAreaView>
  );
}
