<script lang="ts">
    import { derived, writable } from 'svelte/store'
    import { setContext } from 'svelte'
    import { Derived } from './calcul'
    import { page } from '$app/state'
    import { resolve } from '$app/paths'
    import ExclamationTriangle from '../../../ExclamationTriangle.svelte'
    import Question from '../../../Question.svelte'
    import type {
        Communaute,
        Prm,
        Profil,
        SimulationCommunaute,
    } from '../../../../grain-types'
    import { goto } from '$app/navigation'

    let props = $props()
    type Data = {
        nom?: string
        porteur?: string
        adresse?: string
        tel?: string
        id?: string
        communaute?: Communaute & { isMoving?: boolean }
        img?: string
        simulation: SimulationCommunaute
        prms?: Prm[]
        profils?: Profil[]
        accesParticuliers?: boolean
        expert?: boolean
        email?: string
    }

    let data: Data = $derived(props.data)
    let simulation = $derived(new Derived(data.simulation))
    let profils_modified = writable(false)
    let prms_modified = writable(false)
    let expert = $derived(writable(data.expert))
    let needsSaving = $derived(
        derived(
            [simulation.modified, profils_modified, prms_modified],
            ([$mod, $profils, $prms]) => {
                console.log('derived', $mod)
                return $mod || $profils || $prms
            }
        )
    )
    let communaute = $derived(writable(data.communaute))
    $effect(() => {
        setContext('simulation', simulation)
        setContext('profils', writable(data.profils || []))
        setContext('prms', writable(data.prms || []))
        setContext('profils_modified', profils_modified)
        setContext('prms_modified', writable(data.prms || []))
        setContext('communaute', communaute)
        setContext('expert', expert)
        setContext('pvgis', writable({ pvgis: null, loading: false }))
        setContext(
            'soleil',
            writable({
                hourly: {
                    x: <string[]>[],
                    y: <number[]>[],
                },
                daily: {
                    x: <string[]>[],
                    y: <number[]>[],
                },
                weekly: {
                    x: <string[]>[],
                    y: <number[]>[],
                },
                x: <string[]>[],
                y: <number[]>[],
                type: 'bar',
                line: {
                    color: '#ffbf00',
                    width: 1,
                },
                marker: {
                    color: '#ffbf00',
                    width: 1,
                },
                name: 'Production solaire',
                bucket: 1,
            })
        )
    })
    const compteActive = $derived(page.route.id?.endsWith('/finances') ?? false)
    const descriptionActive = $derived(
        page.route.id?.endsWith('/description') ?? false
    )
    const banqueActive = $derived(page.route.id?.endsWith('/banque') ?? false)
    const expertActive = $derived(page.route.id?.endsWith('/expert') ?? false)
    const simuActive = $derived(page.route.id?.endsWith('/simulation') ?? false)
    const syntheseActive = $derived(
        !compteActive &&
            !descriptionActive &&
            !banqueActive &&
            !expertActive &&
            !simuActive
    )
    let menuElt: null | HTMLElement = null

    const surface_kwc = 4.5
    let surface = $derived(surface_kwc * data.simulation.puissance)

    function onTauxChange(ev: Event) {
        let t = ev.target as HTMLInputElement
        console.log(ev, t.valueAsNumber)
        if (t.valueAsNumber > 100) {
            t.valueAsNumber = 100
        }
    }

    function onSurfaceChange(ev: Event) {
        if (simulation) {
            surface = (ev.target as HTMLInputElement).valueAsNumber
            simulation.p.puissance.set(surface / surface_kwc)
        }
    }

    //     function onRatioChange(ev: Event) {
    //         if(simulation) {
    //             surface_kwc = (ev.target as HTMLInputElement).valueAsNumber
    //             surface = get(simulation.p.puissance) * surface_kwc
    //         }
    //     }

    function onPuissanceChange(ev: Event) {
        if (simulation) {
            simulation.p.puissance.set(
                (ev.target as HTMLInputElement).valueAsNumber
            )
            surface = $puissance * surface_kwc
        }
    }
    const puissance = $derived(simulation?.p.puissance)
    const autoconso = $derived(simulation?.p.autoconso)
    const autoprod = $derived(simulation?.p.autoprod)
    const cout = $derived(simulation?.p.cout_elec)
    const prix = $derived(simulation.p.prix)
    const apport = $derived(simulation.p.apport)
    const interet = $derived(simulation.p.interet)
    const echeances = $derived(simulation.p.echeances)
    const N = $derived(simulation.N)

    async function save_() {
        let resp = await fetch(`/grain/projet/${props.params.id}?/save`, {
            method: 'POST',
            headers: {
                'content-type': 'application/x-www-form-urlencoded',
            },
            body:
                'data=' +
                encodeURIComponent(
                    JSON.stringify(<Data>{
                        id: data.id,
                        nom: data.nom,
                        simulation: simulation.s,
                        prms: data.prms,
                        profils: data.profils,
                        communaute: $communaute,
                        expert: $expert,
                    })
                ),
        })
        let id = await resp.json()
        console.log('ID', id)
        simulation.modified.set(false)
        profils_modified.set(false)
        prms_modified.set(false)
        return JSON.parse(id.data)[0]
    }

    async function save() {
        let id: string | null = await save_()
        console.log('SAVED', id)
        if (id && id != data.id) {
            data.id = id
            goto(resolve('/grain/projet/[id]', { id }))
        }
    }
