<script>
  import { onMount, onDestroy } from 'svelte'
  import { GetSessions, GetStatistics, ExportData, ExportCSV, DeleteSession, DeleteAllSessions } from '../../wailsjs/go/app/App'
  import { t, locale } from '../lib/i18n'

  let sessions = []
  let stats = null
  let loading = true
  let dateFrom = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
  let dateTo = new Date().toISOString().split('T')[0]
  let exporting = false
  let showDeleteAllConfirm = false
  let deletingSessionId = null

  function handleKeydown(e) {
    if (e.key === 'Escape') {
      if (deletingSessionId !== null) deletingSessionId = null
      if (showDeleteAllConfirm) showDeleteAllConfirm = false
    }
  }

  onMount(async () => {
    window.addEventListener('keydown', handleKeydown)
    await loadData()
  })

  onDestroy(() => {
    window.removeEventListener('keydown', handleKeydown)
  })

  async function loadData() {
    loading = true
    try {
      sessions = await GetSessions(50, 0)
      stats = await GetStatistics(dateFrom, dateTo)
    } catch (e) {
      console.error('Failed to load history:', e)
    }
    loading = false
  }

  async function handleDeleteSession(id) {
    deletingSessionId = id
  }

  async function confirmDeleteSession() {
    if (!deletingSessionId) return
    try {
      await DeleteSession(deletingSessionId)
      await loadData()
    } catch (e) {
      console.error('Failed to delete session:', e)
    }
    deletingSessionId = null
  }

  async function handleDeleteAll() {
    showDeleteAllConfirm = true
  }

  async function confirmDeleteAll() {
    try {
      await DeleteAllSessions()
      await loadData()
    } catch (e) {
      console.error('Failed to delete all sessions:', e)
    }
    showDeleteAllConfirm = false
  }

  async function handleExportJSON() {
    exporting = true
    try {
      const path = await ExportData(dateFrom, dateTo)
      if (path) {
        alert('Exported to: ' + path)
      }
    } catch (e) {
      alert('Export failed: ' + e)
    }
    exporting = false
  }

  async function handleExportCSV() {
    exporting = true
    try {
      const path = await ExportCSV(dateFrom, dateTo)
      if (path) {
        alert('Exported to: ' + path)
      }
    } catch (e) {
      alert('Export failed: ' + e)
    }
    exporting = false
  }

  function formatTime(seconds) {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, '0')}`
  }

  function formatDate(dateStr) {
    const loc = $locale === 'ru' ? 'ru-RU' : 'en-US'
    return new Date(dateStr).toLocaleDateString(loc, {
      day: 'numeric',
      month: 'short',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
</script>

<div class="history">
  <div class="filters">
    <div class="date-range">
      <input type="date" bind:value={dateFrom} on:change={loadData} />
      <span>—</span>
      <input type="date" bind:value={dateTo} on:change={loadData} />
    </div>
    
    <div class="export-buttons">
      <button on:click={handleExportJSON} disabled={exporting}>{$t('history.exportJSON')}</button>
      <button on:click={handleExportCSV} disabled={exporting}>{$t('history.exportCSV')}</button>
      {#if sessions.length > 0}
        <button class="delete-all-btn" on:click={handleDeleteAll}>{$t('history.deleteAll')}</button>
      {/if}
    </div>
  </div>

  {#if loading}
    <div class="loading">{$t('common.loading')}</div>
  {:else}
    {#if stats}
      <section class="stats-overview">
        <h2>{$t('participants.stats')}</h2>
        
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">{stats.totalSessions}</div>
            <div class="stat-label">{$t('participants.totalMeetings')}</div>
          </div>
          
          <div class="stat-card">
            <div class="stat-value">{formatTime(Math.round(stats.averageMeetingTime))}</div>
            <div class="stat-label">{$t('history.avgTime')}</div>
          </div>
          
          <div class="stat-card">
            <div class="stat-value">{stats.overtimePercentage.toFixed(0)}%</div>
            <div class="stat-label">{$t('history.overtimeRate')}</div>
          </div>
          
          <div class="stat-card">
            <div class="stat-value">{stats.averageAttendance.toFixed(1)}</div>
            <div class="stat-label">{$t('history.avgAttendance')}</div>
          </div>
        </div>

        {#if stats.participantBreakdown?.length > 0}
          <h3>{$t('history.participantBreakdown')}</h3>
          <div class="breakdown-table">
            <div class="breakdown-header">
              <span>{$t('history.name')}</span>
              <span>{$t('history.sessions')}</span>
              <span>{$t('history.avgTime')}</span>
              <span>{$t('history.overtime')}</span>
              <span>{$t('history.attendance')}</span>
            </div>
            {#each stats.participantBreakdown as p}
              <div class="breakdown-row">
                <span>{p.name}</span>
                <span>{p.sessionsAttended}</span>
                <span>{formatTime(Math.round(p.averageSpeakingTime))}</span>
                <span class:overtime={p.overtimeCount > 0}>{p.overtimeCount}</span>
                <span>{p.attendanceRate.toFixed(0)}%</span>
              </div>
            {/each}
          </div>
        {/if}
      </section>
    {/if}

    <section class="sessions-list">
      <h2>{$t('history.recentSessions')}</h2>
      
      {#if sessions.length === 0}
        <p class="empty">{$t('history.noSessions')}</p>
      {:else}
        {#each sessions as session}
          <div class="session-card" class:overtime={session.totalDuration > 900}>
            <div class="session-header">
              <span class="session-date">{formatDate(session.startedAt)}</span>
              <span class="session-duration">{formatTime(session.totalDuration)}</span>
              {#if session.totalDuration > 900}
                <span class="overtime-badge">OVERTIME</span>
              {/if}
              <button class="delete-session-btn" on:click={() => handleDeleteSession(session.id)} title={$t('history.deleteSession')}>🗑️</button>
            </div>
            
            {#if session.participantLogs?.length > 0}
              <div class="session-participants">
                {#each session.participantLogs as log}
                  <div class="participant-log" class:log-overtime={log.overtime} class:skipped={log.skipped}>
                    <span class="log-order">#{log.order}</span>
                    <span class="log-name">{log.participant?.name || 'Unknown'}</span>
                    <span class="log-duration">
                      <span class:overtime={log.duration > (log.participant?.timeLimit || 0)}>
                        {formatTime(log.duration)}
                      </span>
                      {#if log.participant?.timeLimit}
                        <span class="time-sep">/</span>
                        <span class="time-limit">{formatTime(log.participant.timeLimit)}</span>
                      {/if}
                    </span>
                    {#if log.overtime}
                      <span class="overtime-icon">⚠️</span>
                    {/if}
                    {#if log.skipped}
                      <span class="skipped-icon">⏭️</span>
                    {/if}
                  </div>
                {/each}
              </div>
            {/if}
          </div>
        {/each}
      {/if}
    </section>
  {/if}
</div>

<!-- Delete Session Confirmation Modal -->
{#if deletingSessionId !== null}
  <!-- svelte-ignore a11y-click-events-have-key-events a11y-no-static-element-interactions -->
  <div class="modal-overlay" on:click={() => deletingSessionId = null}>
    <!-- svelte-ignore a11y-click-events-have-key-events a11y-no-static-element-interactions -->
    <div class="modal" on:click|stopPropagation>
      <h3>{$t('history.confirmDeleteTitle')}</h3>
      <p>{$t('history.confirmDeleteSession')}</p>
      <div class="modal-buttons">
        <button class="cancel-btn" on:click={() => deletingSessionId = null}>{$t('common.cancel')}</button>
        <button class="confirm-btn" on:click={confirmDeleteSession}>{$t('common.delete')}</button>
      </div>
    </div>
  </div>
{/if}

<!-- Delete All Confirmation Modal -->
{#if showDeleteAllConfirm}
  <!-- svelte-ignore a11y-click-events-have-key-events a11y-no-static-element-interactions -->
  <div class="modal-overlay" on:click={() => showDeleteAllConfirm = false}>
    <!-- svelte-ignore a11y-click-events-have-key-events a11y-no-static-element-interactions -->
    <div class="modal" on:click|stopPropagation>
      <h3>{$t('history.confirmDeleteAllTitle')}</h3>
      <p>{$t('history.confirmDeleteAll')}</p>
      <div class="modal-buttons">
        <button class="cancel-btn" on:click={() => showDeleteAllConfirm = false}>{$t('common.cancel')}</button>
        <button class="confirm-btn danger" on:click={confirmDeleteAll}>{$t('history.deleteAll')}</button>
      </div>
    </div>
  </div>
{/if}

<style>
  .history {
    max-width: 800px;
    margin: 0 auto;
  }

  .filters {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
  }

  .date-range {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
  }

  .date-range input {
    padding: 6px 8px;
    border: 1px solid #3d4f61;
    border-radius: 8px;
    background: #1b2636;
    color: #e0e0e0;
    font-size: 13px;
    max-width: 130px;
  }

  .date-range span {
    color: #6b7280;
  }

  .export-buttons {
    display: flex;
    gap: 8px;
  }

  .export-buttons button {
    padding: 8px 16px;
    background: #3d4f61;
    color: #e0e0e0;
    border: none;
    border-radius: 8px;
    cursor: pointer;
  }

  .export-buttons button:hover {
    background: #4d5f71;
  }

  .export-buttons button:disabled {
    opacity: 0.5;
  }

  section {
    background: #232f3e;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 16px;
  }

  h2 {
    margin: 0 0 16px 0;
    color: #e0e0e0;
  }

  h3 {
    margin: 24px 0 12px 0;
    color: #9ca3af;
    font-size: 16px;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }

  .stat-card {
    background: #1b2636;
    padding: 12px;
    border-radius: 8px;
    text-align: center;
  }

  .stat-value {
    font-size: 22px;
    font-weight: 700;
    color: #4a90d9;
    margin-bottom: 2px;
  }

  .stat-label {
    font-size: 10px;
    color: #6b7280;
    text-transform: uppercase;
  }

  .breakdown-table {
    background: #1b2636;
    border-radius: 8px;
    overflow: hidden;
  }

  .breakdown-header,
  .breakdown-row {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr 1fr 1fr;
    padding: 8px 10px;
    font-size: 12px;
  }

  .breakdown-header {
    background: #3d4f61;
    font-size: 12px;
    text-transform: uppercase;
    color: #9ca3af;
  }

  .breakdown-row {
    border-bottom: 1px solid #3d4f61;
  }

  .breakdown-row:last-child {
    border-bottom: none;
  }

  .breakdown-row .overtime {
    color: #ef4444;
  }

  .session-card {
    background: #1b2636;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
  }

  .session-card.overtime {
    border-left: 4px solid #ef4444;
  }

  .session-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 12px;
  }

  .session-date {
    flex: 1;
    color: #e0e0e0;
  }

  .session-duration {
    font-family: 'SF Mono', 'Menlo', monospace;
    color: #9ca3af;
  }

  .overtime-badge {
    background: #ef4444;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 600;
  }

  .session-participants {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .participant-log {
    display: flex;
    align-items: center;
    gap: 8px;
    background: #232f3e;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 14px;
  }

  .participant-log.log-overtime {
    border: 1px solid #ef4444;
  }

  .participant-log.skipped {
    opacity: 0.6;
  }

  .log-order {
    color: #6b7280;
    font-size: 12px;
  }

  .log-name {
    color: #e0e0e0;
  }

  .log-duration {
    color: #9ca3af;
    font-family: 'SF Mono', 'Menlo', monospace;
    white-space: nowrap;
    display: inline-flex;
    align-items: center;
  }

  .log-duration .overtime {
    color: #ef4444;
  }

  .log-duration .time-sep {
    color: #6b7280;
    margin: 0 3px;
  }

  .log-duration .time-limit {
    color: #6b7280;
  }

  .loading, .empty {
    text-align: center;
    padding: 48px;
    color: #6b7280;
  }

  .delete-all-btn {
    background: #dc2626 !important;
    border-color: #991b1b !important;
  }

  .delete-all-btn:hover {
    background: #b91c1c !important;
  }

  .delete-session-btn {
    margin-left: auto;
    background: transparent;
    border: none;
    cursor: pointer;
    font-size: 16px;
    opacity: 0.5;
    transition: opacity 0.2s;
    padding: 4px 8px;
  }

  .delete-session-btn:hover {
    opacity: 1;
  }

  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }

  .modal {
    background: #1b2636;
    border: 1px solid #3d4f61;
    border-radius: 12px;
    padding: 24px;
    max-width: 400px;
    width: 90%;
  }

  .modal h3 {
    margin: 0 0 12px 0;
    color: #e0e0e0;
    font-size: 18px;
  }

  .modal p {
    margin: 0 0 20px 0;
    color: #9ca3af;
    font-size: 14px;
  }

  .modal-buttons {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }

  .modal-buttons button {
    padding: 8px 16px;
    border-radius: 8px;
    font-size: 14px;
    cursor: pointer;
  }

  .cancel-btn {
    background: #374151;
    border: 1px solid #4b5563;
    color: #e0e0e0;
  }

  .cancel-btn:hover {
    background: #4b5563;
  }

  .confirm-btn {
    background: #dc2626;
    border: 1px solid #991b1b;
    color: white;
  }

  .confirm-btn:hover {
    background: #b91c1c;
  }

  .confirm-btn.danger {
    background: #991b1b;
  }

  .confirm-btn.danger:hover {
    background: #7f1d1d;
  }
</style>
