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

const locales = ['bg', 'en', 'ru'];

const AdminTranslations = () => {
    const [translations, setTranslations] = useState({});
    // set locale to the current locale by default. get it from the useRouter
    let router = useRouter();

    const [locale, setLocale] = useState(router.locale);
    const [baseTranslations, setBaseTranslations] = useState(locales[0]);

    useEffect(() => {
        axiosInstance.get(`/api/translations/${locale}?flat=true`).then(res => setTranslations(res.data));
        axiosInstance.get(`/api/translations/${locales[0]}?flat=true`).then(res => setBaseTranslations(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 (
        <Layout>

            <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>{baseTranslations[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>
        </Layout>
    );
};

export default AdminTranslations;
