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

const fetchSessions = async ({ status, topic_sensitivity, page }) => {
  const params = new URLSearchParams()
  if (status) params.set('status', status)
  if (topic_sensitivity && topic_sensitivity !== 'all') params.set('topic_sensitivity', topic_sensitivity)
  params.set('page', page)
  params.set('limit', '20')
  const res = await apiClient.get(`/internal/sessions?${params}`)
  return res.data.data
}

const fetchOnlineMitras = async () => {
  const res = await apiClient.get('/internal/mitras/online')
  return res.data.data
}

const rerouteSession = async ({ sessionId, new_mitra_id }) => {
  const res = await apiClient.post(`/internal/sessions/${sessionId}/reroute`, { new_mitra_id })
  return res.data.data
}

const fetchSessionDetail = async (sessionId) => {
  const res = await apiClient.get(`/internal/sessions/${sessionId}`)
  return res.data.data
}

const STATUS_OPTIONS = [
  { value: '', label: 'Semua' },
  { value: 'active', label: 'Aktif' },
  { value: 'pending_acceptance', label: 'Menunggu Mitra' },
  { value: 'pending_payment', label: 'Menunggu Bayar' },
  { value: 'completed', label: 'Selesai' },
  { value: 'cancelled', label: 'Dibatalkan' },
  { value: 'expired', label: 'Kedaluwarsa' },
]

const TOPIC_OPTIONS = [
  { value: 'all', label: 'Semua' },
  { value: 'regular', label: 'Umum' },
  { value: 'sensitive', label: 'Sensitif' },
]

