{% extends "layouts/base.html" %}
{% load i18n %}
{% load static %}

{% block title %}{% trans "Physician Leaderboard" %} - PX360{% endblock %}

{% block extra_css %}
<style>
    .leaderboard-row {
        transition: all 0.2s ease;
        border-left: 3px solid transparent;
    }
    .leaderboard-row:hover {
        background: #f8fafc;
        border-left-color: #007bbd;
        transform: translateX(2px);
    }
    .table-card {
        transition: box-shadow 0.2s ease;
    }
    .table-card:hover {
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    }
    .field-label {
        font-size: 10px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #64748b;
    }
</style>
{% endblock %}

{% block content %}
<div class="p-8">
  <!-- Header -->
  <header class="mb-8">
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold text-navy flex items-center gap-3">
          <div class="w-10 h-10 bg-yellow-100 rounded-xl flex items-center justify-center">
            <i data-lucide="trophy" class="w-5 h-5 text-yellow-600"></i>
          </div>
          {% trans "Physician Leaderboard" %}
        </h1>
        <p class="text-slate mt-2 text-sm">{% trans "Top-rated physicians for" %} {{ year }}-{{ month|stringformat:"02d" }}</p>
      </div>
      <div class="flex items-center gap-2">
        <a href="{% url 'physicians:physician_ratings_dashboard' %}"
           class="px-4 py-2.5 bg-navy text-white rounded-xl font-semibold shadow-md hover:bg-blue transition flex items-center gap-2">
          <i data-lucide="layout-dashboard" class="w-4 h-4"></i>
          {% trans "Dashboard" %}
        </a>
        <a href="{% url 'physicians:physician_list' %}"
           class="px-5 py-2.5 border border-slate-200 text-slate rounded-xl font-semibold hover:bg-slate-50 hover:border-slate-300 transition flex items-center gap-2">
          <i data-lucide="arrow-left" class="w-4 h-4"></i>
          {% trans "Back to Physicians" %}
        </a>
      </div>
    </div>
  </header>

  <!-- Statistics Cards -->
  <section class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
    <div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100 hover:shadow-md transition">
      <div class="flex items-center justify-between">
        <div>
          <p class="field-label text-slate mb-2">{% trans "Total Physicians" %}</p>
          <h3 class="text-3xl font-bold text-navy">{{ stats.total_physicians|default:0 }}</h3>
        </div>
        <div class="w-14 h-14 bg-blue/10 rounded-xl flex items-center justify-center">
          <i data-lucide="users" class="w-7 h-7 text-blue"></i>
        </div>
      </div>
    </div>
    <div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100 hover:shadow-md transition">
      <div class="flex items-center justify-between">
        <div>
          <p class="field-label text-slate mb-2">{% trans "Average Rating" %}</p>
          <h3 class="text-3xl font-bold text-green-600">{{ stats.average_rating|floatformat:2|default:"-" }}</h3>
        </div>
        <div class="w-14 h-14 bg-green-100 rounded-xl flex items-center justify-center">
          <i data-lucide="star" class="w-7 h-7 text-green-600 fill-green-600"></i>
        </div>
      </div>
    </div>
    <div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100 hover:shadow-md transition">
      <div class="flex items-center justify-between">
        <div>
          <p class="field-label text-slate mb-2">{% trans "Total Surveys" %}</p>
          <h3 class="text-3xl font-bold text-navy">{{ stats.total_surveys|default:0 }}</h3>
        </div>
        <div class="w-14 h-14 bg-purple-100 rounded-xl flex items-center justify-center">
          <i data-lucide="file-text" class="w-7 h-7 text-purple-600"></i>
        </div>
      </div>
    </div>
    <div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100 hover:shadow-md transition">
      <div class="flex items-center justify-between">
        <div>
          <p class="field-label text-slate mb-2">{% trans "Excellent (4.5+)" %}</p>
          <h3 class="text-3xl font-bold text-yellow-600">{{ distribution.excellent|default:0 }}</h3>
        </div>
        <div class="w-14 h-14 bg-yellow-100 rounded-xl flex items-center justify-center">
          <i data-lucide="award" class="w-7 h-7 text-yellow-600"></i>
        </div>
      </div>
    </div>
  </section>

  <!-- Filters -->
  <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100 mb-6">
    <form method="get" class="grid grid-cols-2 md:grid-cols-6 gap-4">
      <div class="flex gap-2">
        <div class="flex-1">
          <label class="field-label">{% trans "Year" %}</label>
          <input type="number" name="year" 
                 value="{{ year }}" min="2020" max="2030"
                 class="w-full px-2 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition">
        </div>
        <div class="flex-1">
          <label class="field-label">{% trans "Month" %}</label>
          <select name="month" class="w-full px-2 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition">
            {% for m in "123456789012"|make_list %}
            <option value="{{ forloop.counter }}" {% if month == forloop.counter %}selected{% endif %}>
              {{ forloop.counter|stringformat:"02d" }}
            </option>
            {% endfor %}
          </select>
        </div>
      </div>
      
      <div>
        <label class="field-label">{% trans "Department" %}</label>
        <select name="department" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition" data-tomselect>
          <option value="">{% trans "All Departments" %}</option>
          {% for department in departments %}
          <option value="{{ department.id }}" {% if filters.department == department.id|stringformat:"s" %}selected{% endif %}>
            {{ department.name }}
          </option>
          {% endfor %}
        </select>
      </div>

      <div>
        <label class="field-label">{% trans "Physician" %}</label>
        <select name="physician" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition" data-tomselect>
          <option value="">{% trans "All Physicians" %}</option>
          {% for p in physicians %}
          <option value="{{ p.id }}" {% if filters.physician == p.id|stringformat:"s" %}selected{% endif %}>
            {{ p.get_full_name }}
          </option>
          {% endfor %}
        </select>
      </div>

      <div>
        <label class="field-label">{% trans "Min Rating" %}</label>
        <input type="number" name="min_rating" value="{{ filters.min_rating }}" min="1" max="5" step="0.1" placeholder="1.0"
               class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition">
      </div>

      <div>
        <label class="field-label">{% trans "Max Rating" %}</label>
        <input type="number" name="max_rating" value="{{ filters.max_rating }}" min="1" max="5" step="0.1" placeholder="5.0"
               class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition">
      </div>

      <div class="flex items-end gap-2">
        <select name="limit" class="px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition">
          <option value="10" {% if filters.limit == "10" %}selected{% endif %}>10</option>
          <option value="20" {% if filters.limit == "20" or not filters.limit %}selected{% endif %}>20</option>
          <option value="50" {% if filters.limit == "50" %}selected{% endif %}>50</option>
          <option value="100" {% if filters.limit == "100" %}selected{% endif %}>100</option>
        </select>
        <button type="submit" class="px-6 py-2.5 bg-navy text-white rounded-xl font-semibold shadow-md hover:bg-blue transition flex items-center gap-2">
          <i data-lucide="search" class="w-4 h-4"></i>
          {% trans "Filter" %}
        </button>
        <a href="{% url 'physicians:leaderboard' %}" class="px-6 py-2.5 border border-slate-200 text-slate rounded-xl font-semibold hover:bg-slate-50 hover:border-slate-300 transition flex items-center gap-2">
          <i data-lucide="x-circle" class="w-4 h-4"></i>
          {% trans "Clear" %}
        </a>
      </div>
    </form>
  </section>

  <!-- Leaderboard -->
  <section class="bg-white rounded-2xl shadow-sm border border-slate-100 table-card mb-6">
    <div class="p-6 border-b border-slate-200">
      <h3 class="text-lg font-bold text-navy">{% trans "Top Performers" %}</h3>
    </div>
    <div class="overflow-x-auto">
      <table class="w-full">
        <thead>
          <tr class="bg-slate-50 border-b border-slate-200">
            <th class="p-4 text-left font-bold text-navy text-xs uppercase tracking-wider" style="width: 80px;">{% trans "Rank" %}</th>
            <th class="p-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Physician" %}</th>
            <th class="p-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Specialization" %}</th>
            <th class="p-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Department" %}</th>
            <th class="p-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Rating" %}</th>
            <th class="p-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Surveys" %}</th>
            <th class="p-4 text-center font-bold text-navy text-xs uppercase tracking-wider">{% trans "1★" %}</th>
            <th class="p-4 text-center font-bold text-navy text-xs uppercase tracking-wider">{% trans "2★" %}</th>
            <th class="p-4 text-center font-bold text-navy text-xs uppercase tracking-wider">{% trans "3★" %}</th>
            <th class="p-4 text-center font-bold text-navy text-xs uppercase tracking-wider">{% trans "4★" %}</th>
            <th class="p-4 text-center font-bold text-navy text-xs uppercase tracking-wider">{% trans "5★" %}</th>
            <th class="p-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Rating Trend" %}</th>
            <th class="p-4 text-center font-bold text-navy text-xs uppercase tracking-wider">{% trans "Actions" %}</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-100">
          {% for entry in leaderboard %}
          <tr class="leaderboard-row cursor-pointer" onclick="window.location='{% url 'physicians:physician_detail' entry.physician.id %}'">
            <td class="p-4">
              {% if entry.rank <= 3 %}
              <div class="flex items-center justify-center">
                {% if entry.rank == 1 %}
                <div class="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center">
                  <i data-lucide="trophy" class="w-6 h-6 text-yellow-600 fill-yellow-600"></i>
                </div>
                {% elif entry.rank == 2 %}
                <div class="w-12 h-12 bg-slate-200 rounded-full flex items-center justify-center">
                  <i data-lucide="trophy" class="w-6 h-6 text-slate-400 fill-slate-400"></i>
                </div>
                {% elif entry.rank == 3 %}
                <div class="w-12 h-12 bg-orange-100 rounded-full flex items-center justify-center">
                  <i data-lucide="trophy" class="w-6 h-6 text-orange-600 fill-orange-600"></i>
                </div>
                {% endif %}
              </div>
              {% else %}
              <span class="text-slate font-bold text-lg">#{{ entry.rank }}</span>
              {% endif %}
            </td>
            <td class="p-4">
              <div class="flex items-center gap-3 group">
                <div class="w-10 h-10 rounded-lg bg-blue/10 flex items-center justify-center group-hover:bg-blue group-hover:text-white transition">
                  <i data-lucide="user" class="w-5 h-5 text-blue group-hover:text-white transition"></i>
                </div>
                <div>
                  <p class="font-bold text-navy group-hover:text-blue transition">{{ entry.physician.get_full_name }}</p>
                  <p class="text-xs text-slate">{{ entry.physician.license_number }}</p>
                </div>
              </div>
            </td>
            <td class="p-4">
              <span class="text-sm text-slate">{{ entry.physician.specialization|default:"-" }}</span>
            </td>
            <td class="p-4">
              <span class="text-sm text-slate">
                {% if entry.physician.department %}{{ entry.physician.department.name }}{% else %}-{% endif %}
              </span>
            </td>
            <td class="p-4">
              <div class="flex items-center gap-1">
                <i data-lucide="star" class="w-4 h-4 text-yellow-500 fill-yellow-500"></i>
                <span class="font-bold text-lg text-green-600">{{ entry.rating.average_rating|floatformat:2 }}</span>
              </div>
            </td>
            <td class="p-4">
              <span class="text-sm text-slate bg-slate-100 px-2 py-1 rounded-full font-medium">
                {{ entry.rating.total_surveys }}
              </span>
            </td>
            <td class="p-3 text-center">
              <div class="text-xs">
                <span class="font-bold text-red-600">{{ entry.rating.rating_1_count }}</span>
                <span class="text-slate-400 block">{{ entry.rating.rating_1_pct }}%</span>
              </div>
            </td>
            <td class="p-3 text-center">
              <div class="text-xs">
                <span class="font-bold text-orange-600">{{ entry.rating.rating_2_count }}</span>
                <span class="text-slate-400 block">{{ entry.rating.rating_2_pct }}%</span>
              </div>
            </td>
            <td class="p-3 text-center">
              <div class="text-xs">
                <span class="font-bold text-yellow-600">{{ entry.rating.rating_3_count }}</span>
                <span class="text-slate-400 block">{{ entry.rating.rating_3_pct }}%</span>
              </div>
            </td>
            <td class="p-3 text-center">
              <div class="text-xs">
                <span class="font-bold text-blue-600">{{ entry.rating.rating_4_count }}</span>
                <span class="text-slate-400 block">{{ entry.rating.rating_4_pct }}%</span>
              </div>
            </td>
            <td class="p-3 text-center">
              <div class="text-xs">
                <span class="font-bold text-green-600">{{ entry.rating.rating_5_count }}</span>
                <span class="text-slate-400 block">{{ entry.rating.rating_5_pct }}%</span>
              </div>
            </td>
            <td class="p-4">
              <div id="spark-{{ entry.physician.id }}" class="sparkline-container"
                   data-values="{{ entry.trend_data|join:',' }}"
                   data-trend="{{ entry.trend }}"
                   data-labels="{{ entry.trend_labels|join:',' }}"
                   style="width:120px;height:40px;"></div>
            </td>
            <td class="p-4">
              <div class="flex items-center justify-center gap-1" onclick="event.stopPropagation();">
                <a href="{% url 'physicians:physician_detail' entry.physician.id %}" 
                   class="w-8 h-8 flex items-center justify-center rounded-lg bg-blue/10 text-blue hover:bg-blue hover:text-white transition" 
                   title="{% trans 'View' %}">
                  <i data-lucide="eye" class="w-4 h-4"></i>
                </a>
              </div>
            </td>
          </tr>
          {% empty %}
          <tr>
            <td colspan="13" class="p-12 text-center">
              <div class="flex flex-col items-center justify-center">
                <div class="w-20 h-20 bg-slate-100 rounded-full flex items-center justify-center mb-4">
                  <i data-lucide="trophy" class="w-10 h-10 text-slate-300"></i>
                </div>
                <p class="text-slate font-medium mb-2">{% trans "No ratings available for this period" %}</p>
                <p class="text-slate text-sm">{% trans "Try adjusting your filters or date range" %}</p>
              </div>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </section>

  <!-- Performance Distribution -->
  <section class="bg-white rounded-2xl shadow-sm border border-slate-100">
    <div class="p-6 border-b border-slate-200">
      <h3 class="text-lg font-bold text-navy">{% trans "Performance Distribution" %}</h3>
    </div>
    <div class="p-6">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div class="text-center p-4 border border-slate-200 rounded-xl hover:shadow-md transition">
          <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-3">
            <i data-lucide="star" class="w-6 h-6 text-green-600 fill-green-600"></i>
          </div>
          <h2 class="text-3xl font-bold text-green-600 mb-2">{{ distribution.excellent|default:0 }}</h2>
          <p class="text-slate text-sm font-medium">{% trans "Excellent" %}</p>
          <p class="text-slate text-xs">(4.5+)</p>
        </div>
        <div class="text-center p-4 border border-slate-200 rounded-xl hover:shadow-md transition">
          <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-3">
            <i data-lucide="smile" class="w-6 h-6 text-blue-600"></i>
          </div>
          <h2 class="text-3xl font-bold text-blue-600 mb-2">{{ distribution.good|default:0 }}</h2>
          <p class="text-slate text-sm font-medium">{% trans "Good" %}</p>
          <p class="text-slate text-xs">(3.5-4.5)</p>
        </div>
        <div class="text-center p-4 border border-slate-200 rounded-xl hover:shadow-md transition">
          <div class="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-3">
            <i data-lucide="meh" class="w-6 h-6 text-yellow-600"></i>
          </div>
          <h2 class="text-3xl font-bold text-yellow-600 mb-2">{{ distribution.average|default:0 }}</h2>
          <p class="text-slate text-sm font-medium">{% trans "Average" %}</p>
          <p class="text-slate text-xs">(2.5-3.5)</p>
        </div>
        <div class="text-center p-4 border border-slate-200 rounded-xl hover:shadow-md transition">
          <div class="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-3">
            <i data-lucide="frown" class="w-6 h-6 text-red-600"></i>
          </div>
          <h2 class="text-3xl font-bold text-red-600 mb-2">{{ distribution.poor|default:0 }}</h2>
          <p class="text-slate text-sm font-medium">{% trans "Poor" %}</p>
          <p class="text-slate text-xs">(<2.5)</p>
        </div>
      </div>
    </div>
  </section>
