import { getExercices } from "@/api/services/ExercicesServices";
import WorkoutCardComponent from "@/components/WorkoutCardComponent";
import { Workout } from "@/model/Workout";
import { useRouter } from "expo-router";
import React, { useEffect, useState } from "react";
import { FlatList, 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();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const data = await 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 (
    <View className="p-4">
      <FlatList
        data={exercices}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <TouchableOpacity
            className="p-4 mb-2 bg-gray-800 rounded-lg"
            onPress={() =>
              router.push({
                pathname: "/WorkoutScreen",
                params: { workout: JSON.stringify(item) },
              })
            }
          >
            <WorkoutCardComponent exercise={item} background={"black"} />
          </TouchableOpacity>
        )}
      />
    </View>
  );
}