export default function SessionsPage() {
  const queryClient = useQueryClient()
  const [statusFilter, setStatusFilter] = useState('')
  const [topicFilter, setTopicFilter] = useState('all')
  const [page, setPage] = useState(1)
  const [rerouteTarget, setRerouteTarget] = useState({})
  const [expandedId, setExpandedId] = useState(null)
  const [detail, setDetail] = useState(null)
  const [detailLoading, setDetailLoading] = useState(false)

  const toggleExpand = async (sessionId) => {
    if (expandedId === sessionId) {
      setExpandedId(null)
      setDetail(null)
      return
    }
    setExpandedId(sessionId)
    setDetail(null)
    setDetailLoading(true)
    try {
      const d = await fetchSessionDetail(sessionId)
      setDetail(d)
    } catch (_) {
      setDetail({ error: true })
    } finally {
      setDetailLoading(false)
    }
  }

  const { data, isLoading } = useQuery({
    queryKey: ['sessions', statusFilter, topicFilter, page],
    queryFn: () => fetchSessions({ status: statusFilter, topic_sensitivity: topicFilter, page }),
    refetchInterval: 10000,
  })

  const { data: onlineMitras } = useQuery({
    queryKey: ['mitras-online-for-reroute'],
    queryFn: fetchOnlineMitras,
  })

  const rerouteMutation = useMutation({
    mutationFn: rerouteSession,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['sessions'] })
      setRerouteTarget({})
    },
  })

  if (isLoading) return <div>Loading...</div>

  return (
    <div>
      <h1>Sesi</h1>

      <div style={{ marginBottom: 16, display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <label>Status: </label>
          <select value={statusFilter} onChange={e => { setStatusFilter(e.target.value); setPage(1) }}>
            {STATUS_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <label>Topik: </label>
          <select value={topicFilter} onChange={e => { setTopicFilter(e.target.value); setPage(1) }}>
            {TOPIC_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </div>
      </div>

      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Customer</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Mitra</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Status</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Topik</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Waktu</th>
            <th style={{ padding: 8, borderBottom: '1px solid #eee' }}>Aksi</th>
          </tr>
        </thead>
        <tbody>
          {data?.items?.map((session) => (
            <React.Fragment key={session.id}>
            <tr>
              <td style={{ padding: 8 }}>{session.customer_display_name}</td>
              <td style={{ padding: 8 }}>{session.mitra_display_name ?? '-'}</td>
              <td style={{ padding: 8 }}>{session.status}</td>
              <td style={{ padding: 8 }}>
                {session.topic_sensitivity === 'sensitive' ? (
                  <span style={{ background: '#F7B500', color: '#3D2A00', padding: '2px 8px', borderRadius: 999, fontSize: 12, fontWeight: 600 }}>
                    Sensitif
                  </span>
                ) : (
                  <span style={{ color: '#666', fontSize: 12 }}>Umum</span>
                )}
              </td>
              <td style={{ padding: 8 }}>{new Date(session.created_at).toLocaleString('id-ID')}</td>
              <td style={{ padding: 8 }}>
                <div style={{ display: 'flex', gap: 4, alignItems: 'center', flexWrap: 'wrap' }}>
                  <button onClick={() => toggleExpand(session.id)} style={{ fontSize: 12 }}>
                    {expandedId === session.id ? 'Tutup' : 'Detail'}
                  </button>
                  {['active', 'pending_payment'].includes(session.status) && (
                    <>
                      <select
                        value={rerouteTarget[session.id] ?? ''}
                        onChange={e => setRerouteTarget(t => ({ ...t, [session.id]: e.target.value }))}
                        style={{ fontSize: 12 }}
                      >
                        <option value="">Reroute ke...</option>
                        {(onlineMitras ?? [])
                          .filter(m => m.id !== session.mitra_id)
                          .map(m => <option key={m.id} value={m.id}>{m.display_name}</option>)}
                      </select>
                      <button
                        disabled={!rerouteTarget[session.id] || rerouteMutation.isPending}
                        onClick={() => rerouteMutation.mutate({
                          sessionId: session.id,
                          new_mitra_id: rerouteTarget[session.id],
                        })}
                        style={{ fontSize: 12 }}
                      >
                        Reroute
                      </button>
                    </>
                  )}
                </div>
              </td>
            </tr>
            {expandedId === session.id && (
              <tr>
                <td colSpan={6} style={{ padding: 16, background: '#fafafa' }}>
                  {detailLoading && <div>Memuat detail…</div>}
                  {detail?.error && <div style={{ color: 'red' }}>Gagal memuat detail sesi.</div>}
                  {detail && !detail.error && (
                    <div>
                      <h3 style={{ margin: '0 0 8px' }}>Riwayat Topik Sensitif</h3>
                      {(!detail.sensitivity_log || detail.sensitivity_log.length === 0) ? (
                        <p style={{ color: '#666', fontSize: 13 }}>Belum ada perubahan topik oleh Mitra.</p>
                      ) : (
                        <ul style={{ margin: 0, paddingLeft: 20 }}>
                          {detail.sensitivity_log.map(log => (
                            <li key={log.id} style={{ fontSize: 13, marginBottom: 4 }}>
                              <strong>{log.changed_by_mitra_name ?? 'Mitra'}</strong>{' '}
                              mengubah dari <code>{log.from_value}</code> menjadi <code>{log.to_value}</code>
                              {' '}pada {new Date(log.created_at).toLocaleString('id-ID')}
                            </li>
                          ))}
                        </ul>
                      )}
                    </div>
                  )}
                </td>
              </tr>
            )}
            </React.Fragment>
          ))}
        </tbody>
      </table>

      {data && (
        <div style={{ marginTop: 16, display: 'flex', gap: 8, justifyContent: 'center' }}>
          <button disabled={page <= 1} onClick={() => setPage(p => p - 1)}>Prev</button>
          <span>Halaman {data.page} dari {Math.ceil(data.total / data.limit) || 1}</span>
          <button disabled={page >= Math.ceil(data.total / data.limit)} onClick={() => setPage(p => p + 1)}>Next</button>
        </div>
      )}

      {rerouteMutation.isError && <p style={{ color: 'red', marginTop: 8 }}>Gagal reroute sesi.</p>}
    </div>
  )
}
