<?= $this->extend("layout/main_layout"); ?>

<?= $this->section("content"); ?>
<main class="flex-1 p-6 overflow-auto"
      x-data="dailyEntry()">
    <div class="flex justify-between items-center mb-6">
        <div>
            <h1 class="text-2xl font-bold text-base-content tracking-tight">Daily Entry</h1>
            <p class="text-sm mt-1 opacity-70">Record daily QC test results</p>
        </div>
        <button @click="saveResults()"
                :disabled="saving || !canSave"
                class="btn btn-primary"
                :class="{ 'loading': saving }">
            <i class="fa-solid fa-save mr-2"></i>
            Save Results
        </button>
    </div>

    <!-- Filters -->
    <div class="bg-base-100 rounded-xl border border-base-300 shadow-sm p-4 mb-6">
        <div class="flex flex-wrap gap-4 items-end">
            <div class="form-control">
                <label class="label">
                    <span class="label-text font-medium">Date</span>
                </label>
                <input type="date"
                       x-model="date"
                       @change="fetchControls()"
                       :max="today"
                       class="input input-bordered input-sm w-40">
            </div>
            <div class="form-control">
                <label class="label">
                    <span class="label-text font-medium">Quick Date</span>
                </label>
                <div class="flex gap-2">
                    <button @click="setToday()" class="btn btn-sm btn-outline">Today</button>
                    <button @click="setYesterday()" class="btn btn-sm btn-outline">Yesterday</button>
                </div>
            </div>
            <div class="form-control">
                <label class="label">
                    <span class="label-text font-medium">Control</span>
                </label>
                <select x-model="selectedControl"
                        @change="fetchTests()"
                        class="select select-bordered select-sm w-64">
                    <option value="">Select Control</option>
                    <template x-for="control in controls" :key="control.id">
                        <option :value="control.id" x-text="control.controlName + ' (Lot: ' + control.lot + ')'"></option>
                    </template>
                </select>
            </div>
        </div>
    </div>

    <!-- Loading State -->
    <div x-show="loading" class="flex justify-center py-12">
        <span class="loading loading-spinner loading-lg text-primary"></span>
    </div>

    <!-- Empty State -->
    <div x-show="!loading && selectedControl && tests.length === 0"
         class="bg-base-100 rounded-xl border border-base-300 shadow-sm p-12 text-center">
        <i class="fa-solid fa-flask text-4xl text-base-content/20 mb-3"></i>
        <p class="text-base-content/60">No tests configured for this control</p>
        <p class="text-sm text-base-content/40 mt-1">Add tests in the Control-Tests setup</p>
    </div>

    <!-- No Control Selected -->
    <div x-show="!loading && !selectedControl"
         class="bg-base-100 rounded-xl border border-base-300 shadow-sm p-12 text-center">
        <i class="fa-solid fa-clipboard-list text-4xl text-base-content/20 mb-3"></i>
        <p class="text-base-content/60">Select a control to view tests</p>
    </div>

    <!-- Tests Grid -->
    <div x-show="!loading && selectedControl && tests.length > 0"
         class="bg-base-100 rounded-xl border border-base-300 shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
            <table class="table">
                <thead class="bg-base-200">
                    <tr>
                        <th>Test</th>
                        <th class="text-center">Mean ± 2SD</th>
                        <th class="w-32">Result</th>
                        <th class="w-56">Comment</th>
                    </tr>
                </thead>
                <tbody>
                    <template x-for="test in tests" :key="test.testId">
                        <tr class="hover">
                            <td>
                                <div class="font-medium" x-text="test.testName"></div>
                                <div class="text-xs text-base-content/50" x-text="test.testUnit || ''"></div>
                            </td>
                            <td class="text-center">
                                <div class="font-mono text-sm">
                                    <span x-text="test.mean !== null ? test.mean : '-'"></span>
                                    <span class="text-base-content/40">±</span>
                                    <span x-text="test.sd !== null ? (2 * test.sd).toFixed(2) : '-'"></span>
                                </div>
                            </td>
                            <td>
                                <input type="number"
                                       step="0.01"
                                       :placeholder="'...'"
                                       class="input input-bordered input-sm w-full font-mono"
                                       :class="getInputClass(test, $el.value)"
                                       @input.debounce.300ms="updateResult(test.testId, $el.value)"
                                       :value="test.existingResult ? test.existingResult.resValue : ''">
                            </td>
                            <td>
                                <textarea
                                      :placeholder="'Optional comment...'"
                                      rows="1"
                                      class="textarea textarea-bordered textarea-xs w-full"
                                      @input.debounce.300ms="updateComment(test.testId, $el.value)"
                                      :value="getComment(test.testId)"></textarea>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Summary -->
    <div x-show="hasChanges"
         class="mt-4 p-3 bg-info/10 rounded-lg border border-info/20 text-sm">
        <i class="fa-solid fa-info-circle mr-2"></i>
        <span x-text="changedCount"></span> test(s) with changes pending save
    </div>
</main>
<?= $this->endSection(); ?>

