<script lang="ts">
    import {push} from 'svelte-spa-router'
    import {auth} from '../../lib/stores/auth.svelte'
    import {apiGetHunt, apiGetItemPhotos, apiGetItems, apiGetUnreviewedPhotos, apiListTeams, apiReviewPhoto} from '../../lib/api/index'
    import {parseUTC} from '../../lib/utils'
    import type {HuntResponse, ItemResponse, PhotoResponse, TeamResponse} from '../../lib/api/types'
    import StatusBadge from '../../lib/components/StatusBadge.svelte'
    import AuthImage from '../../lib/components/AuthImage.svelte'
    import LoadingSpinner from '../../lib/components/LoadingSpinner.svelte'

  let { params }: { params: { huntId: string } } = $props()

  $effect(() => {
    if (!auth.isLoggedIn) push('/login')
    if (!auth.isAdmin) push('/')
  })

  type PhotoWithContext = PhotoResponse & { teamName: string; itemName: string }

  let hunt = $state<HuntResponse | null>(null)
  let teams = $state<TeamResponse[]>([])
  let items = $state<ItemResponse[]>([])
  let selectedItem = $state<ItemResponse | null>(null)
  let photos = $state<PhotoWithContext[]>([])
  let unreviewedPhotos = $state<PhotoWithContext[]>([])
  let loading = $state(true)
  let photosLoading = $state(false)
  let error = $state('')
  let reviewing = $state<string | null>(null)
  let expandedPhoto = $state<PhotoWithContext | null>(null)

  $effect(() => {
    const { huntId } = params
    Promise.all([apiGetHunt(huntId), apiListTeams(huntId), apiGetItems(huntId), apiGetUnreviewedPhotos(huntId)])
      .then(async ([h, t, i, unreviewed]) => {
        hunt = h
        teams = t
        items = i
        // Build photoId → context map from all item+team combos in parallel
        const rows = await Promise.all(
          i.flatMap(item =>
            t.map(team =>
              apiGetItemPhotos(huntId, team.id, item.id)
                .then(ps => ps.map(p => [p.id, { itemName: item.name, teamName: team.name }] as [string, { itemName: string; teamName: string }]))
                .catch(() => [] as [string, { itemName: string; teamName: string }][])
            )
          )
        )
        const contextMap = new Map(rows.flat())
        unreviewedPhotos = unreviewed.map(p => {
          const ctx = contextMap.get(p.id) ?? { itemName: 'Unknown', teamName: 'Unknown' }
          return { ...p, ...ctx }
        })
      })
      .catch(e => { error = e instanceof Error ? e.message : 'Failed to load' })
      .finally(() => { loading = false })
  })

  $effect(() => {
    if (selectedItem) {
      photosLoading = true
      photos = []
      Promise.all(
        teams.map(team =>
          apiGetItemPhotos(params.huntId, team.id, selectedItem!.id)
            .then(ps => ps.map(p => ({ ...p, teamName: team.name, itemName: selectedItem!.name })))
        )
      )
        .then(results => { photos = results.flat() })
        .catch(e => { error = e instanceof Error ? e.message : 'Failed to load photos' })
        .finally(() => { photosLoading = false })
    }
  })

  async function review(photo: PhotoWithContext, status: 'APPROVED' | 'REJECTED' | 'REMOVED') {
    reviewing = photo.id
    try {
      await apiReviewPhoto(photo.id, status)
      const updated = { ...photo, photoStatus: status } as PhotoWithContext
      photos = photos.map(p => p.id === photo.id ? updated : p)
      unreviewedPhotos = unreviewedPhotos.map(p => p.id === photo.id ? updated : p)
      if (expandedPhoto?.id === photo.id) expandedPhoto = updated
    } catch (e: unknown) {
      error = e instanceof Error ? e.message : 'Failed to review photo'
    } finally {
      reviewing = null
    }
  }

  const activePhotos    = $derived(photos.filter(p => p.photoStatus !== 'REMOVED'))
  const activeUnreviewed = $derived(unreviewedPhotos.filter(p => p.photoStatus === 'SUBMITTED'))
</script>

