import { Component, createSignal, For, Show, Signal } from "solid-js";
import { weatherIcons } from "./iconConsts";
import "../../css/weatherIcons.css";
import { WeatherGlyph } from "./WeatherGlyph";

export const IconInputs: Component<{cities: string[]; weatherIconsSignal: Signal<Record<string, string>>}> = (props) => {
    const [icons, setIcons] = props.weatherIconsSignal;
    const [selected, setSelected] = createSignal(weatherIcons[0]);
    const assign = (city: string) => setIcons({...icons(), [city]: selected()});
    const clear = (city: string) => { const next = {...icons()}; delete next[city]; setIcons(next); };
    const applyAll = () => setIcons(Object.fromEntries(props.cities.map(city => [city, selected()])));

    return <section class="symbolEditor">
        <div class="symbolEditorHeading"><div><strong>Weather symbols</strong><p class="fieldHint">Choose one symbol, apply it broadly, then update the exceptions below.</p></div><div class="bulkSymbol"><span class="selectedPreview"><WeatherGlyph glyph={selected()} size={40} tone="inverse"/></span><button type="button" onClick={applyAll}>Apply to all cities</button></div></div>
        <div class="symbolPalette" role="radiogroup" aria-label="Choose weather symbol"><For each={weatherIcons}>{icon => <button type="button" role="radio" aria-checked={selected() === icon} aria-label={`Weather symbol ${icon}`} class="weatherIconButton" classList={{selected: selected() === icon}} onClick={() => setSelected(icon)}><WeatherGlyph glyph={icon} size={40} tone={selected() === icon ? "inverse" : "default"}/></button>}</For></div>
        <div class="assignmentHeading"><strong>City assignments</strong><span>Use the selected symbol for each exception.</span></div>
        <div class="citySymbols"><For each={props.cities}>{city => <div class="citySymbolRow"><span class="cityName">{city}</span><span class="currentSymbol" classList={{empty: !icons()[city]}}><Show when={icons()[city]} fallback="—">{icon => <WeatherGlyph glyph={icon()} size={40}/>}</Show></span><button type="button" class="assignAction" onClick={() => assign(city)}>Use selected</button><button type="button" class="clearSymbol" disabled={!icons()[city]} onClick={() => clear(city)} aria-label={`Clear ${city} symbol`}>×</button></div>}</For></div>
    </section>;
};
