import React, { useEffect, useState } from 'react';

interface QuizModule {
    moduleName: string;
    type: string;
    moduleId: string;
}

export default function AdminIndex() {
    const [moduleList, setModuleList] = useState<QuizModule[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<Error | null>(null);

    useEffect(() => {
        fetch(`http://localhost:5174/api/quiz-module-list`)
            .then(res => {
                if (!res.ok) {
                    throw new Error('Network response was not ok');
                }
                return res.json();
            })
            .then(data => {
                console.log(data);
                setModuleList(data);
                setLoading(false);
            })
            .catch(error => {
                console.error('An error occurred', error);
                setError(error);
                setLoading(false);
            });
    }, []); // Dependency array to run the effect only once on mount

    if (loading) {
        return <div>Loading...</div>;
    }

    if (error) {
        return <div>Error: {error.message}</div>;
    }

    return (
        <div>
            <section className="container mx-auto px-4">
                <div>
                    <table className='w-full'>
                        <thead>
                            <tr>
                                <th>Module ID</th>
                                <th>Module Name</th>
                                <th>Module Type</th>
                                <th className=''>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {moduleList.map(module => (
                                <tr key={module.moduleId}>
                                    <td>{module.moduleId}</td>
                                    <td>{module.moduleName}</td>
                                    <td>{module.type}</td>
                                    <td>
                                        <div className='flex flex-row space-x-2'>
                                            <a href={`/admin/edit-module?id=${module.moduleId}`}>Edit</a>
                                            <span>|</span>
                                            <a href="">Delete</a>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </section>
        </div>
    );
}