<!-- Lightbox -->
{#if expandedPhoto}
  {@const photo = expandedPhoto}
  <div
    class="fixed inset-0 z-50 bg-black/90 flex flex-col"
    role="dialog"
    aria-modal="true"
  >
    <div class="flex items-center justify-between px-4 py-3 shrink-0">
      <div>
        <p class="text-xs font-semibold uppercase tracking-wide text-white/40">{photo.itemName}</p>
        <p class="font-semibold text-white">{photo.hunterName} <span class="text-white/50 font-normal">· {photo.teamName}</span></p>
        <p class="text-xs text-white/40">{parseUTC(photo.photoUploadDateTime).toLocaleString()}</p>
      </div>
      <div class="flex items-center gap-3">
        <StatusBadge status={photo.photoStatus} />
        <button class="btn btn-ghost btn-sm btn-circle text-white" onclick={() => expandedPhoto = null}>✕</button>
      </div>
    </div>

    <div class="flex-1 min-h-0 flex items-center justify-center px-4">
      <AuthImage photoId={photo.id} version="LARGE" alt={photo.hunterName} class="max-h-full max-w-full object-contain rounded-lg" />
    </div>

    <div class="px-4 py-4 shrink-0">
      {#if photo.photoStatus === 'SUBMITTED'}
        <div class="flex gap-2 mb-2">
          <button class="btn btn-success btn-sm flex-1" onclick={() => review(photo, 'APPROVED')} disabled={reviewing === photo.id}>
            {#if reviewing === photo.id}<span class="loading loading-spinner loading-xs"></span>{/if}
            Approve
          </button>
          <button class="btn btn-error btn-sm flex-1" onclick={() => review(photo, 'REJECTED')} disabled={reviewing === photo.id}>
            Reject
          </button>
        </div>
        <button class="btn btn-ghost btn-sm w-full text-white/40" onclick={() => review(photo, 'REMOVED')} disabled={reviewing === photo.id}>
          Remove
        </button>
      {:else if photo.photoStatus === 'APPROVED'}
        <div class="flex gap-2">
          <button class="btn btn-outline btn-error btn-sm flex-1" onclick={() => review(photo, 'REJECTED')} disabled={reviewing === photo.id}>
            Revoke Approval
          </button>
          <button class="btn btn-ghost btn-sm text-white/40" onclick={() => review(photo, 'REMOVED')} disabled={reviewing === photo.id}>
            Remove
          </button>
        </div>
      {:else if photo.photoStatus === 'REJECTED'}
        <div class="flex gap-2">
          <button class="btn btn-outline btn-success btn-sm flex-1" onclick={() => review(photo, 'APPROVED')} disabled={reviewing === photo.id}>
            Approve Instead
          </button>
          <button class="btn btn-ghost btn-sm text-white/40" onclick={() => review(photo, 'REMOVED')} disabled={reviewing === photo.id}>
            Remove
          </button>
        </div>
      {/if}
    </div>
  </div>
{/if}

<div class="p-4 pb-6">
  <div class="flex items-center gap-3 mb-4">
    <button class="btn btn-ghost btn-sm btn-circle" onclick={() => push(`/admin/hunt/${params.huntId}`)}>←</button>
    <h1 class="text-lg font-bold">{hunt?.title ?? 'Photo Review'}</h1>
  </div>

  {#if error}
    <div class="alert alert-error mb-4 text-sm">{error}</div>
  {/if}

  {#if loading}
    <LoadingSpinner />
  {:else}
    <!-- Item selector -->
    <div class="mb-4">
      <p class="text-sm font-medium text-base-content/60 mb-2">
        {#if selectedItem}
          Filtering by item — tap again to see all unreviewed
        {:else}
          Unreviewed ({activeUnreviewed.length})
        {/if}
      </p>
      <div class="flex flex-wrap gap-2">
        {#each items as item}
          <button
            class="btn btn-sm"
            class:btn-secondary={selectedItem?.id === item.id}
            class:btn-outline={selectedItem?.id !== item.id}
            onclick={() => { selectedItem = selectedItem?.id === item.id ? null : item }}
          >
            {item.name}
          </button>
        {/each}
      </div>
    </div>

    {#if selectedItem}
      <!-- Per-item photo view -->
      {#if photosLoading}
        <LoadingSpinner />
      {:else if activePhotos.length === 0}
        <div class="text-center py-10 text-base-content/50">
          <p>No photos submitted for this item</p>
        </div>
      {:else}
        <div class="flex flex-col gap-4">
          {#each activePhotos as photo (photo.id)}
            <div class="card bg-base-100 shadow-sm border border-base-200 overflow-hidden">
              <button class="w-full cursor-zoom-in" onclick={() => expandedPhoto = photo}>
                <AuthImage photoId={photo.id} version="SMALL" alt={photo.hunterName} class="w-full h-56 object-cover" />
              </button>
              <div class="p-3">
                <div class="flex items-center justify-between mb-3">
                  <div>
                    <p class="font-semibold">{photo.hunterName} <span class="text-base-content/50 font-normal">· {photo.teamName}</span></p>
                    <p class="text-xs text-base-content/50">
                      {parseUTC(photo.photoUploadDateTime).toLocaleString()}
                    </p>
                  </div>
                  <StatusBadge status={photo.photoStatus} />
                </div>
                {#if photo.photoStatus === 'SUBMITTED'}
                  <div class="flex gap-2 mb-2">
                    <button class="btn btn-success btn-sm flex-1" onclick={() => review(photo, 'APPROVED')} disabled={reviewing === photo.id}>
                      {#if reviewing === photo.id}<span class="loading loading-spinner loading-xs"></span>{/if}
                      Approve
                    </button>
                    <button class="btn btn-error btn-sm flex-1" onclick={() => review(photo, 'REJECTED')} disabled={reviewing === photo.id}>
                      Reject
                    </button>
                  </div>
                  <button class="btn btn-ghost btn-sm w-full text-base-content/50" onclick={() => review(photo, 'REMOVED')} disabled={reviewing === photo.id}>
                    Remove
                  </button>
                {:else if photo.photoStatus === 'APPROVED'}
                  <div class="flex gap-2">
                    <button class="btn btn-outline btn-error btn-sm flex-1" onclick={() => review(photo, 'REJECTED')} disabled={reviewing === photo.id}>
                      Revoke Approval
                    </button>
                    <button class="btn btn-ghost btn-sm text-base-content/50" onclick={() => review(photo, 'REMOVED')} disabled={reviewing === photo.id}>
                      Remove
                    </button>
                  </div>
                {:else if photo.photoStatus === 'REJECTED'}
                  <div class="flex gap-2">
                    <button class="btn btn-outline btn-success btn-sm flex-1" onclick={() => review(photo, 'APPROVED')} disabled={reviewing === photo.id}>
                      Approve Instead
                    </button>
                    <button class="btn btn-ghost btn-sm text-base-content/50" onclick={() => review(photo, 'REMOVED')} disabled={reviewing === photo.id}>
                      Remove
                    </button>
                  </div>
                {/if}
              </div>
            </div>
          {/each}
        </div>
      {/if}

    {:else}
      <!-- All-unreviewed view -->
      {#if activeUnreviewed.length === 0}
        <div class="text-center py-10 text-base-content/50">
          <p>All caught up — no unreviewed photos!</p>
        </div>
      {:else}
        <div class="flex flex-col gap-4">
          {#each activeUnreviewed as photo (photo.id)}
            <div class="card bg-base-100 shadow-sm border border-base-200 overflow-hidden">
              <button class="w-full cursor-zoom-in" onclick={() => expandedPhoto = photo}>
                <AuthImage photoId={photo.id} version="SMALL" alt={photo.hunterName} class="w-full h-56 object-cover" />
              </button>
              <div class="p-3">
                <p class="text-xs font-semibold uppercase tracking-wide text-primary mb-1">{photo.itemName}</p>
                <div class="flex items-center justify-between mb-3">
                  <div>
                    <p class="font-semibold">{photo.hunterName} <span class="text-base-content/50 font-normal">· {photo.teamName}</span></p>
                    <p class="text-xs text-base-content/50">
                      {parseUTC(photo.photoUploadDateTime).toLocaleString()}
                    </p>
                  </div>
                  <StatusBadge status={photo.photoStatus} />
                </div>
                <div class="flex gap-2 mb-2">
                  <button class="btn btn-success btn-sm flex-1" onclick={() => review(photo, 'APPROVED')} disabled={reviewing === photo.id}>
                    {#if reviewing === photo.id}<span class="loading loading-spinner loading-xs"></span>{/if}
                    Approve
                  </button>
                  <button class="btn btn-error btn-sm flex-1" onclick={() => review(photo, 'REJECTED')} disabled={reviewing === photo.id}>
                    Reject
                  </button>
                </div>
                <button class="btn btn-ghost btn-sm w-full text-base-content/50" onclick={() => review(photo, 'REMOVED')} disabled={reviewing === photo.id}>
                  Remove
                </button>
              </div>
            </div>
          {/each}
        </div>
      {/if}
    {/if}
  {/if}
</div>
