{% extends "ui/templates/base/layout.html" %}
{% block content %}
<div class="space-y-6">
  <div class="flex flex-wrap items-center justify-between gap-3">
    <div>
      <h2 class="text-xl font-semibold text-slate-900">Service Catalogue</h2>
      <p class="text-sm text-slate-500">Standard service master. Firm Admin can select the services applicable for the active firm.</p>
    </div>
    <div class="flex flex-wrap gap-2">
      <a href="/services" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">Firm Services</a>
      <a href="/services/categories" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">Categories</a>
      <a href="/services/templates" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">Firm Task Templates</a>
      {% if can_create %}
      <a href="/services/defaults" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">System Default Tasks</a>
      <a href="/services/catalogue/export" class="rounded-xl border border-emerald-300 bg-emerald-50 px-4 py-2 text-sm font-medium text-emerald-800 hover:bg-emerald-100">Export Excel</a>
      <a href="/services/catalogue/merge" class="rounded-xl border border-amber-300 px-4 py-2 text-sm font-medium text-amber-800 hover:bg-amber-50">Merge Services</a>
      <a href="/services/catalogue/new" class="rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700">Add Catalogue Service</a>
      {% endif %}
    </div>
  </div>

  {% if request.query_params.get('bulk_action') == 'enable' or request.query_params.get('bulk_action') == 'disable' %}
  <div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800">
    Bulk update completed: <span class="font-semibold">{{ request.query_params.get('bulk_updated', '0') }}</span> changed,
    <span class="font-semibold">{{ request.query_params.get('bulk_unchanged', '0') }}</span> already in the requested state,
    and <span class="font-semibold">{{ request.query_params.get('bulk_skipped', '0') }}</span> skipped.
    {% if request.query_params.get('bulk_action') == 'enable' %}
    <div class="mt-2">
      <span class="font-semibold">{{ request.query_params.get('tasks_copied', '0') }}</span> system-default tasks copied.
      <span class="font-semibold">{{ request.query_params.get('services_existing_tasks', '0') }}</span> services already had firm tasks and were preserved.
      {% if request.query_params.get('services_without_defaults', '0') != '0' %}
      <span class="font-semibold">{{ request.query_params.get('services_without_defaults', '0') }}</span> services had no system-default tasks.
      {% endif %}
    </div>
    {% endif %}
  </div>
  {% elif request.query_params.get('bulk_action') == 'no_selection' %}
  <div class="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">Select at least one service before applying a bulk action.</div>
  {% elif request.query_params.get('bulk_action') == 'invalid_branch' %}
  <div class="rounded-2xl border border-red-200 bg-red-50 p-4 text-sm text-red-800">The selected default branch is not available for the active firm.</div>
  {% elif request.query_params.get('bulk_action') == 'invalid' %}
  <div class="rounded-2xl border border-red-200 bg-red-50 p-4 text-sm text-red-800">The requested bulk action is invalid.</div>
  {% endif %}


  {% if request.query_params.get('service_action') == 'enabled' %}
  <div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800">
    Service selected for the firm.
    {% if request.query_params.get('existing_tasks') == '1' %}
    Existing firm task templates were preserved without changes.
    {% elif request.query_params.get('tasks_copied', '0') != '0' %}
    <span class="font-semibold">{{ request.query_params.get('tasks_copied', '0') }}</span> system-default tasks were copied automatically.
    {% else %}
    No system-default tasks were available to copy.
    {% endif %}
  </div>
  {% elif request.query_params.get('service_action') == 'disabled' %}
  <div class="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
    Service disabled for the firm. Existing firm task templates were retained for future re-enablement.
  </div>
  {% endif %}

  {% if can_manage_firm_services %}
  <div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800">
    Select the services your firm provides. System-default tasks are copied automatically only when that service has no existing firm task templates. Existing customised firm tasks are never overwritten.
  </div>
  {% endif %}

  <form method="get" class="rounded-2xl bg-white p-4 shadow-soft">
    <div class="grid gap-3 md:grid-cols-5">
      <input type="text" name="q" value="{{ q }}" placeholder="Search code, name, category" class="rounded-xl border border-slate-300 px-4 py-2 text-sm md:col-span-2">
      <select name="category_id" class="rounded-xl border border-slate-300 px-4 py-2 text-sm">
        <option value="">All categories</option>
        {% for cat in categories %}<option value="{{ cat.id }}" {% if category_id == cat.id %}selected{% endif %}>{{ cat.name }}</option>{% endfor %}
      </select>
      <select name="recurrence_type" class="rounded-xl border border-slate-300 px-4 py-2 text-sm">
        <option value="">All recurrence</option>
        {% for value, label in recurrence_choices %}<option value="{{ value }}" {% if recurrence_type == value %}selected{% endif %}>{{ label }}</option>{% endfor %}
      </select>
      <select name="engagement_type" class="rounded-xl border border-slate-300 px-4 py-2 text-sm">
        <option value="">All engagement types</option>
        {% for value, label in engagement_type_choices %}<option value="{{ value }}" {% if engagement_type == value %}selected{% endif %}>{{ label }}</option>{% endfor %}
      </select>
    </div>
    <div class="mt-3 flex flex-wrap items-center justify-between gap-3">
      <label class="flex items-center gap-2 text-sm text-slate-600">
        Rows per page
        <select name="per_page" class="rounded-lg border border-slate-300 px-3 py-2 text-sm">
          {% for size in [20, 50, 100] %}
          <option value="{{ size }}" {% if per_page == size %}selected{% endif %}>{{ size }}</option>
          {% endfor %}
        </select>
      </label>
      <div class="flex gap-2">
        {% if q or category_id or recurrence_type or engagement_type or per_page != 20 %}
        <a href="/services/catalogue" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">Clear</a>
        {% endif %}
        <button class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium hover:bg-slate-50">Search</button>
      </div>
    </div>
  </form>

  {% if can_manage_firm_services %}
  <form id="bulk-service-form" method="post" action="/services/catalogue/bulk-selection" class="rounded-2xl border border-slate-200 bg-white p-4 shadow-soft">
    <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
    <input type="hidden" name="return_q" value="{{ q }}">
    <input type="hidden" name="return_category_id" value="{{ category_id or '' }}">
    <input type="hidden" name="return_recurrence_type" value="{{ recurrence_type }}">
    <input type="hidden" name="return_engagement_type" value="{{ engagement_type }}">
    <input type="hidden" name="return_page" value="{{ page }}">
    <input type="hidden" name="return_per_page" value="{{ per_page }}">
    <div class="flex flex-wrap items-center gap-3">
      <div class="mr-auto text-sm font-medium text-slate-700"><span id="bulk-selected-count">0</span> services selected</div>
      {% if branches %}
      <select name="default_branch_id" class="rounded-xl border border-slate-300 px-3 py-2 text-sm">
        <option value="">Keep existing branch / no default for new selections</option>
        {% for branch in branches %}<option value="{{ branch.id }}">{{ branch.name }}</option>{% endfor %}
      </select>
      {% else %}
      <input type="hidden" name="default_branch_id" value="">
      {% endif %}
      <button type="submit" name="bulk_action" value="enable" class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700">Select for Firm</button>
      <button type="submit" name="bulk_action" value="disable" class="rounded-xl border border-amber-300 px-4 py-2 text-sm font-semibold text-amber-700 hover:bg-amber-50">Disable for Firm</button>
      <button type="button" id="bulk-clear-selection" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">Clear Selection</button>
    </div>
  </form>
  {% endif %}

  <div class="overflow-hidden rounded-2xl bg-white shadow-soft">
    <table class="min-w-full divide-y divide-slate-200">
      <thead class="bg-slate-50">
        <tr>
          {% if can_manage_firm_services %}
          <th class="w-12 px-4 py-3 text-left">
            <input id="bulk-select-all-visible" type="checkbox" class="h-4 w-4 rounded border-slate-300 text-brand-600" aria-label="Select all services visible on this page">
          </th>
          {% endif %}
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Code</th>
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Name</th>
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Category</th>
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Recurrence</th>
          <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Firm Selection</th>
          <th class="px-4 py-3 text-right text-xs font-semibold uppercase tracking-wide text-slate-500">Action</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-100">
        {% for row in rows %}
        {% set selection = firm_selection_by_catalogue.get(row.id) if firm_selection_by_catalogue else None %}
        <tr>
          {% if can_manage_firm_services %}
          <td class="px-4 py-3 align-top">
            <input type="checkbox" name="service_ids" value="{{ row.id }}" form="bulk-service-form" class="bulk-service-checkbox h-4 w-4 rounded border-slate-300 text-brand-600" aria-label="Select {{ row.service_name }}">
          </td>
          {% endif %}
          <td class="px-4 py-3 text-sm font-medium text-slate-900">{{ row.service_code }}</td>
          <td class="px-4 py-3 text-sm text-slate-700">
            <div class="font-medium text-slate-900">{{ row.service_name }}</div>
            <div class="mt-1 text-xs text-slate-500">{{ 'Assurance' if row.engagement_type == 'assurance' else 'Non-Assurance' }}</div>
          </td>
          <td class="px-4 py-3 text-sm text-slate-700">{{ row.service_category.name if row.service_category else (row.category or '-') }}</td>
          <td class="px-4 py-3 text-sm text-slate-700">{{ row.recurrence_type|replace('_',' ')|title if row.recurrence_type else '-' }}</td>
          <td class="px-4 py-3 text-sm">
            {% if selection and selection.is_enabled %}
              <div class="mb-2"><span class="rounded-full bg-emerald-100 px-2 py-1 text-xs font-medium text-emerald-700">Selected for Firm</span></div>
              {% if selection.default_branch_id %}<div class="mb-2 text-xs text-slate-500">Default Branch ID: {{ selection.default_branch_id }}</div>{% endif %}
            {% else %}
              <div class="mb-2"><span class="rounded-full bg-slate-200 px-2 py-1 text-xs font-medium text-slate-700">Not Selected</span></div>
            {% endif %}

            {% if can_manage_firm_services %}
            <form method="post" action="/services/catalogue/{{ row.id }}/toggle" class="flex flex-wrap items-center gap-2">
              <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
              {% if branches %}
              <select name="default_branch_id" class="max-w-44 rounded-lg border border-slate-300 px-2 py-1 text-xs">
                <option value="">Default branch optional</option>
                {% for branch in branches %}
                <option value="{{ branch.id }}" {% if selection and selection.default_branch_id == branch.id %}selected{% endif %}>{{ branch.name }}</option>
                {% endfor %}
              </select>
              {% else %}
              <input type="hidden" name="default_branch_id" value="">
              {% endif %}
              <button class="rounded-lg {% if selection and selection.is_enabled %}border border-amber-300 text-amber-700 hover:bg-amber-50{% else %}bg-emerald-600 text-white hover:bg-emerald-700{% endif %} px-3 py-1.5 text-xs font-semibold">
                {{ 'Disable for Firm' if selection and selection.is_enabled else 'Select for Firm' }}
              </button>
            </form>
            {% endif %}
          </td>
          <td class="px-4 py-3 text-right text-sm">
            <a href="/services/catalogue/{{ row.id }}" class="font-medium text-brand-700 hover:underline">Open</a>
            {% if selection and selection.is_enabled %}
            <a href="/services/templates/{{ row.id }}" class="ml-3 font-medium text-brand-700 hover:underline">Firm Tasks</a>
            {% endif %}
            {% if can_create %}<a href="/services/catalogue/{{ row.id }}/edit" class="ml-3 font-medium text-brand-700 hover:underline">Edit</a>{% endif %}
          </td>
        </tr>
        {% else %}
        <tr><td colspan="{{ 7 if can_manage_firm_services else 6 }}" class="px-4 py-8 text-center text-sm text-slate-500">No catalogue services found.</td></tr>
        {% endfor %}
      </tbody>
    </table>

    <div class="flex flex-col gap-3 border-t border-slate-200 px-4 py-4 sm:flex-row sm:items-center sm:justify-between">
      <div class="text-sm text-slate-600">
        {% if total %}
          Showing <span class="font-semibold text-slate-900">{{ start_item }}</span>–<span class="font-semibold text-slate-900">{{ end_item }}</span>
          of <span class="font-semibold text-slate-900">{{ total }}</span> active services
        {% else %}
          No active services found
        {% endif %}
      </div>

      {% if pages > 1 %}
      <div class="flex flex-wrap items-center justify-end gap-2" aria-label="Service catalogue pagination">
        <form method="get">
          <input type="hidden" name="q" value="{{ q }}">
          {% if category_id %}<input type="hidden" name="category_id" value="{{ category_id }}">{% endif %}
          <input type="hidden" name="recurrence_type" value="{{ recurrence_type }}">
          <input type="hidden" name="engagement_type" value="{{ engagement_type }}">
          <input type="hidden" name="per_page" value="{{ per_page }}">
          <input type="hidden" name="page" value="{{ page - 1 }}">
          <button {% if page <= 1 %}disabled{% endif %} class="rounded-lg border border-slate-300 px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-40">Previous</button>
        </form>

        {% set first_page = 1 if page <= 3 else page - 2 %}
        {% set last_page = pages if page + 2 >= pages else page + 2 %}

        {% if first_page > 1 %}
        <form method="get">
          <input type="hidden" name="q" value="{{ q }}">{% if category_id %}<input type="hidden" name="category_id" value="{{ category_id }}">{% endif %}<input type="hidden" name="recurrence_type" value="{{ recurrence_type }}"><input type="hidden" name="engagement_type" value="{{ engagement_type }}"><input type="hidden" name="per_page" value="{{ per_page }}"><input type="hidden" name="page" value="1">
          <button class="rounded-lg border border-slate-300 px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">1</button>
        </form>
        {% if first_page > 2 %}<span class="px-1 text-slate-400">…</span>{% endif %}
        {% endif %}

        {% for page_number in range(first_page, last_page + 1) %}
        <form method="get">
          <input type="hidden" name="q" value="{{ q }}">
          {% if category_id %}<input type="hidden" name="category_id" value="{{ category_id }}">{% endif %}
          <input type="hidden" name="recurrence_type" value="{{ recurrence_type }}">
          <input type="hidden" name="engagement_type" value="{{ engagement_type }}">
          <input type="hidden" name="per_page" value="{{ per_page }}">
          <input type="hidden" name="page" value="{{ page_number }}">
          <button class="rounded-lg border px-3 py-2 text-sm font-medium {% if page_number == page %}border-brand-600 bg-brand-600 text-white{% else %}border-slate-300 text-slate-700 hover:bg-slate-50{% endif %}" {% if page_number == page %}aria-current="page"{% endif %}>{{ page_number }}</button>
        </form>
        {% endfor %}

        {% if last_page < pages %}
        {% if last_page < pages - 1 %}<span class="px-1 text-slate-400">…</span>{% endif %}
        <form method="get">
          <input type="hidden" name="q" value="{{ q }}">{% if category_id %}<input type="hidden" name="category_id" value="{{ category_id }}">{% endif %}<input type="hidden" name="recurrence_type" value="{{ recurrence_type }}"><input type="hidden" name="engagement_type" value="{{ engagement_type }}"><input type="hidden" name="per_page" value="{{ per_page }}"><input type="hidden" name="page" value="{{ pages }}">
          <button class="rounded-lg border border-slate-300 px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">{{ pages }}</button>
        </form>
        {% endif %}

        <form method="get">
          <input type="hidden" name="q" value="{{ q }}">
          {% if category_id %}<input type="hidden" name="category_id" value="{{ category_id }}">{% endif %}
          <input type="hidden" name="recurrence_type" value="{{ recurrence_type }}">
          <input type="hidden" name="engagement_type" value="{{ engagement_type }}">
          <input type="hidden" name="per_page" value="{{ per_page }}">
          <input type="hidden" name="page" value="{{ page + 1 }}">
          <button {% if page >= pages %}disabled{% endif %} class="rounded-lg border border-slate-300 px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-40">Next</button>
        </form>
      </div>
      {% endif %}
    </div>
  </div>
