import { useState, useEffect } from "react";
import type { VocabWord, Tag } from "@/types/types";
import FlashCard from "./FlashCard";

export default function FlashCardActivity() {
    const [words, setWords] = useState<VocabWord[]>([]);
    const [tags, setTags] = useState<Tag[]>([]);
    const [currentWord, setCurrentWord] = useState<VocabWord | null>(null);
    const [numFilteredWords, setNumFilteredWords] = useState(0);
    const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);
    const [selectedTypes, setSelectedTypes] = useState<string[]>(['noun', 'verb', 'adjective']);

    useEffect(() => {
        // Fetch all words and tags
        Promise.all([
            fetch('/api/vocab.json').then(res => res.json()),
            fetch('/api/tags.json').then(res => res.json()),
        ]).then(([wordsData, tagsData]) => {
            setWords(wordsData);
            setTags(tagsData);
            // Default: select all tags
            setSelectedTagIds(tagsData.map((t: Tag) => t.id));
        });
    }, []);

    useEffect(() => {
        // Update filtered words count and get a new random word when filters change
        updateFilteredWordsAndRandomize();
    }, [words, selectedTagIds, selectedTypes]);

    const getFilteredWords = () => {
        return words.filter(word => {
            // Filter by tags
            const hasSelectedTag = word.tags?.some(tag => selectedTagIds.includes(tag.id));
            if (!hasSelectedTag) return false;

            // Filter by type
            if (word.type && !selectedTypes.includes(word.type)) return false;

            return true;
        });
    };

    const updateFilteredWordsAndRandomize = () => {
        const filteredWords = getFilteredWords();
        setNumFilteredWords(filteredWords.length);

        if (filteredWords.length > 0) {
            const randomIndex = Math.floor(Math.random() * filteredWords.length);
            setCurrentWord(filteredWords[randomIndex]);
        } else {
            setCurrentWord(null);
        }
    };

    const getRandomWord = () => {
        const filteredWords = getFilteredWords();
        if (filteredWords.length === 0) {
            alert("No words match the selected filters.");
            return;
        }
        const randomIndex = Math.floor(Math.random() * filteredWords.length);
        setCurrentWord(filteredWords[randomIndex]);
    };

    const toggleTag = (tagId: number) => {
        setSelectedTagIds(prev =>
            prev.includes(tagId)
                ? prev.filter(id => id !== tagId)
                : [...prev, tagId]
        );
    };

    const toggleType = (type: string) => {
        setSelectedTypes(prev =>
            prev.includes(type)
                ? prev.filter(t => t !== type)
                : [...prev, type]
        );
    };

    return (
        <div className="flash-card-activity">
            {currentWord && (
                <FlashCard word={currentWord} />
            )}

            <button onClick={getRandomWord}>Next</button>
            <div>
                {numFilteredWords} words match the selected filters.
            </div>

            <style>{`
                .flash-card-activity {
                    margin: 2rem 0;
                }

                .filters {
                    display: flex;
                    gap: 2rem;
                    margin-bottom: 2rem;
                    padding: 1rem;
                    background: var(--sl-color-gray-6);
                    border-radius: 8px;
                }

                .filter-group {
                    flex: 1;
                }

                .filter-group h3 {
                    margin-top: 0;
                    margin-bottom: 0.5rem;
                    font-size: 1rem;
                }

                .filter-checkbox {
                    display: flex;
                    align-items: center;
                    gap: 0.5rem;
                    margin-bottom: 0.25rem;
                    font-weight: normal;
                }

                .filter-checkbox input[type="checkbox"] {
                    margin: 0;
                }
            `}</style>
        </div>
    );
}