<?= $this->section("script"); ?>
<script>
document.addEventListener('alpine:init', () => {
    Alpine.data("dailyEntry", () => ({
        date: new Date().toISOString().split('T')[0],
        controls: [],
        selectedControl: null,
        tests: [],
        loading: false,
        saving: false,
        resultsData: {},
        commentsData: {},

        init() {
            this.fetchControls();
            this.setupKeyboard();
        },

        get today() {
            return new Date().toISOString().split('T')[0];
        },

        async fetchControls() {
            try {
                const params = new URLSearchParams({ date: this.date });
                const response = await fetch(`${BASEURL}api/entry/controls?${params}`);
                const json = await response.json();
                this.controls = json.data || [];
                // Reset selected control if it's no longer in the list
                if (this.selectedControl && !this.controls.find(c => c.id === this.selectedControl)) {
                    this.selectedControl = null;
                    this.tests = [];
                }
            } catch (e) {
                console.error('Failed to fetch controls:', e);
            }
        },

        async fetchTests() {
            if (!this.selectedControl) {
                this.tests = [];
                this.resultsData = {};
                this.commentsData = {};
                return;
            }

            this.loading = true;
            try {
                const params = new URLSearchParams({
                    date: this.date,
                    control_id: this.selectedControl
                });
                const response = await fetch(`${BASEURL}api/entry/daily?${params}`);
                const json = await response.json();
                this.tests = json.data || [];

                // Initialize resultsData and commentsData with existing values
                this.resultsData = {};
                this.commentsData = {};
                for (const test of this.tests) {
                    if (test.existingResult && test.existingResult.resValue !== null) {
                        this.resultsData[test.testId] = test.existingResult.resValue;
                    }
                    if (test.existingResult && test.existingResult.resComment) {
                        this.commentsData[test.testId] = test.existingResult.resComment;
                    }
                }
            } catch (e) {
                console.error('Failed to fetch tests:', e);
                this.$dispatch('notify', { type: 'error', message: 'Failed to load tests' });
            } finally {
                this.loading = false;
            }
        },

        async saveResults() {
            if (!this.canSave) return;

            this.saving = true;
            try {
                const results = [];
                for (const test of this.tests) {
                    const value = this.resultsData[test.testId];
                    if (value !== undefined && value !== '') {
                        results.push({
                            controlId: test.controlId,
                            testId: test.testId,
                            value: parseFloat(value)
                        });
                    }
                }

                const response = await fetch(`${BASEURL}api/entry/daily`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        date: this.date,
                        results: results
                    })
                });

                const json = await response.json();
                if (json.status === 'success') {
                    // Save comments using the returned result IDs
                    const savedIds = json.data.savedIds || [];
                    for (const item of savedIds) {
                        const comment = this.commentsData[item.testId];
                        if (comment) {
                            await this.saveComment(item.resultId, comment);
                        }
                    }

                    // Show success notification
                    this.$dispatch('notify', { type: 'success', message: json.message });
                    // Refresh data
                    this.resultsData = {};
                    this.commentsData = {};
                    await this.fetchTests();
                } else {
                    this.$dispatch('notify', { type: 'error', message: json.message || 'Failed to save' });
                }
            } catch (e) {
                console.error('Failed to save:', e);
                this.$dispatch('notify', { type: 'error', message: 'Failed to save results' });
            } finally {
                this.saving = false;
            }
        },

        async saveComment(resultId, commentText) {
            try {
                const response = await fetch(`${BASEURL}api/entry/comment`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        resultId: resultId,
                        comment: commentText
                    })
                });
                return response.json();
            } catch (e) {
                console.error('Failed to save comment:', e);
                return { status: 'error', message: e.message };
            }
        },

        updateResult(testId, value) {
            if (value === '') {
                delete this.resultsData[testId];
            } else {
                this.resultsData[testId] = value;
            }
        },

        updateComment(testId, value) {
            if (value.trim() === '') {
                delete this.commentsData[testId];
            } else {
                this.commentsData[testId] = value;
            }
        },

        getComment(testId) {
            return this.commentsData[testId] || '';
        },

        getExpectedRange(mean, sd) {
            if (mean === null || sd === null) return 'N/A';
            const min = (mean - 2 * sd).toFixed(2);
            const max = (mean + 2 * sd).toFixed(2);
            return `${min} - ${max}`;
        },

        getValueClass(test, value) {
            if (test.mean === null || test.sd === null) return '';
            const num = parseFloat(value);
            const lower = test.mean - 2 * test.sd;
            const upper = test.mean + 2 * test.sd;
            if (num >= lower && num <= upper) return 'text-success';
            return 'text-error';
        },

        getInputClass(test, value) {
            if (value === '' || test.mean === null || test.sd === null) return '';
            const num = parseFloat(value);
            const lower = test.mean - 2 * test.sd;
            const upper = test.mean + 2 * test.sd;
            if (num >= lower && num <= upper) return 'input-success';
            return 'input-error';
        },

        get hasChanges() {
            return Object.keys(this.resultsData).length > 0 ||
                   Object.keys(this.commentsData).length > 0;
        },

        get changedCount() {
            return Object.keys(this.resultsData).length + Object.keys(this.commentsData).length;
        },

        get canSave() {
            return this.selectedControl && (Object.keys(this.resultsData).length > 0 || Object.keys(this.commentsData).length > 0) && !this.saving;
        },

        setToday() {
            this.date = new Date().toISOString().split('T')[0];
        },

        setYesterday() {
            const yesterday = new Date();
            yesterday.setDate(yesterday.getDate() - 1);
            this.date = yesterday.toISOString().split('T')[0];
        },

        setupKeyboard() {
            document.addEventListener('keydown', (e) => {
                if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                    e.preventDefault();
                    if (this.canSave) {
                        this.saveResults();
                    }
                }
            });
        }
    }));
});
</script>
<?= $this->endSection(); ?>