</div>
{% endblock %}

{% block extra_js %}
<script>
  lucide.createIcons();

  document.querySelectorAll('.sparkline-container').forEach(function(el) {
    var raw = el.getAttribute('data-values');
    if (!raw) return;
    var values = raw.split(',').map(function(v) { return v === '' || v === 'None' ? null : parseFloat(v); });
    var trend = el.getAttribute('data-trend') || 'stable';
    var labels = (el.getAttribute('data-labels') || '').split(',');

    var color = trend === 'up' ? '#16a34a' : (trend === 'down' ? '#dc2626' : '#94a3b8');

    var options = {
      chart: {
        type: 'line',
        width: 120,
        height: 40,
        sparkline: { enabled: true },
        animations: { enabled: false },
      },
      series: [{ data: values }],
      stroke: { curve: 'smooth', width: 2, colors: [color] },
      fill: {
        type: 'gradient',
        gradient: {
          shadeIntensity: 1,
          opacityFrom: 0.4,
          opacityTo: 0.05,
          stops: [0, 100],
          colorStops: [{
            offset: 0, color: color, opacity: 0.3
          }, {
            offset: 100, color: color, opacity: 0.02
          }]
        }
      },
      tooltip: {
        enabled: true,
        theme: 'dark',
        x: { formatter: function(val, opts) { return labels[opts.dataPointIndex] || ''; } },
        y: { formatter: function(val) { return val !== null ? val.toFixed(2) : '-'; } },
      },
      xaxis: { labels: { show: false }, axisBorder: { show: false }, axisTicks: { show: false } },
      yaxis: { min: 1, max: 5, labels: { show: false } },
      grid: { show: false },
      padding: { left: 0, right: 0, top: 0, bottom: 0 },
    };

    new ApexCharts(el, options).render();
  });
</script>
{% endblock %}