'use client'

/**
 * TicketsPanel — 工單追蹤面板 (不含 AppLayout)
 * ==============================================
 * Sprint 5: 從 /tickets/page.tsx 抽取
 * 供原始頁面和整合頁面 (/operations) 共用
 *
 * 建立時間: 2026-04-09 (台北時區)
 */

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? ''

interface Incident {
  id: string
  title: string
  severity: string
  status: string
  created_at: string
  affected_service: string | null
}

interface IncidentListResponse {
  incidents: Incident[]
  total: number
}

const SEV_COLOR: Record<string, string> = {
  P0: '#cc2200',
  P1: '#F59E0B',
  P2: '#4A90D9',
  P3: '#22C55E',
}

const STATUS_COLOR: Record<string, string> = {
  open: '#cc2200',
  in_progress: '#F59E0B',
  resolved: '#22C55E',
  closed: '#87867f',
}

export function TicketsPanel() {
  const t = useTranslations('tickets')
  const [incidents, setIncidents] = useState<Incident[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetch(`${API_BASE}/api/v1/incidents`)
      .then(r => r.json())
      .then((data: IncidentListResponse) => {
        setIncidents(data.incidents ?? [])
        setTotal(data.total ?? 0)
        setLoading(false)
      })
      .catch(err => { setError(String(err)); setLoading(false) })
  }, [])

  return (
    <div style={{ padding: '24px', background: '#f5f4ed', minHeight: '100%' }}>
      <div style={{ marginBottom: '20px' }}>
        <h1 style={{ fontSize: 18, fontWeight: 700, color: '#141413', margin: 0, fontFamily: 'var(--font-body), monospace' }}>{t('title')}</h1>
        <p style={{ fontSize: 12, color: '#87867f', margin: '4px 0 0', fontFamily: 'var(--font-body), monospace' }}>{t('subtitle')}</p>
      </div>
      <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, fontWeight: 700, padding: '10px 14px', borderBottom: '0.5px solid #e0ddd4', background: '#faf9f3', fontFamily: 'var(--font-body), monospace', color: '#141413' }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#d97757', display: 'inline-block' }} />
          {t('title')} ({loading ? '...' : total})
        </div>
        {loading ? (
          <div style={{ padding: '32px', textAlign: 'center', color: '#87867f', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>{t('loading')}</div>
        ) : error ? (
          <div style={{ padding: '32px', textAlign: 'center', color: '#cc2200', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>{t('error')}</div>
        ) : incidents.length === 0 ? (
          <div style={{ padding: '32px', textAlign: 'center', color: '#87867f', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>{t('noTickets')}</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>
            <thead>
              <tr style={{ background: '#faf9f3' }}>
                {[t('id'), t('title_col'), t('priority'), t('status'), t('createdAt')].map(col => (
                  <th key={col} style={{ padding: '8px 14px', textAlign: 'left', fontWeight: 600, color: '#87867f', borderBottom: '0.5px solid #e0ddd4', fontSize: 11 }}>{col}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {incidents.map((inc) => (
                <tr key={inc.id} style={{ borderBottom: '0.5px solid #f0ede4' }}>
                  <td style={{ padding: '8px 14px', color: '#87867f', fontSize: 11, fontFamily: 'monospace' }}>{inc.id.slice(0, 8)}</td>
                  <td style={{ padding: '8px 14px', fontWeight: 500, color: '#141413', maxWidth: 300 }}>
                    <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{inc.title}</div>
                    {inc.affected_service && (
                      <div style={{ fontSize: 11, color: '#87867f', marginTop: 2 }}>{inc.affected_service}</div>
                    )}
                  </td>
                  <td style={{ padding: '8px 14px' }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: SEV_COLOR[inc.severity] ?? '#87867f', background: `${SEV_COLOR[inc.severity] ?? '#87867f'}18`, border: `0.5px solid ${SEV_COLOR[inc.severity] ?? '#87867f'}40`, borderRadius: 4, padding: '1px 6px' }}>
                      {inc.severity}
                    </span>
                  </td>
                  <td style={{ padding: '8px 14px' }}>
                    <span style={{ fontSize: 11, fontWeight: 600, color: STATUS_COLOR[inc.status] ?? '#87867f' }}>
                      {inc.status}
                    </span>
                  </td>
                  <td style={{ padding: '8px 14px', color: '#87867f', fontSize: 11 }}>
                    {new Date(inc.created_at).toLocaleString('zh-TW', { timeZone: 'Asia/Taipei', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  )
}
