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";
import { ToastContainer, toast } from 'react-toastify';

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}`, translations)
            .then(res => {
                if (res.data.status === 'Updated') {
                    toast.success('Translations updated!');
                } else {
                    toast.error('Something went wrong!');
                }
            })
            .catch(err => toast.error('Failed to update translations: ' + err.message));
    };

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

    return (
        <Layout>
            <ProtectedRoute allowedRoles={[UserRole.ADMIN, UserRole.POWERUSER]}>
                <div className="mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="sticky top-0 z-10 bg-white shadow-md py-4 px-4">
                        <div className="flex justify-between items-center">
                            <h1 className="text-xl font-semibold leading-tight text-gray-800">Edit Translations</h1>
                            <div className="flex items-center space-x-4">
                                <button
                                    onClick={handleSave}
                                    className="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                                >
                                    Save Changes
                                </button>
                                <div>
                                    <select
                                        id="locale-select"
                                        onChange={e => setLocale(e.target.value)}
                                        value={locale}
                                        className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
                                    >
                                        {locales.map(l => (
                                            <option key={l} value={l}>{l.toUpperCase()}</option>
                                        ))}
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="overflow-x-auto relative shadow-md sm:rounded-lg">
                        <table className="w-full text-sm text-left text-gray-500">
                            <thead className="text-xs text-gray-700 uppercase bg-gray-50">
                                <tr>
                                    <th scope="col" className="py-3 px-6 w-2/12">Key</th> {/* Adjusted width */}
                                    <th scope="col" className="py-3 px-6 w-3/12">Base Translation</th> {/* Adjusted width */}
                                    <th scope="col" className="py-3 px-6 w-7/12">Translation</th> {/* Adjusted width */}
                                </tr>
                            </thead>
                            <tbody>
                                {Object.entries(baseTranslations).map(([key, baseValue]) => (
                                    <tr key={key} className="bg-white border-b hover:bg-gray-50">
                                        <td className="py-4 px-6 font-medium text-gray-900 whitespace-nowrap text-ellipsis">{key}</td>
                                        <td className="py-4 px-6">{baseValue}</td>
                                        <td className="py-4 px-6">
                                            <textarea
                                                value={translations[key] || ''}
                                                placeholder='Въведи превод...'
                                                onChange={e => handleChange(key, e.target.value)}
                                                className="block w-60hv text-base px-2 py-1 border border-gray-300 focus:ring-blue-500 focus:border-blue-500 rounded placeholder-gray-400"
                                                style={{ width: '100%', resize: 'both', transition: 'box-shadow .3s', boxShadow: translations[key] ? '0 0 0px 1px rgba(59, 130, 246, 0.5)' : 'none' }}
                                            />

                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                    {/* <button
                        onClick={handleSave}
                        className="mt-4 inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                        Save Changes
                    </button> */}
                </div>
            </ProtectedRoute>
        </Layout>
    );
};

export default AdminTranslations;
