{% extends 'base.html' %}

{% block content %}
<script src="//unpkg.com/alpinejs" defer></script>

<div class="max-w-5xl mx-auto px-4">
    <form method="post" action="{{ url_for('blog.save_image') }}" id="postForm" class="space-y-6"
        enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

        <h1 class="text-2xl font-bold mb-6 dark:text-white">{{ 'Edit' if is_edit else 'New' }} Post</h1>
        <!-- Title -->
        <div>
            <label class="label">Title (use searchable Object Name like M100, etc.)</label>
            <input name="title" type="text" value="{{ image.title if is_edit else '' }}" required
                class="input_container" />
        </div>

        {% if is_edit %}
        <input type="hidden" name="image_id" value="{{ image.id }}">
        {% endif %}

        <!-- Short Description -->
        <div>
            <label class="label">Short Description (Will be displayed next to the title...)</label>
            <input name="short_description" type="text" value="{{ image.short_description if is_edit else '' }}"
                required class="input_container" />
        </div>

        <!-- Description -->
        <div>
            <label class="label">Description (longer paragraph if required...)</label>
            <textarea name="description" required style="min-height:200px;"
                class="input_container">{{ image.description if is_edit else '' }}</textarea>
        </div>

        <!-- Image Path -->
        <div x-data="{ imagePath: '{{ image.image_path if is_edit and image.image_path else '' }}' }" class="space-y-2">
            {% if is_edit %}
            <label class="label block text-sm font-medium text-gray-700 dark:text-gray-300">Current Image</label>
            <template x-if="imagePath">
                <div
                    class="flex items-center justify-between bg-gray-100 dark:bg-gray-800 px-3 py-2 rounded text-sm text-gray-700 dark:text-gray-300">
                    <input type="text" x-model="imagePath" name="prev_img" class="w-full truncate" readonly />
                </div>
            </template>

            <!-- Redo Plate Solving Checkbox -->
            <label class="inline-flex items-center mt-2 text-sm text-gray-700 dark:text-gray-300">
                <input type="checkbox" id="redo_plate_solve" name="redo_plate_solve"
                    class="form-checkbox h-4 w-4 text-blue-600 rounded mr-2">
                Redo Plate Solving
            </label>
            <label class="inline-flex items-center mt-2 text-sm text-gray-700 dark:text-gray-300">
                <input type="checkbox" id="regenerate_overlays" name="regenerate_overlays"
                    class="form-checkbox h-4 w-4 text-blue-600 rounded mr-2">
                Regenerate Overlays
            </label>
            {% endif %}

            <label class="label block text-sm font-medium text-gray-700 dark:text-gray-300 mt-4">Upload Image</label>
            <input name="image_path" type="file" accept=".png,.jpg,.jpeg" class="block w-full text-sm text-gray-500
        file:mr-4 file:py-2 file:px-4
        file:rounded-full file:border-0
        file:text-sm file:font-semibold
        file:bg-blue-50 file:text-blue-700
        hover:file:bg-blue-100" {% if not is_edit %} required {% endif %} />

            <label class="label block text-sm font-medium text-gray-700 dark:text-gray-300 mt-4">
                <p>Upload FITS/XISF file</p>
                <p>[The Jpeg should be of same
                    dimension as the fits/XISF file otherwise the annotation will be incorrect!]</p>
            </label>
            <input name="fits_file" type="file" accept=".fits,.fit,.xisf" class="block w-full text-sm text-gray-500
                 file:mr-4 file:py-2 file:px-4
                 file:rounded-full file:border-0
                 file:text-sm file:font-semibold
                 file:bg-blue-50 file:text-blue-700
                 hover:file:bg-blue-100" {% if not is_edit %} required {% endif %}/>
            
            <div id="lightFramesContainer" class="my-4">
                <label class="label block text-sm font-medium text-gray-700 dark:text-gray-300 mt-4">
                    <p>Upload WBPP log file from Pixinsight [optional]</p>
                </label>
                <div class="flex space-x-2 items-center">
                    <input id="wbppLogInput"name="wbpp_log_file" type="file" accept=".log" class="block w-full text-sm text-gray-500
                        file:mr-4 file:py-2 file:px-4
                        file:rounded-full file:border-0
                        file:text-sm file:font-semibold
                        file:bg-blue-50 file:text-blue-700
                        hover:file:bg-blue-100"/>
                </div>

                <label class="label block text-sm font-medium text-gray-700 dark:text-gray-300 mt-4">
                    <p>Extract Metadata from Light Frames [optional]</p>
                </label>

                <div class="flex space-x-2 items-center">
                    <input
                        type="file"
                        id="lightFramesInput"
                        multiple
                        accept=".fits,.fit"
                        class="flex-1 text-sm text-gray-500
                            file:mr-4 file:py-2 file:px-4
                            file:rounded-full file:border-0
                            file:text-sm file:font-semibold
                            file:bg-blue-50 file:text-blue-700
                            hover:file:bg-blue-100"
                    />
                    <button
                        id="analyseLightsBtn"
                        type="button"
                        class="px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                    >
                        Extract Fits Metadata + WBPP Log and add
                    </button>
                </div>
                <input type="hidden" name="meta_store" id="meta_store_input" value="" />
            </div>

            <h3 class="mt-4 font-semibold text-gray-700 dark:text-white">Constant Keywords</h3>
            <div class="mt-2 border rounded max-h-96 overflow-y-auto text-gray-700 dark:text-gray-300">
                <table id="constantsTable" class="min-w-full text-sm border-collapse">
                    <thead class="sticky top-0 bg-gray-100 text-black">
                        <tr>
                            <th class="border px-2 py-1 text-left">Keyword</th>
                            <th class="border px-2 py-1 text-left">Value</th>
                            <th class="border px-2 py-1 text-left">Comment</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

            <h3 class="mt-4 font-semibold  text-gray-700 dark:text-gray-300">Variable Keywords</h3>
            <div class="mt-2 border rounded max-h-96 overflow-y-auto text-gray-700 dark:text-gray-300">
                <table id="variablesTable" class="min-w-full text-sm border-collapse">
                    <thead class="sticky top-0 bg-gray-100"></thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>

        <!-- Location Row -->
        <div class="mb-6">
            <div class="gap-4 flex flex-wrap ...">
                <div class="w-64 flex-auto ...">
                    <label class="label">Location</label>
                    <input name="location" id="locationInput" class="input_container"
                        value="{{ image.location if is_edit else '' }}" required />
                </div>

                <div class="w-36 flex-none ...">
                    <label class="label">Latitude</label>
                    <input name="location_latitude" id="location_lat" class="input_container"
                        value="{{ image.location_latitude if is_edit else '' }}" />
                </div>

                <div class="w-36 flex-none ...">
                    <label class="label">Longitude</label>
                    <input name="location_longitude" id="location_lng" class="input_container"
                        value="{{ image.location_longitude if is_edit else '' }}" />
                </div>

                <div class="w-36 flex-none ...">
                    <label class="label">Elevation</label>
                    <input name="location_elevation" id="location_elev" class="input_container"
                        value="{{ image.location_elevation if is_edit else '' }}" />
                </div>
            </div>
        </div>

        <!-- Guide Log -->
        <div x-data="{ logs: '{{ image.guide_log if is_edit and image.guide_log else '' }}' }" class="space-y-2">
            {% if is_edit %}
            <label class="label block text-sm font-medium text-gray-700 dark:text-gray-300">Current Guide Logs</label>

            <template x-if="logs">
                <div
                    class="flex items-center justify-between bg-gray-100 dark:bg-gray-800 px-3 py-2 rounded text-sm text-gray-700 dark:text-gray-300">
                    <input type="text" x-model="logs" name="prev_guide_logs" class="w-full truncate" readonly />
                </div>
            </template>

            <!-- Redo Graphs -->
            <label class="inline-flex items-center mt-2 text-sm text-gray-700 dark:text-gray-300">
                <input type="checkbox" name="redo_graphs" class="form-checkbox h-4 w-4 text-blue-600 rounded mr-2">
                Redo Guiding Graphs
            </label>
            {% endif %}

            <label class="label block text-sm font-medium text-gray-700 dark:text-gray-300 mt-4">Upload Guide
                Logs</label>
            <input name="guide_logs" type="file" multiple accept=".txt" class="block w-full text-sm text-gray-500
        file:mr-4 file:py-2 file:px-4
        file:rounded-full file:border-0
        file:text-sm file:font-semibold
        file:bg-blue-50 file:text-blue-700
        hover:file:bg-blue-100" />
        </div>

        <h5 class="label">Created On</h5>
        <div class="gap-4 flex">
            <input type="date" class="input_container" name="created_at"
                value="{% if is_edit %}{{ image.created_at.strftime('%Y-%m-%d') }}{% else %}{{ now().date() }}{% endif %}">
        </div>

        <h5 class="label">Capture Dates</h5>
        <div class="gap-4 flex">
            <input type="date" id="datePicker" class="input_container">
            <button type="button"
                class="inline-block px-4 py-2 text-sm font-medium text-white bg-red-600 rounded hover:bg-red-700"
                id="addDateBtn">Add</button>
        </div>

        <ul id="dateList"></ul>
        <input type="hidden" name="capture_dates" id="captureDates">

        <h5 class="label">Image Lights</h5>
        <div class="mb-3 overflow-x-auto">
            <table id="lightsTable" class="min-w-[980px] w-full table-auto border-separate border-spacing-y-2">
                <thead id="lightsHeader">
                    <tr class="text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                        <th class="w-56 pr-4 text-left font-semibold">Filter</th>
                        <th class="w-32 pr-4 text-left font-semibold">Frames</th>
                        <th class="w-36 pr-4 text-left font-semibold">Exposure (s)</th>
                        <th class="w-32 pr-4 text-left font-semibold">Gain</th>
                        <th class="w-32 pr-4 text-left font-semibold">Offset</th>
                        <th class="w-32 pr-4 text-left font-semibold">Temp (C)</th>
                        <th class="w-24 text-left font-semibold"></th>
                    </tr>
                </thead>
                <tbody id="lightsContainer" {% if not is_edit %} required {% endif %}></tbody>
            </table>
        </div>
        <button type="button"
            class="inline-block px-4 py-2 text-sm font-medium text-white bg-red-600 rounded hover:bg-red-700"
            id="addLightBtn">Add Light</button>

        <div class="gap-4 flex ">
            <div class="w-64 flex-auto ">
                <label class="label">Camera</label>
                <select name="camera_id" class="input_container">
                    {% for c in camera %}
                    <option value="{{ c.id }}" {{'selected' if c.id == equipment.get('camera') else '' }}>{{ c.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>

            <div class="w-64 flex-auto ">
                <label class="label">Guide Camera</label>
                <select name="guide_camera_id" class="input_container">
                    {% for c in camera if c.id > 1 %}
                    <option value="{{ c.id }}" {{'selected' if c.id == equipment.get('guide_camera') else '' }}>
                        {{ c.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>

            <div class="w-64 flex-auto ">
                <label class="label">Rotator</label>
                <select name="rotator_id" class="input_container">
                    {{option_none | safe}}
                    {% for r in rotator %}
                    <option value="{{ r.id }}" {{'selected' if r.id == equipment.get('rotator') else '' }}>
                        {{ r.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
        </div>

        <div class="gap-4 flex ">
            <div class="w-64 flex-auto ">
                <label class="label">Telescope</label>
                <select name="telescope_id" class="input_container">
                    {% for t in telescope %}
                    <option value="{{ t.id }}" {{'selected' if t.id == equipment.get('telescope') else '' }}>
                        {{ t.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>

            <div class="w-64 flex-auto ...">
                <label class="label">Reducer</label>
                <select name="reducer_id" class="input_container">
                    {% for r in reducer %}
                    <option value="{{ r.id }}" {{'selected' if r.id == equipment.get('reducer') else '' }}>{{ r.name }}
                    </option>
                    {% endfor %}
                    {{option_none | safe}}
                </select>
            </div>

            <div class="w-64 flex-auto">
                <label class="label">Guider</label>
                <select name="guider_id" class="input_container">
                    {% for g in guider %}
                    <option value="{{ g.id }}" {{'selected' if g.id == equipment.get('guider') else '' }}>{{ g.name }}
                    </option>
                    {% endfor %}
                    {{option_none | safe}}
                </select>
            </div>
        </div>

        <div class="gap-4 flex ">
            <div class="w-64 flex-auto ">
                <label class="label">Mount</label>
                <select name="mount_id" class="input_container">
                    {% for m in mount %}
                    <option value="{{ m.id }}" {{'selected' if m.id == equipment.get('mount') else '' }}>{{ m.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>

            <div class="w-64 flex-auto">
                <label class="label">Tripod</label>
                <select name="tripod_id" class="input_container">
                    {% for t in tripod %}
                    <option value="{{ t.id }}" {{'selected' if t.id == equipment.get('tripod') else '' }}>{{ t.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>

            <div class="w-64 flex-auto">
                <label class="label">Flat Panel</label>
                <select name="flat_panel_id" class="input_container">
                    {% for p in flat_panel %}
                    <option value="{{ p.id }}" {{'selected' if p.id == equipment.get('flat_panel') else '' }}>
                        {{ p.name }}
                    </option>
                    {% endfor %}
                    {{option_none | safe}}
                </select>
            </div>
        </div>

        <div class="gap-4 flex">
            <div class="w-64 flex-auto">
                <label class="label">Filter Wheel</label>
                <select name="filter_wheel_id" class="input_container">
                    {% for f in filter_wheel %}
                    <option value="{{ f.id }}" {{'selected' if f.id == equipment.get('filter_wheel') else '' }}>
                        {{ f.name }}
                    </option>
                    {% endfor %}
                    {{option_none | safe}}
                </select>
            </div>

            <div class="w-64 flex-auto ...">
                <label class="label">EAF</label>
                <select name="eaf_id" class="input_container">
                    {% for e in eaf %}
                    <option value="{{ e.id }}" {{'selected' if e.id == equipment.get('eaf') else '' }}>{{ e.name }}
                    </option>
                    {% endfor %}
                    {{option_none | safe}}
                </select>
            </div>

            <div class="w-64 flex-auto ...">
                <label class="label">Dew Heater</label>
                <select name="dew_heater_id" class="input_container">
                    {% for d in dew_heater %}
                    <option value="{{ d.id }}" {{'selected' if d.id == equipment.get('dew_heater') else '' }}>
                        {{ d.name }}
                    </option>
                    {% endfor %}
                    {{option_none | safe}}
                </select>
            </div>
        </div>

        <label class="label">Software</label>
        <div class="flex ...">
            <select name="software_ids" multiple class="input_container">
                {% for s in softwares %}
                <option value="{{ s.id }}" {{'selected' if s.id in software_list else '' }}>{{ s.name }}</option>
                {% endfor %}
            </select>
        </div>


        <button class="inline-block px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded hover:bg-blue-800"
            type="submit">{{ "Edit" if is_edit else "Create" }}</button>
    </form>

    <script type="module">
        import { bindLocationInput, metaStore,
         bindLightFramesAnalyse } from "{{ url_for('static', filename='js/binds.js') }}";
        import * as fitsUtils from "{{ url_for('static', filename='js/fitsUtils.js') }}";

        const input_container_style = `w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500`;

        let dates = {{ capture_dates| safe }};

        // If dates is empty, initialize with today's date
        if (!dates || dates.length === 0) {
            const today = new Date();
            const yyyy = today.getFullYear();
            const mm = String(today.getMonth() + 1).padStart(2, '0'); // Months are 0-based
            const dd = String(today.getDate()).padStart(2, '0');
            dates = [`${yyyy}-${mm}-${dd}`]; // format as YYYY-MM-DD
        }

        function renderDateList() {
            const list = document.getElementById('dateList');
            list.innerHTML = '';
            dates.forEach((date, index) => {
                const li = document.createElement('li');
                li.className = input_container_style
                li.innerHTML = `
            <div class="flex justify-between items-center w-full">
                <span>${date}</span>
                <button 
                type="button" 
                class="remove-date ml-2 inline-flex items-center px-2 py-1 text-xs font-medium text-red-600 bg-red-100 hover:bg-red-200 rounded" 
                data-index="${index}">
                Remove
                </button>
            </div>
            `;
                list.appendChild(li);
            });

            // Update hidden input with JSON string
            document.getElementById('captureDates').value = JSON.stringify(dates);
        }

        document.getElementById('addDateBtn').onclick = () => {
            const d = document.getElementById('datePicker').value;
            if (d && !dates.includes(d)) {
                dates.push(d);
                renderDateList();
            }
        };

        // Remove date handler using event delegation
        document.getElementById('dateList').addEventListener('click', (e) => {
            if (e.target.classList.contains('remove-date')) {
                const index = parseInt(e.target.dataset.index);
                if (!isNaN(index)) {
                    dates.splice(index, 1);
                    renderDateList();
                }
            }
        });

        let idx = 0;
        const existingLights = {{ lights_json | safe }};

        function addLight(light = {}) {
            const container = document.getElementById('lightsContainer');
            const row = document.createElement('tr');
            row.dataset.idx = idx;

            // Create a temporary wrapper to insert filter options and preselect the value
            const selectHTML = `{{ filter_options | safe }}`;
            const parser = new DOMParser();
            const doc = parser.parseFromString(`<select>${selectHTML}</select>`, 'text/html');
            const select = doc.querySelector('select');
            select.name = `filter_${idx}`;
            select.className = input_container_style;

            if (light.cam_filter) {
                const matchingOption = Array.from(select.options).find(
                    (option) => option.value === light.cam_filter
                );
                if (matchingOption) {
                    matchingOption.selected = true;
                }
            }

            row.innerHTML = `
                <td class="pr-4 align-top">${select.outerHTML}</td>
                <td class="pr-4 align-top"><input name="count_${idx}" type="number" step="1" placeholder="Frames" aria-label="Frames" class="${input_container_style}" value="${light.light_count || '10'}" required></td>
                <td class="pr-4 align-top"><input name="exposure_${idx}" type="number" step="1" placeholder="Exposure (s)" aria-label="Exposure (s)" class="${input_container_style}" value="${light.exposure_time || '300'}" required></td>
                <td class="pr-4 align-top"><input name="gain_${idx}" type="number" step="1" placeholder="Gain" aria-label="Gain" class="${input_container_style}" value="${light.gain || '101'}"></td>
                <td class="pr-4 align-top"><input name="offset_${idx}" type="number" step="1" placeholder="Offset" aria-label="Offset" class="${input_container_style}" value="${light.offset_cam || '200'}"></td>
                <td class="pr-4 align-top"><input name="temperature_${idx}" type="number" step="1" placeholder="Temp (C)" aria-label="Temp (C)" class="${input_container_style}" value="${light.temperature || '-10'}"></td>
                <td class="align-top"><button type="button" class="remove-light mt-1 inline-flex items-center px-2 py-1 text-xs font-medium text-red-600 bg-red-100 hover:bg-red-200 rounded">Remove</button></td>
            `;
            container.appendChild(row);
            idx++;
        }

        document.getElementById('addLightBtn').onclick = () => addLight();

        // Remove row handler using event delegation
        document.getElementById('lightsContainer').addEventListener('click', (e) => {
            if (e.target.classList.contains('remove-light')) {
                e.target.closest('tr').remove();
            }
        });

        document.addEventListener('DOMContentLoaded', function () {
            renderDateList();
            if (existingLights.length === 0) {
                addLight(); // start with one empty row
            } else {
            existingLights.forEach(addLight); // prefill
            }

            bindLocationInput();
            bindLightFramesAnalyse();

            const redo = document.getElementById("redo_plate_solve");
            const regen = document.getElementById("regenerate_overlays");

            if (redo && regen) {
                redo.addEventListener("change", () => {
                    if (redo.checked) {
                        regen.checked = true;
                        regen.disabled = true;
                    } else {
                        regen.disabled = false;
                    }
                });
            }

            const labelStyle = document.querySelectorAll('.label');
            labelStyle.forEach(link => {
                link.className = 'block text-sm font-medium mb-1 text-gray-700 dark:text-gray-200';
            });

            const inputStyle = document.querySelectorAll('.input_container');
            inputStyle.forEach(link => {
                link.className = input_container_style;
            });

            const form = document.querySelector("#postForm"); // or give your form an id
            const fitsInput = document.querySelector("input[name='fits_file']");

            form.addEventListener("submit", async function (e) {

                const lightFramesInput = document.getElementById("lightFramesInput");
                const wbppLogInput = document.getElementById("wbppLogInput");
                // After you intercept/prepare FormData:
                if (lightFramesInput) {
                    lightFramesInput.value = "";  // clears all selected files
                }
                if (wbppLogInput) {
                    wbppLogInput.value = "";  // clears all selected files
                }
                
                // If user didn’t pick a fits/xif file → normal submit
                if (!fitsInput || fitsInput.files.length === 0) return;

                const file = fitsInput.files[0];
                const ext = file.name.toLowerCase();

                // Only intercept for XISF/FITS
                if (!(ext.endsWith(".xisf") || ext.endsWith(".fits") || ext.endsWith(".fit"))) return;

                e.preventDefault(); // Stop default full-file upload

                // --- Header extraction ---
                let headerBytes;
                let newName;
                if (ext.endsWith(".xisf")) {
                    headerBytes = await fitsUtils.readXISFHeader(file);
                    newName = file.name + ".header.xisf";
                } else {
                    // FITS: Header ends with "END" padded to 2880-byte blocks
                    headerBytes = await fitsUtils.readFITSHeader(file);
                    newName = file.name + ".header.fits";
                }

                // --- Build modified FormData with header only ---
                const formData = new FormData(form);

                // Replace full file with small header blob
                formData.set(
                    "fits_file",
                    new Blob([headerBytes], { type: "application/octet-stream" }),
                    newName   // keep filename distinct
                );

                fitsInput.value = "";

                // Submit using fetch
                const response = await fetch(form.action, {
                    method: form.method,
                    body: formData
                });

                if (response.redirected) {
                    window.location.href = response.url;
                    return;
                }

                if (!response.ok) {
                    alert("Failed to save the post.");
                    return;
                }

                window.location.reload();
            });
        });

    </script>
</div>
{%endblock%}