</script>

<div class="w-full flex-1 h-screen lg:h-full">
    <div class="drawer lg:drawer-open h-full">
        <input id="grain-menu" type="checkbox" class="drawer-toggle" />
        <div
            class="drawer-side shadow-xl z-200 lg:z-0 overflow-y-auto h-screen lg:h-full">
            <label
                for="grain-menu"
                aria-label="close sidebar"
                class="drawer-overlay"></label>
            <div class="pt-10 px-5 bg-base-100 min-h-screen lg:min-h-0 lg:h-0">
                <div class="lg:hidden ms-3 me-auto">
                    <h1 class="text-4xl">{data.nom}</h1>
                </div>

                <input
                    id="text-nom"
                    data-testid="text-nom"
                    type="text"
                    class="input input-lg"
                    bind:value={data.nom}
                    placeholder="Nouveau projet" />
                <form onsubmit={save}>
                    <button
                        id="sauvegarder"
                        data-testid="sauvegarder"
                        class="my-2 btn btn-sm btn-primary"
                        disabled={!$needsSaving}>Sauvegarder</button>
                </form>
                {#if data.email}
                    <div class="flex gap-2 my-5">
                        <input
                            class="checkbox"
                            type="checkbox"
                            role="switch"
                            id="expertsw"
                            data-testid="expertsw"
                            bind:checked={$expert} />
                        <label class="label ms" for="expertsw"
                            >Niveau expert</label>
                    </div>
                {/if}
                <h2 class="mt-5">Communauté</h2>
                <div class="my-3 flex flex-col gap-1">
                    <label class="label" for="puissance"
                        >Puissance totale (kWc)</label>
                    <input
                        class="input input-sm"
                        type="number"
                        id="puissance"
                        min="1"
                        max="3000"
                        value={$puissance}
                        onchange={onPuissanceChange} />
                    {#if data.simulation.puissance > 3000}<div
                            class="text-warning my-5 max-w-82">
                            <ExclamationTriangle />&nbsp;Une communauté
                            d'autoconsommation ne peut dépasser plus de 3MWc.
                            Les résultats obtenus seront donc purement
                            hypothétiques.
                        </div>{/if}
                </div>
                <div class="my-3 flex flex-col gap-1">
                    <label class="label" for="surface"
                        >Surface totale (m²)<Question
                            datatip="Estimation de la surface de modules photovoltaïques en fonction de la puissance et du ratio (configurable en mode expert)." />
                    </label>
                    <input
                        class="input input-sm"
                        type="number"
                        id="surface"
                        min="1"
                        value={surface}
                        onchange={onSurfaceChange} />
                </div>
                <div class="mb-3 flex flex-col">
                    <label class="label" for="autoconso"
                        >Taux d'autoconsommation (%)<Question
                            datatip="Pourcentage de la production consommée localement, à valider plus finement dans l'onglet Simulation. C'est la valeur que l'application Coturnix optimise." />
                    </label>
                    <div>
                        <input
                            class="range range-sm me-4 my-3 max-w-64"
                            type="range"
                            id="autoconso"
                            bind:value={$autoconso} />{$autoconso}%
                    </div>
                </div>
                <div class="mb-3 flex flex-col gap-1">
                    <label class="label" for="autoprod"
                        >Taux d'autoproduction (%) <Question
                            datatip="Pourcentage des consommations venant de sources locales, à valider plus finement dans l'onglet Simulation." />
                    </label>
                    <div class="d-flex">
                        <input
                            class="range range-sm me-4 my-3 max-w-64"
                            type="range"
                            id="autoprod"
                            bind:value={$autoprod} />{$autoprod}%
                    </div>
                </div>
                <div class="mb-3 flex flex-col gap-1">
                    <label class="label" for="prix"
                        >Prix d'achat fournisseur (€/kWh)<Question
                            datatip="Prix d'achat moyen des consommateurs de la communauté à leur fournisseur d'électricité habituel (par exemple EDF)." />
                    </label>
                    <input
                        class="input input-sm"
                        type="number"
                        step="0.01"
                        min="0"
                        id="coutElec"
                        bind:value={$cout} />
                </div>
                <div class="mb-3 flex flex-col gap-1">
                    <label class="label" for="prix"
                        >Prix de vente local (€/kWh)<Question
                            datatip="Hypothèse sur le prix de vente moyen. Dans Coturnix, les producteurs et les consommateurs choisissent leurs prix acceptables, et Coturnix calcule à chaque instant le prix qui maximise la valeur totale créée par la communauté." />
                    </label>
                    <input
                        class="input input-sm"
                        type="number"
                        step="0.01"
                        min="0"
                        id="prix"
                        bind:value={$prix} />
                </div>
                <div class="mb-3 flex flex-col gap-1">
                    <label class="label" for="echeances"
                        >Durée d'analyse (an)</label>
                    <input
                        class="input input-sm"
                        type="number"
                        id="echeances"
                        min="0"
                        bind:value={$N} />
                </div>

                <h2 class="mt-5 text-2xl">Financement</h2>
                <div class="my-3 flex flex-col gap-1">
                    <label class="label" for="apport">Apport initial (€)</label>
                    <input
                        class="input input-sm"
                        type="number"
                        id="apport"
                        min="0"
                        step="1000"
                        bind:value={$apport} />
                </div>
                <div class="mb-3 flex flex-col gap-1">
                    <label class="label" for="interet">Taux d'intérêt(%)</label>
                    <input
                        class="input input-sm"
                        type="number"
                        step="0.1"
                        id="interet"
                        min="0"
                        max="100"
                        onchange={onTauxChange}
                        onkeyup={onTauxChange}
                        bind:value={$interet} />
                </div>
                <div class="mb-3 flex flex-col gap-1">
                    <label class="label" for="echeances"
                        >Nombre d'échéances (en mois)</label>
                    <input
                        class="input input-sm"
                        type="number"
                        id="echeances"
                        min="0"
                        bind:value={$echeances} />
                </div>
                {#if data.id}
                    <form method="POST" action="?/del" class="pb-5">
                        <button class="my-2 btn btn-outline btn-primary"
                            >Supprimer</button>
                    </form>
                {/if}
            </div>
        </div>

        <div class="drawer-content flex flex-col px-5 overflow-y-auto h-full">
            <div class="flex sticky top-0 pt-5 pb-5 bg-base-100 relative z-100">
                <label
                    for="grain-menu"
                    class="btn btn-ghost drawer-button lg:hidden">
                    <div tabindex="0" role="button">
                        <svg
                            xmlns="http://www.w3.org/2000/svg"
                            class="h-5 w-5"
                            fill="none"
                            viewBox="0 0 24 24"
                            stroke="currentColor">
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M4 6h16M4 12h16M4 18h7" />
                        </svg>
                    </div>
                </label>
                <div>
                    <div role="tablist" class="tabs tabs-border">
                        <a
                            href={resolve('/grain/projet/[id]', {
                                id: data.id || 'nouveau',
                            })}
                            class="tab"
                            class:tab-active={syntheseActive}
                            id="synthese-tab"
                            data-testid="synthese-tab"
                            type="button"
                            role="tab">Synthèse</a>
                        <a
                            href={resolve('/grain/projet/[id]/finances', {
                                id: data.id || 'nouveau',
                            })}
                            class="tab"
                            class:tab-active={compteActive}
                            id="finances-tab"
                            data-testid="finances-tab"
                            type="button"
                            role="tab">Détails financiers</a>
                        <a
                            href={resolve('/grain/projet/[id]/description', {
                                id: data.id || 'nouveau',
                            })}
                            class="tab"
                            class:tab-active={descriptionActive}
                            id="profile-tab"
                            data-testid="profile-tab"
                            type="button"
                            role="tab">Description</a>

                        <a
                            href={resolve('/grain/projet/[id]/banque', {
                                id: data.id || 'nouveau',
                            })}
                            class="tab"
                            class:tab-active={banqueActive}
                            id="banque-tab"
                            data-testid="banque-tab"
                            type="button"
                            role="tab">Emprunt</a>

                        {#if $expert}
                            <a
                                href={resolve('/grain/projet/[id]/expert', {
                                    id: data.id || 'nouveau',
                                })}
                                class="tab"
                                class:tab-active={expertActive}
                                id="expert-tab"
                                data-testid="expert-tab"
                                type="button"
                                role="tab">Mode expert</a>
                        {/if}

                        <a
                            href={resolve('/grain/projet/[id]/simulation', {
                                id: data.id || 'nouveau',
                            })}
                            class="tab"
                            class:tab-active={simuActive}
                            id="prm-tab"
                            data-testid="prm-tab"
                            type="button"
                            role="tab">Simulation</a>
                    </div>
                </div>
            </div>
            <div class="h-0">
                {@render props.children()}
            </div>
        </div>
    </div>
</div>
