@extends('layouts.app')

@section('title', __('History'))
@section('active', 'history')

@section('content')
  @php
    $statusClasses = [
      'completed' => 'bg-emerald-50 text-emerald-600',
      'review' => 'bg-amber-50 text-amber-600',
      'scanning' => 'bg-blue-50 text-blue-600',
      'scheduled' => 'bg-gray-100 text-gray-600',
    ];
    $activeCollection = $collections->firstWhere('id', (int) $filters['collection_id']);
  @endphp

  <div class="rounded-2xl border border-[#c7d3fc] bg-[#eff3fe] p-6 lg:p-8">
    <div class="flex flex-col gap-5">
      <div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <p class="text-xs font-medium text-[#4f6ef7]">{{ __('Inspection History') }} - {{ __('Workspace') }}: {{ $activeWorkspace->name }}</p>
          <h1 class="mt-2 text-2xl font-bold tracking-tight lg:text-3xl">{{ __('Inspection History') }}</h1>
          <p class="mt-2 max-w-2xl text-sm leading-6 text-gray-500">
            {{ $activeCollection ? __('Filtered to collection: :name', ['name' => $activeCollection->displayName()]) : __('View and manage all property inspection records') }}
          </p>
        </div>
        <a href="{{ route('inspections.index', ['workspace_id' => $activeWorkspace->id]) }}" data-spa-link class="flex items-center justify-center rounded-xl bg-[#4f6ef7] px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-[#3d5ce0]">{{ __('New Inspection') }}</a>
      </div>

      <div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
        @foreach ($workspaces as $workspace)
          <a href="{{ route('history.index', ['workspace_id' => $workspace->id]) }}" data-spa-link class="rounded-xl border p-4 transition-colors {{ (int) $filters['workspace_id'] === $workspace->id ? 'border-[#4f6ef7] bg-white shadow-sm' : 'border-[#c7d3fc]/70 bg-white/60 hover:bg-white' }}">
            <div class="flex items-center justify-between gap-3">
              <p class="truncate text-sm font-semibold text-gray-900">{{ $workspace->name }}</p>
              <span class="rounded-full bg-[#eff3fe] px-2 py-0.5 text-[11px] font-medium text-[#4f6ef7]">{{ $workspace->collections_count }}</span>
            </div>
            <p class="mt-2 text-xs text-gray-500">{{ __('Completed') }} / {{ __('Total Inspections') }}</p>
            <p class="mt-1 text-lg font-bold">{{ $workspace->completed_count }} / {{ $workspace->inspections_count }}</p>
            <p class="mt-1 text-xs text-gray-500">Rp {{ number_format($workspace->estimated_cost_sum ?? 0, 0, ',', '.') }}</p>
          </a>
        @endforeach
      </div>
    </div>
  </div>

  <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
    <div class="stat-card rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <p class="text-sm font-medium text-gray-500">{{ __('Total Inspections') }}</p>
      <p class="mt-2 text-2xl font-bold tracking-tight" data-live="totalInspections">{{ $stats['total'] }}</p>
      <p class="mt-2 text-xs font-medium text-[#4f6ef7]">{{ __('Live records') }}</p>
    </div>
    <div class="stat-card rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <p class="text-sm font-medium text-gray-500">{{ __('Completed') }}</p>
      <p class="mt-2 text-2xl font-bold tracking-tight" data-live="completedInspections">{{ $stats['completed'] }}</p>
      <p class="mt-2 text-xs font-medium text-emerald-500">{{ __('Ready for archive') }}</p>
    </div>
    <div class="stat-card rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <p class="text-sm font-medium text-gray-500">{{ __('In Review') }}</p>
      <p class="mt-2 text-2xl font-bold tracking-tight" data-live="reviewInspections">{{ $stats['review'] }}</p>
      <p class="mt-2 text-xs font-medium text-amber-500">{{ __('Needs attention') }}</p>
    </div>
    <div class="stat-card rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <p class="text-sm font-medium text-gray-500">{{ __('Total Cost') }}</p>
      <p class="mt-2 text-2xl font-bold tracking-tight" data-live="estimatedCost">Rp {{ number_format($stats['totalCost'], 0, ',', '.') }}</p>
      <p class="mt-2 text-xs font-medium text-gray-400">{{ __('Synced') }} <span data-live-updated-at>--:--:--</span></p>
    </div>
  </div>

  <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
    <form id="historyFilterForm" method="GET" action="{{ route('history.index') }}" class="grid gap-3 md:grid-cols-[1fr_200px_220px_180px_auto]">
      <input name="search" value="{{ $filters['search'] }}" type="search" placeholder="{{ __('Search inspections by property or address...') }}" class="h-10 rounded-xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white focus:ring-2 focus:ring-[#4f6ef7]/20">
      <select id="historyWorkspaceSelect" name="workspace_id" class="h-10 rounded-xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white focus:ring-2 focus:ring-[#4f6ef7]/20">
        @foreach ($workspaces as $workspace)
          <option value="{{ $workspace->id }}" @selected((int) $filters['workspace_id'] === $workspace->id)>{{ $workspace->name }}</option>
        @endforeach
      </select>
      <select id="historyCollectionSelect" name="collection_id" class="h-10 rounded-xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white focus:ring-2 focus:ring-[#4f6ef7]/20">
        <option value="">{{ __('All collections') }}</option>
        @foreach ($collections as $collection)
          <option value="{{ $collection->id }}" @selected((int) $filters['collection_id'] === $collection->id)>{{ $collection->displayName() }}</option>
        @endforeach
      </select>
      <select name="status" class="h-10 rounded-xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white focus:ring-2 focus:ring-[#4f6ef7]/20">
        <option value="">{{ __('All status') }}</option>
        @foreach (['completed', 'review', 'scanning', 'scheduled'] as $status)
          <option value="{{ $status }}" @selected($filters['status'] === $status)>{{ Str::headline($status) }}</option>
        @endforeach
      </select>
      <button type="submit" class="h-10 rounded-xl bg-[#4f6ef7] px-4 text-sm font-medium text-white">{{ __('Apply') }}</button>
    </form>
  </div>

  <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
    <div class="mb-4 flex items-center justify-between">
      <div>
        <h3 class="text-base font-semibold">{{ __('History Records') }}</h3>
        <p class="text-sm text-gray-400">{{ __(':count matched inspections', ['count' => $inspections->total()]) }}</p>
      </div>
    </div>

    <div class="overflow-x-auto">
      <table class="w-full text-left text-sm">
        <thead class="text-xs uppercase text-gray-400">
          <tr>
            <th class="px-3 py-3">{{ __('Property') }}</th>
            <th class="px-3 py-3">{{ __('Collection') }}</th>
            <th class="px-3 py-3">{{ __('Status') }}</th>
            <th class="px-3 py-3">{{ __('Damages') }}</th>
            <th class="px-3 py-3">{{ __('Confidence') }}</th>
            <th class="px-3 py-3">{{ __('Cost') }}</th>
            <th class="px-3 py-3">{{ __('Date') }}</th>
            <th class="px-3 py-3 text-right">{{ __('Action') }}</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-100">
          @forelse ($inspections as $inspection)
            <tr>
              <td class="px-3 py-3">
                <p class="font-medium">{{ $inspection->property_name }}</p>
                <p class="mt-0.5 text-xs text-gray-400">{{ $inspection->property_address }}</p>
              </td>
              <td class="px-3 py-3">
                <p class="font-medium">{{ $inspection->collection?->displayName() ?? __('Unbatched') }}</p>
                <p class="mt-0.5 text-xs text-gray-400">{{ Str::headline($inspection->collection?->collection_type ?? 'single scan') }}</p>
              </td>
              <td class="px-3 py-3"><span class="rounded-lg px-2 py-1 text-xs font-medium {{ $statusClasses[$inspection->status] ?? 'bg-gray-100 text-gray-600' }}">{{ Str::headline($inspection->status) }}</span></td>
              <td class="px-3 py-3">{{ $inspection->damage_findings_count }}</td>
              <td class="px-3 py-3">{{ number_format($inspection->ai_confidence, 1) }}%</td>
              <td class="px-3 py-3">{{ $inspection->estimated_cost_label ?? 'Rp '.number_format($inspection->estimated_cost, 0, ',', '.') }}</td>
              <td class="px-3 py-3">{{ $inspection->scheduled_at?->format('M d, Y') ?? '-' }}</td>
              <td class="px-3 py-3 text-right">
                <button type="button"
                  class="rounded-lg border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-50"
                  data-history-detail
                  data-property="{{ $inspection->property_name }}"
                  data-collection="{{ $inspection->collection?->displayName() ?? __('Unbatched') }}"
                  data-address="{{ $inspection->property_address }}"
                  data-status="{{ Str::headline($inspection->status) }}"
                  data-damages="{{ $inspection->damage_findings_count }}"
                  data-confidence="{{ number_format($inspection->ai_confidence, 1) }}%"
                  data-cost="{{ $inspection->estimated_cost_label ?? 'Rp '.number_format($inspection->estimated_cost, 0, ',', '.') }}"
                  data-report-url="{{ $inspection->report ? route('reports.show', $inspection->report) : '' }}"
                  data-images="{{ e(json_encode($inspection->visualization_image_paths ?? [])) }}">
                  {{ __('Detail') }}
                </button>
              </td>
            </tr>
          @empty
            <tr>
              <td colspan="8" class="px-3 py-10 text-center text-sm text-gray-400">{{ __('No inspection history found.') }}</td>
            </tr>
          @endforelse
        </tbody>
      </table>
    </div>

    <div class="mt-5">{{ $inspections->links() }}</div>
  </div>

  <div id="historyModal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/40 p-4">
    <div class="w-full max-w-lg rounded-2xl bg-white p-6 shadow-xl">
      <div class="mb-5 flex items-start justify-between gap-4">
        <div>
          <p class="text-xs font-medium uppercase tracking-wide text-gray-400">{{ __('Inspection Detail') }}</p>
          <h3 id="historyModalTitle" class="mt-1 text-xl font-bold tracking-tight">Property</h3>
          <p id="historyModalCollection" class="mt-1 text-sm font-medium text-[#4f6ef7]"></p>
          <p id="historyModalAddress" class="mt-1 text-sm text-gray-500"></p>
        </div>
        <button type="button" onclick="closeHistoryModal()" class="rounded-lg p-2 text-gray-400 hover:bg-gray-100">x</button>
      </div>
      <div class="grid gap-3 sm:grid-cols-2">
        <div class="rounded-xl border border-gray-100 p-4"><p class="text-xs text-gray-400">{{ __('Status') }}</p><p id="historyModalStatus" class="mt-1 font-semibold"></p></div>
        <div class="rounded-xl border border-gray-100 p-4"><p class="text-xs text-gray-400">{{ __('Damages') }}</p><p id="historyModalDamages" class="mt-1 font-semibold"></p></div>
        <div class="rounded-xl border border-gray-100 p-4"><p class="text-xs text-gray-400">{{ __('Confidence') }}</p><p id="historyModalConfidence" class="mt-1 font-semibold"></p></div>
        <div class="rounded-xl border border-gray-100 p-4"><p class="text-xs text-gray-400">{{ __('Cost') }}</p><p id="historyModalCost" class="mt-1 font-semibold"></p></div>
      </div>
      <div id="historyModalImages" class="mt-5 grid gap-3 sm:grid-cols-2"></div>
      <div class="mt-5 flex justify-end">
        <a id="historyModalReportLink" href="{{ route('reports.index') }}" data-spa-link class="hidden rounded-xl bg-[#4f6ef7] px-4 py-2 text-sm font-medium text-white hover:bg-[#3d5ce0]">{{ __('View Full Report') }}</a>
      </div>
    </div>
  </div>
