import gradio as gr
from utils.helpers import load_content, check_spelling, check_translation, get_random_exercise, check_reading_answer

def intermediate_component():
    content = load_content()
    
    with gr.Column() as intermediate:
        # Vocabulary Section
        with gr.Tab("Vocabulary"):
            gr.Markdown("### Intermediate Vocabulary")
            word_display = gr.Textbox(label="Afrikaans Word")
            translation_hidden = gr.Textbox(visible=False)
            sentence_display = gr.Textbox(label="Example Sentence")
            user_translation = gr.Textbox(label="Your Translation")
            check_btn = gr.Button("Check")
            result = gr.Textbox(label="Result")
            next_btn = gr.Button("Next Word")

            def get_vocab():
                exercise = get_random_exercise("vocabulary", "intermediate")
                return exercise["word"], exercise["translation"], exercise["sentence"]

            def check_vocab(user_input, correct):
                return "Correct! ✓" if check_translation(user_input, correct) else "Try again"

            next_btn.click(fn=get_vocab, outputs=[word_display, translation_hidden, sentence_display])
            check_btn.click(fn=check_vocab, inputs=[user_translation, translation_hidden], outputs=[result])

        # Grammar Section
        with gr.Tab("Grammar"):
            gr.Markdown("### Intermediate Grammar")
            for rule in content["grammar"]["intermediate"]:
                with gr.Accordion(rule["rule"], open=False):
                    gr.Markdown(rule["explanation"])

        # Reading Section
        with gr.Tab("Reading"):
            gr.Markdown("### Intermediate Reading")
            for text in content["reading"]["intermediate"]:
                with gr.Accordion(text["title"], open=False):
                    gr.Markdown(text["text"])
                    for i, question in enumerate(text["questions"]):
                        gr.Markdown(f"**Question {i+1}:** {question}")
                        answer = gr.Textbox(label="Your Answer")
                        result = gr.Textbox(label="Result")
                        check_btn = gr.Button(f"Check Answer {i+1}")
                        
                        check_btn.click(
                            fn=lambda ans, idx=i, txt=text: "Correct! ✓" 
                            if check_reading_answer(ans, idx, txt) else "Try again",
                            inputs=[answer],
                            outputs=[result]
                        )

    return intermediate