<script lang="ts">
  import { onMount } from 'svelte';
  import { api } from '../../api';
  import type { BackfillResult, MaintenanceLog, MaintenanceTask, MetadataRetryResult } from '../../types';

  let tasks = $state<MaintenanceTask[]>([]);
  let logs = $state<MaintenanceLog[]>([]);
  let loading = $state(true);
  let error = $state('');
  let busyAction = $state<'backfill' | 'retry' | null>(null);
  let actionError = $state('');
  let actionMessage = $state('');
  let dryRun = $state(true);

  async function load() {
    loading = true;
    error = '';
    try {
      const [taskRows, logRows] = await Promise.all([api.maintenance.tasks(), api.maintenance.logs()]);
      tasks = taskRows;
      logs = logRows;
    } catch (e) {
      error = e instanceof Error ? e.message : 'Failed to load maintenance data';
    } finally {
      loading = false;
    }
  }

  function formatDate(value?: string): string {
    if (!value) return '—';
    return new Date(value).toLocaleString();
  }

  function formatCost(value?: number): string {
    if (value === undefined || value === null) return '—';
    return `$${value.toFixed(2)}`;
  }

  function summarizeBackfill(result: BackfillResult): string {
    return `Backfill (${result.dry_run ? 'dry-run' : 'run'}) scanned ${result.scanned}, embedded ${result.embedded}, failed ${result.failed}.`;
  }

  function summarizeRetry(result: MetadataRetryResult): string {
    return `Metadata retry (${result.dry_run ? 'dry-run' : 'run'}) scanned ${result.scanned}, retried ${result.retried}, updated ${result.updated}, failed ${result.failed}.`;
  }

  async function runBackfill() {
    busyAction = 'backfill';
    actionError = '';
    actionMessage = '';
    try {
      const result = await api.maintenance.runBackfill({ dry_run: dryRun });
      actionMessage = summarizeBackfill(result);
    } catch (e) {
      actionError = e instanceof Error ? e.message : 'Backfill failed';
    } finally {
      busyAction = null;
    }
  }

  async function runRetryMetadata() {
    busyAction = 'retry';
    actionError = '';
    actionMessage = '';
    try {
      const result = await api.maintenance.runRetryMetadata({ dry_run: dryRun });
      actionMessage = summarizeRetry(result);
    } catch (e) {
      actionError = e instanceof Error ? e.message : 'Retry failed';
    } finally {
      busyAction = null;
    }
  }

  onMount(load);
</script>

<div class="space-y-6">
  <div class="flex items-end justify-between">
    <div>
      <h2 class="text-2xl font-semibold text-white">Maintenance</h2>
      <p class="mt-1 text-sm text-slate-400">Operational state and safe maintenance actions.</p>
    </div>
    <button
      class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200 transition hover:bg-white/10"
      onclick={load}
    >Refresh</button>
  </div>

  <section class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
    <div class="flex flex-wrap items-center gap-3">
      <label class="flex items-center gap-2 text-sm text-slate-300">
        <input type="checkbox" class="accent-cyan-400" bind:checked={dryRun} />
        Dry run
      </label>
      <button
        class="rounded-xl border border-cyan-300/30 bg-cyan-400/10 px-4 py-2 text-sm font-medium text-cyan-100 transition hover:bg-cyan-400/20 disabled:opacity-50"
        onclick={runBackfill}
        disabled={busyAction !== null}
      >{busyAction === 'backfill' ? 'Running backfill…' : 'Run Backfill'}</button>
      <button
        class="rounded-xl border border-amber-300/30 bg-amber-400/10 px-4 py-2 text-sm font-medium text-amber-100 transition hover:bg-amber-400/20 disabled:opacity-50"
        onclick={runRetryMetadata}
        disabled={busyAction !== null}
      >{busyAction === 'retry' ? 'Running retry…' : 'Run Metadata Retry'}</button>
    </div>
    {#if actionError}
      <p class="mt-3 text-sm text-rose-300">{actionError}</p>
    {/if}
    {#if actionMessage}
      <p class="mt-3 text-sm text-emerald-300">{actionMessage}</p>
    {/if}
  </section>

  {#if loading}
    <div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-12 text-center text-slate-400">Loading…</div>
  {:else if error}
    <div class="rounded-2xl border border-rose-400/30 bg-rose-400/10 px-4 py-4 text-sm text-rose-100">{error}</div>
  {:else}
    <section class="space-y-4">
      <h3 class="text-lg font-semibold text-white">Tasks ({tasks.length})</h3>
      {#if tasks.length === 0}
        <div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-10 text-center text-slate-500">No maintenance tasks.</div>
      {:else}
        <div class="overflow-hidden rounded-2xl border border-white/10">
          <table class="min-w-full divide-y divide-white/10 text-sm text-slate-300">
            <thead class="bg-white/5 text-xs uppercase tracking-[0.18em] text-slate-500">
              <tr>
                <th class="px-4 py-3 text-left font-medium">Task</th>
                <th class="px-4 py-3 text-left font-medium">Category</th>
                <th class="px-4 py-3 text-left font-medium">Priority</th>
                <th class="px-4 py-3 text-right font-medium">Next Due</th>
                <th class="px-4 py-3 text-right font-medium">Last Completed</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-white/5 bg-slate-950/30">
              {#each tasks as task}
                <tr class="hover:bg-white/[0.03]">
                  <td class="px-4 py-3 font-medium text-white">{task.name}</td>
                  <td class="px-4 py-3 text-slate-400">{task.category || '—'}</td>
                  <td class="px-4 py-3 text-slate-300">{task.priority || 'medium'}</td>
                  <td class="px-4 py-3 text-right text-slate-300">{formatDate(task.next_due)}</td>
                  <td class="px-4 py-3 text-right text-slate-400">{formatDate(task.last_completed)}</td>
                </tr>
              {/each}
            </tbody>
          </table>
        </div>
      {/if}
    </section>

    <section class="space-y-4">
      <h3 class="text-lg font-semibold text-white">Recent Logs ({logs.length})</h3>
      {#if logs.length === 0}
        <div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-10 text-center text-slate-500">No maintenance logs.</div>
      {:else}
        <div class="overflow-hidden rounded-2xl border border-white/10">
          <table class="min-w-full divide-y divide-white/10 text-sm text-slate-300">
            <thead class="bg-white/5 text-xs uppercase tracking-[0.18em] text-slate-500">
              <tr>
                <th class="px-4 py-3 text-left font-medium">Completed</th>
                <th class="px-4 py-3 text-left font-medium">Task ID</th>
                <th class="px-4 py-3 text-left font-medium">By</th>
                <th class="px-4 py-3 text-right font-medium">Cost</th>
                <th class="px-4 py-3 text-left font-medium">Notes</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-white/5 bg-slate-950/30">
              {#each logs as log}
                <tr class="hover:bg-white/[0.03]">
                  <td class="px-4 py-3 text-slate-300">{formatDate(log.completed_at)}</td>
                  <td class="px-4 py-3"><code class="text-xs text-cyan-100">{log.task_id}</code></td>
                  <td class="px-4 py-3 text-slate-400">{log.performed_by || '—'}</td>
                  <td class="px-4 py-3 text-right tabular-nums text-slate-300">{formatCost(log.cost)}</td>
                  <td class="max-w-sm truncate px-4 py-3 text-slate-400">{log.notes || '—'}</td>
                </tr>
              {/each}
            </tbody>
          </table>
        </div>
      {/if}
    </section>
  {/if}
</div>