@endsection

@push('scripts')
<script data-page-script>
  function closeHistoryModal() {
    document.getElementById('historyModal')?.classList.add('hidden');
    document.getElementById('historyModal')?.classList.remove('flex');
  }

  document.querySelectorAll('[data-history-detail]').forEach((button) => {
    button.addEventListener('click', () => {
      document.getElementById('historyModalTitle').textContent = button.dataset.property;
      document.getElementById('historyModalCollection').textContent = button.dataset.collection;
      document.getElementById('historyModalAddress').textContent = button.dataset.address;
      document.getElementById('historyModalStatus').textContent = button.dataset.status;
      document.getElementById('historyModalDamages').textContent = button.dataset.damages;
      document.getElementById('historyModalConfidence').textContent = button.dataset.confidence;
      document.getElementById('historyModalCost').textContent = button.dataset.cost;
      const images = JSON.parse(button.dataset.images || '[]');
      const imageWrap = document.getElementById('historyModalImages');
      imageWrap.innerHTML = images.map((image) => `
        <figure class="overflow-hidden rounded-xl border border-gray-100 bg-white">
          <img src="${escapeHistoryHtml(image.url || '')}" alt="${escapeHistoryHtml(image.key || 'Roboflow result')}" class="h-56 w-full object-contain bg-gray-950">
          <figcaption class="truncate px-3 py-2 text-xs text-gray-500">${escapeHistoryHtml(image.key || 'Roboflow result')}</figcaption>
        </figure>
      `).join('');
      const reportLink = document.getElementById('historyModalReportLink');
      reportLink.href = button.dataset.reportUrl || '#';
      reportLink.classList.toggle('hidden', !button.dataset.reportUrl);
      document.getElementById('historyModal').classList.remove('hidden');
      document.getElementById('historyModal').classList.add('flex');
    });
  });

  function escapeHistoryHtml(value) {
    return String(value ?? '').replace(/[&<>"']/g, (char) => ({
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#039;'
    }[char]));
  }

  document.getElementById('historyWorkspaceSelect')?.addEventListener('change', () => {
    const collection = document.getElementById('historyCollectionSelect');
    if (collection) collection.value = '';
    document.getElementById('historyFilterForm')?.submit();
  });
</script>
@endpush
