import axiosInstance from '../../../src/axiosSecure';
import { useState, useEffect } from 'react';
import ProtectedRoute from "../../../components/protectedRoute";
import { UserRole } from "@prisma/client";

// Simulate importing locales from a config or define directly here
const locales = ['en', 'bg', 'ru'];

const AdminTranslations = () => {
    const [translations, setTranslations] = useState({});
    const [locale, setLocale] = useState('en');

    useEffect(() => {
        axiosInstance.get(`/api/translations/${locale}`).then(res => setTranslations(res.data));
    }, [locale]);

    const handleSave = () => {
        axiosInstance.post(`/api/translations/${locale}/modified`, translations)
            .then(res => {
                if (res.data.status === 'Updated') {
                    alert('Translations updated!');
                }
            });
    };

    const handleChange = (key, value) => {
        setTranslations(prev => ({ ...prev, [key]: value }));
    };

    return (
        <ProtectedRoute allowedRoles={[UserRole.ADMIN, UserRole.POWERUSER]}>
            <div>
                <h1>Edit Translations</h1>
                <select onChange={e => setLocale(e.target.value)} value={locale}>
                    {locales.map(l => (
                        <option key={l} value={l}>{l.toUpperCase()}</option>
                    ))}
                </select>
                <table>
                    <tbody>
                        {Object.entries(translations).map(([key, value]) => (
                            <tr key={key}>
                                <td>{key}</td>
                                <td>
                                    <input
                                        type="text"
                                        value={value}
                                        onChange={e => handleChange(key, e.target.value)}
                                        style={{ width: '100%' }}
                                    />
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
                <button onClick={handleSave}>Save Changes</button>
            </div>
        </ProtectedRoute>
    );
};

export default AdminTranslations;
