// frontend/screens/Home/ExercisesScreen.js

import React, { useContext, useState } from 'react';
import {
    View,
    Text,
    FlatList,
    ActivityIndicator,
} from 'react-native';
import { AuthContext } from '../../context/AuthContext';
import { useTheme } from 'react-native-paper';
import CustomMultiSelect from '../../Components/CustomMultiSelect';
import useExercises from '../../hooks/useExercises';
import useFilters from '../../hooks/useFilters';
import ExerciseItem from '../../Components/ExerciseItem';
import FilterModal from '../../Components/FilterModal';
import DetailModal from '../../Components/DetailModal';
import SearchHeader from '../../Components/SearchHeader';
import createStyles from './ExercisesScreenStyles';

const ExercisesScreen = () => {
    const { authToken } = useContext(AuthContext);
    const theme = useTheme();
    const styles = createStyles(theme);

    // Filter management
    const {
        selectedMuscles,
        selectedEquipment,
        selectedDifficulty,
        handleSelectedMusclesChange,
        handleSelectedEquipmentChange,
        setSelectedDifficulty,
        resetFilters,
    } = useFilters();

    // State for modals
    const [filterModalVisible, setFilterModalVisible] = useState(false);
    const [detailModalVisible, setDetailModalVisible] = useState(false);
    const [selectedExercise, setSelectedExercise] = useState(null);

    // Search query
    const [searchQuery, setSearchQuery] = useState('');

    // Fetch exercises using custom hook
    const {
        exercises,
        loading,
        isRefreshing,
        onRefresh,
    } = useExercises(authToken, searchQuery, {
        muscles: selectedMuscles.join(','),
        equipment: selectedEquipment.join(','),
        difficulty: selectedDifficulty,
    });

    // Predefined filter options
    const muscleOptions = [
        { id: 'chest', name: 'Chest' },
        { id: 'back', name: 'Back' },
        { id: 'legs', name: 'Legs' },
        { id: 'arms', name: 'Arms' },
        { id: 'shoulders', name: 'Shoulders' },
        // Add more muscles as needed
    ];

    const equipmentOptions = [
        { id: 'barbell', name: 'Barbell' },
        { id: 'dumbbell', name: 'Dumbbell' },
        { id: 'kettlebell', name: 'Kettlebell' },
        { id: 'machine', name: 'Machine' },
        { id: 'bodyweight', name: 'Bodyweight' },
        { id: 'band', name: 'Band' },
        { id: 'plate', name: 'Plate' },
        { id: 'other', name: 'Other' },
        // Add more equipment as needed
    ];

    const difficultyOptions = [
        { label: 'Beginner', value: 'beginner' },
        { label: 'Intermediate', value: 'intermediate' },
        { label: 'Advanced', value: 'advanced' },
    ];

    // Handlers
    const handleSearch = (text) => {
        setSearchQuery(text);
    };

    const openFilterModal = () => {
        setFilterModalVisible(true);
    };

    const closeFilterModal = () => {
        setFilterModalVisible(false);
    };

    const handleOpenURL = async (url) => {
        const supported = await Linking.canOpenURL(url);
        if (supported) {
            await Linking.openURL(url);
        } else {
            Alert.alert('Invalid URL', 'Cannot open the requested URL.');
        }
    };

    const openDetailModal = (exercise) => {
        setSelectedExercise(exercise);
        setDetailModalVisible(true);
    };

    const closeDetailModal = () => {
        setDetailModalVisible(false);
        setSelectedExercise(null);
    };

    // Render
    if (loading && exercises.length === 0) {
        return (
            <View style={styles.loader}>
                <ActivityIndicator size="large" color={theme.colors.primary} />
            </View>
        );
    }

    return (
        <View style={styles.container}>
            {/* Search and Filter Header */}
            <SearchHeader
                searchQuery={searchQuery}
                onSearch={handleSearch}
                onOpenFilter={openFilterModal}
            />

            {/* Filter Modal */}
            <FilterModal
                visible={filterModalVisible}
                onClose={closeFilterModal}
                muscleOptions={muscleOptions}
                equipmentOptions={equipmentOptions}
                difficultyOptions={difficultyOptions}
                selectedMuscles={selectedMuscles}
                selectedEquipment={selectedEquipment}
                selectedDifficulty={selectedDifficulty}
                onMusclesChange={handleSelectedMusclesChange}
                onEquipmentChange={handleSelectedEquipmentChange}
                onDifficultyChange={setSelectedDifficulty}
                onReset={resetFilters}
            />

            {/* Detail Modal */}
            <DetailModal
                visible={detailModalVisible}
                onClose={closeDetailModal}
                exercise={selectedExercise}
                onOpenURL={handleOpenURL}
            />

            {/* Exercises List */}
            <FlatList
                data={exercises}
                keyExtractor={(item, index) => (item._id ? item._id : index.toString())}
                renderItem={({ item }) => (
                    <ExerciseItem
                        item={item}
                        onPress={openDetailModal}
                        onOpenURL={handleOpenURL}
                    />
                )}
                contentContainerStyle={styles.list}
                keyboardShouldPersistTaps="handled"
                refreshControl={
                    <RefreshControl
                        refreshing={isRefreshing}
                        onRefresh={onRefresh}
                        tintColor={theme.colors.primary}
                        colors={[theme.colors.primary, theme.colors.accent]}
                        progressBackgroundColor={theme.colors.surface}
                    />
                }
                ListEmptyComponent={
                    !loading && (
                        <View style={styles.emptyContainer}>
                            <Text style={styles.emptyText}>No exercises found.</Text>
                        </View>
                    )
                }
                initialNumToRender={10}
                windowSize={21}
                getItemLayout={(data, index) => (
                    { length: 250, offset: 250 * index, index }
                )}
            />
        </View>
    );
};

export default ExercisesScreen;