import { useState } from "react";
import { Env } from "../../models/Env";
import Highlight from 'react-highlight'
import 'highlight.js/styles/far.css'
import { Builder } from "../../builders";
import { Config } from "../../models/Config";
import { ConfigTemplate } from "./ConfigTemplate";


export function Content(props: { config: Config, env: Env, onTemplateSaved: (newContent: string) => void }) {
    const [selectTab, setTab] = useState(ContentType.Env);

    return (
        <>
            <ContentTabs onSelected={(id) => setTab(id)} />
            <div className="">
                {selectTab == ContentType.Env ? (<ContentParams env={props.env} />) : ""}
                {selectTab == ContentType.Json ? (<ConfigTemplate config={props.config} onSaved={props.onTemplateSaved} />) : ""}
                {selectTab == ContentType.Raw ? (<ContentRaw config={props.config} env={props.env} />) : ""}
                {selectTab == ContentType.Test ? (<ContentTest config={props.config} env={props.env} />) : ""}
            </div>
        </>
    );
}

enum ContentType {
    Env = 0,
    Json = 1,
    Raw = 2,
    Test = 3
}

function ContentTabs(props: { onSelected: (id: ContentType) => void }) {
    const [selectTab, setSelect] = useState(ContentType.Env);

    function clickHandler(type: ContentType) {
        setSelect(type);
        props.onSelected(type);
    }

    function isActive(type: ContentType): string {
        return type == selectTab ? " active" : " ";
    }

    return (
        <ul className="nav nav-pills nav-fill">
            <li className="nav-item">
                <a className={"nav-link" + isActive(ContentType.Env)} aria-current="page" href="#" onClick={() => clickHandler(ContentType.Env)}>Env</a>
            </li>
            <li className="nav-item">
                <a className={"nav-link" + isActive(ContentType.Json)} href="#" onClick={() => clickHandler(ContentType.Json)} >Content Template</a>
            </li>
            <li className="nav-item">
                <a className={"nav-link" + isActive(ContentType.Raw)} href="#" onClick={() => clickHandler(ContentType.Raw)}>Raw template</a>
            </li>
            <li className="nav-item">
                <a className={"nav-link" + isActive(ContentType.Test)} href="#" onClick={() => clickHandler(ContentType.Test)}>Test-filled template</a>
            </li>
        </ul>
    )
}

function ContentRaw(props: { config: Config, env: Env }) {
    const envsXml = Builder.getEnvs(props.config.envs);
    const templateContent = props.config.template.content;

    const xml = `<engine>
${envsXml}
    <template>
${templateContent}
    </template>
</engine>`;

    return (
        <>
            <Highlight className="language-xml">
                {xml}
            </Highlight>
        </>
    )
}

function ContentTest(props: { config: Config, env: Env }) {
    const [selectedEnvId, setSelectedEnvId] = useState(props.env.id);
    const selectedEnv = props.config.envs.find(e => e.id === selectedEnvId) ?? props.env;

    const filledTemplate = fillTemplate(props.config, selectedEnv);

    return (
        <>
            <div className="mb-2">
                <label className="form-label">Select Environment:</label>
                <select 
                    className="form-select w-auto d-inline-block" 
                    value={selectedEnvId}
                    onChange={(e) => setSelectedEnvId(Number(e.target.value))}
                >
                    {props.config.envs.map(env => (
                        <option key={env.id} value={env.id}>{env.name}</option>
                    ))}
                </select>
            </div>
            <Highlight className="language-json">
                {filledTemplate}
            </Highlight>
        </>
    )
}

function fillTemplate(config: Config, env: Env): string {
    const defaultEnv = config.envs.find(e => e.name === "DEFAULT");
    const paramMap = new Map<string, string>();

    // First, load DEFAULT values as fallback
    if (defaultEnv) {
        for (const param of defaultEnv.params) {
            if (param.name && param.value !== undefined) {
                paramMap.set(param.name, param.value);
            }
        }
    }

    // Then, override with selected environment values (precedence)
    for (const param of env.params) {
        if (param.name && param.value !== undefined) {
            paramMap.set(param.name, param.value);
        }
    }

    let filledTemplate = config.template.content;
    const placeholderRegex = /@(\w+)@/g;

    filledTemplate = filledTemplate.replace(placeholderRegex, (_, paramName) => {
        if (paramName === Config.ENV_NAME_PARAM) {
            return env.name ?? "--NO-VALUE--";
        }
        return paramMap.get(paramName) ?? "--NO-VALUE--";
    });

    return filledTemplate;
}

function ContentParams(props: { env: Env }) {
    const bldr = Builder.getEnv(props.env);

    return (
        <Highlight className="language-xml">
            {bldr.build()}
        </Highlight>
    )
}