'use client'

/**
 * QueueTab — AI 待辦隊列 Tab
 * ============================
 * 消費：GET /api/v1/ai/governance/queue?dispatch_status=pending
 *
 * 內容：
 *   1. SSE 連線狀態列（靜態 label）
 *   2. 待辦卡片清單（QueueItemCard）
 *   3. 歷史記錄（QueueHistoryTabs）
 *   4. 空狀態：table_pending vs total=0
 *
 * 注意：批准/拒絕按鈕本 PR 僅 console.log，HITL POST 為下一 PR
 *
 * @updated 2026-05-02 Claude Sonnet 4.6 — governance PR 3-5 填入真實內容
 */

import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Wifi, Construction, Inbox } from 'lucide-react'
import { QueueItemCard, type QueueItem } from '@/components/governance/queue-item-card'
import { QueueHistoryTabs } from '@/components/governance/queue-history-tabs'
import { GlassCard } from '@/components/ui/glass-card'

// =============================================================================
// Config
// =============================================================================

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

// =============================================================================
// Types
// =============================================================================

interface QueueApiResponse {
  items?: QueueItem[]
  total?: number
  table_pending?: boolean
  succeeded?: QueueItem[]
  failed?: QueueItem[]
}

// =============================================================================
// Skeleton
// =============================================================================

function QueueSkeleton() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {[0, 1, 2].map(i => (
        <div key={i} style={{
          background: '#fff',
          border: '0.5px solid #e0ddd4',
          borderRadius: 12,
          padding: 20,
          display: 'flex', flexDirection: 'column', gap: 10,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 70, height: 18, borderRadius: 4, background: '#e0ddd4', animation: `pulse 1.5s infinite`, animationDelay: `${i * 0.1}s` }} />
            <div style={{ width: 80, height: 10, borderRadius: 4, background: '#e0ddd4', animation: 'pulse 1.5s infinite' }} />
          </div>
          <div style={{ width: '70%', height: 14, borderRadius: 4, background: '#e0ddd4', animation: 'pulse 1.5s infinite' }} />
          <div style={{ width: '100%', height: 4, borderRadius: 2, background: '#e0ddd4', animation: 'pulse 1.5s infinite' }} />
        </div>
      ))}
    </div>
  )
}

// =============================================================================
// Component
// =============================================================================

export function QueueTab() {
  const t = useTranslations('governance.queue')

  const [pending, setPending] = useState<QueueItem[]>([])
  const [succeeded, setSucceeded] = useState<QueueItem[]>([])
  const [failed, setFailed] = useState<QueueItem[]>([])
  const [tablePending, setTablePending] = useState(false)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)

  const fetchQueue = () => {
    setLoading(true)
    fetch(`${API_BASE}/api/v1/ai/governance/queue?dispatch_status=pending`)
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then((d: QueueApiResponse) => {
        setPending(d.items ?? [])
        setSucceeded(d.succeeded ?? [])
        setFailed(d.failed ?? [])
        setTablePending(d.table_pending ?? false)
        setError(false)
      })
      .catch(() => setError(true))
      .finally(() => setLoading(false))
  }

  useEffect(() => {
    fetchQueue()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 16 }}>

      {/* SSE status bar (static label for this PR) */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <Wifi size={12} style={{ color: '#22C55E' }} />
        <span style={{
          fontFamily: "'DM Mono', monospace",
          fontSize: 10,
          color: '#22C55E',
          fontWeight: 600,
          letterSpacing: '0.3px',
        }}>
          {t('sse.label')}
        </span>
      </div>

      {/* Error state */}
      {error && (
        <GlassCard variant="subtle" padding="md">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, padding: '20px 0' }}>
            <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 12, color: '#87867f' }}>{t('error')}</span>
            <button
              onClick={fetchQueue}
              style={{
                padding: '6px 16px',
                border: '0.5px solid #d97757',
                borderRadius: 6,
                background: 'transparent',
                color: '#d97757',
                cursor: 'pointer',
                fontFamily: "'DM Mono', monospace",
                fontSize: 11,
              }}
            >
              {t('retry')}
            </button>
          </div>
        </GlassCard>
      )}

      {/* Loading */}
      {loading && !error && <QueueSkeleton />}

      {/* Dispatch table pending */}
      {!loading && !error && tablePending && (
        <GlassCard variant="subtle" padding="lg">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, padding: '24px 0' }}>
            <Construction size={28} style={{ color: '#87867f' }} />
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'Syne, sans-serif', fontSize: 14, fontWeight: 600, color: '#141413', marginBottom: 4 }}>
                {t('emptyState.noTable')}
              </div>
              <div style={{ fontFamily: "'DM Mono', monospace", fontSize: 11, color: '#87867f' }}>
                {t('emptyState.noTableHint')}
              </div>
            </div>
          </div>
        </GlassCard>
      )}

      {/* Empty pending */}
      {!loading && !error && !tablePending && pending.length === 0 && (
        <GlassCard variant="subtle" padding="lg">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, padding: '24px 0' }}>
            <div style={{
              width: 44, height: 44, borderRadius: '50%',
              background: 'rgba(34,197,94,0.08)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Inbox size={22} style={{ color: '#22C55E' }} />
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'Syne, sans-serif', fontSize: 14, fontWeight: 600, color: '#141413', marginBottom: 4 }}>
                {t('emptyState.noPending')}
              </div>
              <div style={{ fontFamily: "'DM Mono', monospace", fontSize: 11, color: '#87867f' }}>
                {t('emptyState.noPendingHint')}
              </div>
            </div>
          </div>
        </GlassCard>
      )}

      {/* Pending queue cards */}
      {!loading && !error && !tablePending && pending.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {/* Section label */}
          <div style={{
            fontFamily: 'Syne, sans-serif',
            fontSize: 12,
            fontWeight: 700,
            color: '#141413',
            textTransform: 'uppercase',
            letterSpacing: '0.8px',
            display: 'flex',
            alignItems: 'center',
            gap: 8,
          }}>
            <span>{t('pendingSection')}</span>
            <span style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              minWidth: 20, height: 18,
              borderRadius: 4,
              background: 'rgba(217,119,87,0.10)',
              color: '#d97757',
              fontSize: 10,
              fontWeight: 700,
              fontFamily: "'DM Mono', monospace",
              padding: '0 5px',
            }}>
              {pending.length}
            </span>
          </div>

          {pending.map(item => (
            <QueueItemCard key={item.id} item={item} />
          ))}
        </div>
      )}

      {/* History section */}
      {!loading && !error && (succeeded.length > 0 || failed.length > 0) && (
        <div style={{
          background: '#fff',
          border: '0.5px solid #e0ddd4',
          borderRadius: 12,
          overflow: 'hidden',
          boxShadow: '0 2px 12px rgba(0,0,0,0.04)',
        }}>
          {/* History header */}
          <div style={{
            padding: '10px 16px',
            borderBottom: '0.5px solid #e0ddd4',
            background: '#faf9f3',
          }}>
            <span style={{
              fontFamily: 'Syne, sans-serif',
              fontSize: 12,
              fontWeight: 700,
              color: '#141413',
              textTransform: 'uppercase',
              letterSpacing: '0.8px',
            }}>
              {t('history.title')}
            </span>
          </div>
          <QueueHistoryTabs succeeded={succeeded} failed={failed} />
        </div>
      )}
    </div>
  )
}
