import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { apiClient } from '../../core/api/api-client'

const fetchSummary = async ({ mitra_id, date_from, date_to }) => {
  const params = new URLSearchParams()
  if (mitra_id) params.set('mitra_id', mitra_id)
  if (date_from) params.set('date_from', date_from)
  if (date_to) params.set('date_to', date_to)
  const res = await apiClient.get(`/internal/mitra-activity/summary?${params}`)
  return res.data.data
}

const fetchLog = async ({ mitra_id, date_from, date_to, page, limit }) => {
  const params = new URLSearchParams()
  if (mitra_id) params.set('mitra_id', mitra_id)
  if (date_from) params.set('date_from', date_from)
  if (date_to) params.set('date_to', date_to)
  params.set('page', String(page))
  params.set('limit', String(limit))
  const res = await apiClient.get(`/internal/mitra-activity/log?${params}`)
  return res.data.data
}

const fetchMitras = async () => {
  const res = await apiClient.get('/internal/mitras?limit=100')
  return res.data.data.items
}

const responseColor = (response) => {
  switch (response) {
    case 'accepted': return '#22c55e'
    case 'declined': return '#ef4444'
    case 'missed': return '#f97316'
    case 'ignored': return '#9ca3af'
    default: return '#6b7280'
  }
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const d = new Date(dateStr)
  return `${d.toLocaleDateString('id-ID')} ${d.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })}`
}

