import React, {useEffect, useState} from 'react';
import {useLocation, useNavigate} from 'react-router-dom';
import {fetchAdminThemes} from '@_api/theme/themeAPI';
import type {AdminThemeSummaryRetrieveResponse} from '@_api/theme/themeTypes';
import {isLoginRequiredError} from '@_api/apiClient';
import '@_css/admin-theme-page.css';

const AdminThemePage: React.FC = () => {
    const [themes, setThemes] = useState<AdminThemeSummaryRetrieveResponse[]>([]);
    const navigate = useNavigate();
    const location = useLocation();

    const handleError = (err: any) => {
        if (isLoginRequiredError(err)) {
            alert('로그인이 필요해요.');
            navigate('/admin/login', { state: { from: location } });
        } else {
            const message = err.response?.data?.message || '알 수 없는 오류가 발생했습니다.';
            alert(message);
            console.error(err);
        }
    };

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await fetchAdminThemes();
                setThemes(response.themes);
            } catch (error) {
                handleError(error);
            }
        };
        fetchData();
    }, []);

    const handleAddClick = () => {
        navigate('/admin/theme/edit/new');
    };
    
    const handleManageClick = (themeId: string) => {
        navigate(`/admin/theme/edit/${themeId}`);
    };

    return (
        <div className="admin-theme-container">
            <h2 className="page-title">테마 관리</h2>
            <div className="section-card">
                <div className="table-header">
                    <button className="btn btn-primary" onClick={handleAddClick}>테마 추가</button>
                </div>
                <div className="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>이름</th>
                                <th>난이도</th>
                                <th>1인당 요금</th>
                                <th>공개여부</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            {themes.map(theme => (
                                <tr key={theme.id}>
                                    <td>{theme.name}</td>
                                    <td>{theme.difficulty}</td>
                                    <td>{theme.price.toLocaleString()}원</td>
                                    <td>{theme.isActive ? '공개' : '비공개'}</td>
                                    <td>
                                        <button className="btn btn-secondary" onClick={() => handleManageClick(theme.id)}>관리</button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
};

export default AdminThemePage;