</div>
{% if can_manage_firm_services %}
<script>
  (() => {
    const selectAll = document.getElementById('bulk-select-all-visible');
    const clearButton = document.getElementById('bulk-clear-selection');
    const countLabel = document.getElementById('bulk-selected-count');
    const checkboxes = Array.from(document.querySelectorAll('.bulk-service-checkbox'));

    const refreshSelectionState = () => {
      const selectedCount = checkboxes.filter((checkbox) => checkbox.checked).length;
      countLabel.textContent = String(selectedCount);
      if (selectAll) {
        selectAll.checked = checkboxes.length > 0 && selectedCount === checkboxes.length;
        selectAll.indeterminate = selectedCount > 0 && selectedCount < checkboxes.length;
      }
    };

    if (selectAll) {
      selectAll.addEventListener('change', () => {
        checkboxes.forEach((checkbox) => { checkbox.checked = selectAll.checked; });
        refreshSelectionState();
      });
    }

    checkboxes.forEach((checkbox) => checkbox.addEventListener('change', refreshSelectionState));

    if (clearButton) {
      clearButton.addEventListener('click', () => {
        checkboxes.forEach((checkbox) => { checkbox.checked = false; });
        refreshSelectionState();
      });
    }

    refreshSelectionState();
  })();
</script>
{% endif %}
{% endblock %}