export default function MitraActivityPage() {
  const [mitraFilter, setMitraFilter] = useState('')
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')
  const [logPage, setLogPage] = useState(1)
  const logLimit = 20

  const filters = { mitra_id: mitraFilter || undefined, date_from: dateFrom || undefined, date_to: dateTo || undefined }

  const { data: mitras } = useQuery({ queryKey: ['mitras-list'], queryFn: fetchMitras })

  const { data: summary, isLoading: summaryLoading } = useQuery({
    queryKey: ['mitra-activity-summary', filters],
    queryFn: () => fetchSummary(filters),
  })

  const { data: logData, isLoading: logLoading } = useQuery({
    queryKey: ['mitra-activity-log', filters, logPage],
    queryFn: () => fetchLog({ ...filters, page: logPage, limit: logLimit }),
  })

  return (
    <div>
      <h1>Aktivitas Mitra</h1>

      <div style={{ display: 'flex', gap: 12, marginBottom: 24, flexWrap: 'wrap', alignItems: 'end' }}>
        <div>
          <label style={{ display: 'block', fontSize: 12, marginBottom: 4 }}>Mitra</label>
          <select value={mitraFilter} onChange={e => { setMitraFilter(e.target.value); setLogPage(1) }} style={{ padding: '6px 8px' }}>
            <option value="">Semua Mitra</option>
            {(mitras || []).map(m => (
              <option key={m.id} value={m.id}>{m.display_name}</option>
            ))}
          </select>
        </div>
        <div>
          <label style={{ display: 'block', fontSize: 12, marginBottom: 4 }}>Dari</label>
          <input type="date" value={dateFrom} onChange={e => { setDateFrom(e.target.value); setLogPage(1) }} />
        </div>
        <div>
          <label style={{ display: 'block', fontSize: 12, marginBottom: 4 }}>Sampai</label>
          <input type="date" value={dateTo} onChange={e => { setDateTo(e.target.value); setLogPage(1) }} />
        </div>
      </div>

      <section style={{ marginBottom: 32 }}>
        <h2>Ringkasan</h2>
        {summaryLoading ? <p>Loading...</p> : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ borderBottom: '2px solid #ddd', textAlign: 'left' }}>
                <th style={{ padding: 8 }}>Mitra</th>
                <th style={{ padding: 8 }}>Total</th>
                <th style={{ padding: 8 }}>Accepted</th>
                <th style={{ padding: 8 }}>Rejected</th>
                <th style={{ padding: 8 }}>Missed</th>
                <th style={{ padding: 8 }}>Ignored</th>
                <th style={{ padding: 8 }}>Rate (%)</th>
                <th style={{ padding: 8 }}>Avg Response (s)</th>
                <th style={{ padding: 8, background: '#FFF8DF' }}>Sensitif Total</th>
                <th style={{ padding: 8, background: '#FFF8DF' }}>Sensitif Diterima</th>
                <th style={{ padding: 8, background: '#FFF8DF' }}>Sensitif Rate (%)</th>
              </tr>
            </thead>
            <tbody>
              {(summary || []).map(s => {
                const overall = s.acceptance_rate != null ? Number(s.acceptance_rate) : null
                const sensRate = s.sensitive_acceptance_rate != null ? Number(s.sensitive_acceptance_rate) : null
                const flagSensRate = overall != null && sensRate != null && (overall - sensRate) >= 20
                return (
                  <tr key={s.mitra_id} style={{ borderBottom: '1px solid #eee' }}>
                    <td style={{ padding: 8 }}>{s.mitra_display_name}</td>
                    <td style={{ padding: 8 }}>{s.total_requests}</td>
                    <td style={{ padding: 8, color: '#22c55e' }}>{s.accepted_count}</td>
                    <td style={{ padding: 8, color: '#ef4444' }}>{s.rejected_count}</td>
                    <td style={{ padding: 8, color: '#f97316' }}>{s.missed_count}</td>
                    <td style={{ padding: 8, color: '#9ca3af' }}>{s.ignored_count}</td>
                    <td style={{ padding: 8 }}>{s.acceptance_rate ?? '-'}%</td>
                    <td style={{ padding: 8 }}>{s.avg_response_time_seconds ?? '-'}</td>
                    <td style={{ padding: 8 }}>{s.sensitive_total || 0}</td>
                    <td style={{ padding: 8 }}>{s.sensitive_accepted || 0}</td>
                    <td style={{ padding: 8, color: flagSensRate ? '#ef4444' : undefined, fontWeight: flagSensRate ? 'bold' : undefined }}>
                      {(s.sensitive_total || 0) === 0 ? '—' : `${s.sensitive_acceptance_rate ?? 0}%`}
                    </td>
                  </tr>
                )
              })}
              {(!summary || summary.length === 0) && (
                <tr><td colSpan={11} style={{ padding: 16, textAlign: 'center', color: '#999' }}>Tidak ada data</td></tr>
              )}
            </tbody>
          </table>
        )}
      </section>

      <section>
        <h2>Detail Log</h2>
        {logLoading ? <p>Loading...</p> : (
          <>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ borderBottom: '2px solid #ddd', textAlign: 'left' }}>
                  <th style={{ padding: 8 }}>Mitra</th>
                  <th style={{ padding: 8 }}>Session</th>
                  <th style={{ padding: 8 }}>Topik</th>
                  <th style={{ padding: 8 }}>Response</th>
                  <th style={{ padding: 8 }}>Response Time (s)</th>
                  <th style={{ padding: 8 }}>Active Sessions</th>
                  <th style={{ padding: 8 }}>Notified At</th>
                  <th style={{ padding: 8 }}>Responded At</th>
                </tr>
              </thead>
              <tbody>
                {(logData?.items || []).map(item => (
                  <tr key={item.id} style={{ borderBottom: '1px solid #eee' }}>
                    <td style={{ padding: 8 }}>{item.mitra_display_name}</td>
                    <td style={{ padding: 8, fontSize: 11, fontFamily: 'monospace' }}>{item.session_id?.substring(0, 8)}...</td>
                    <td style={{ padding: 8 }}>
                      {item.topic_sensitivity === 'sensitive' ? (
                        <span style={{ background: '#F7B500', color: '#3D2A00', padding: '2px 6px', borderRadius: 999, fontSize: 11, fontWeight: 600 }}>Sensitif</span>
                      ) : (
                        <span style={{ color: '#666', fontSize: 11 }}>Umum</span>
                      )}
                    </td>
                    <td style={{ padding: 8 }}>
                      <span style={{ color: responseColor(item.response), fontWeight: 'bold' }}>
                        {item.response || '-'}
                      </span>
                    </td>
                    <td style={{ padding: 8 }}>{item.response_time_seconds ?? '-'}</td>
                    <td style={{ padding: 8 }}>{item.active_session_count}</td>
                    <td style={{ padding: 8, fontSize: 12 }}>{formatDate(item.notified_at)}</td>
                    <td style={{ padding: 8, fontSize: 12 }}>{formatDate(item.responded_at)}</td>
                  </tr>
                ))}
                {(!logData?.items || logData.items.length === 0) && (
                  <tr><td colSpan={8} style={{ padding: 16, textAlign: 'center', color: '#999' }}>Tidak ada data</td></tr>
                )}
              </tbody>
            </table>
            {logData && logData.total > logLimit && (
              <div style={{ display: 'flex', gap: 8, marginTop: 12, alignItems: 'center' }}>
                <button disabled={logPage <= 1} onClick={() => setLogPage(p => p - 1)}>Prev</button>
                <span>Halaman {logData.page} dari {Math.ceil(logData.total / logLimit)}</span>
                <button disabled={logPage >= Math.ceil(logData.total / logLimit)} onClick={() => setLogPage(p => p + 1)}>Next</button>
              </div>
            )}
          </>
        )}
      </section>
    </div>
  )
}
