'use client'

/**
 * ConversationalView - 對話式 AI 審核介面
 * ========================================
 * Phase 11: ChatGPT / GitHub Copilot 風格
 * Phase 11.3: 響應式佈局 (#54-55)
 *
 * Features:
 * - 左側: ApprovalThread 對話列表
 * - 右側: ApprovalCard 詳情面板
 * - 鍵盤快捷鍵: Y/N/方向鍵
 * - 響應式:
 *   - Desktop (≥1024px): 雙欄並排
 *   - Tablet (768-1024px): 滑動切換 (#54)
 *   - Mobile (<768px): 全螢幕詳情模式 (#55)
 *
 * i18n: 100% next-intl
 *
 * @modified 2026-03-26 v11.3.0 (TPE) - Phase 11.3 響應式佈局
 */

import { useState, useCallback, useEffect, useMemo, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { cn } from '@/lib/utils'
import { Z_INDEX, CURRENT_USER } from '@/lib/constants'
import {
  useApprovalStore,
  usePendingApprovals,
  toFrontendApproval,
} from '@/stores/approval.store'
import { useApprovalSSE } from '@/hooks/useApprovalSSE'
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts'
import { ApprovalCard } from './approval-card'
import { ApprovalThreadItem } from './approval-thread-item'
import { StatusOrb } from '@/components/ui/status-orb'
import {
  MessageSquare,
  ChevronLeft,
  ChevronRight,
  Keyboard,
  Wifi,
  WifiOff,
  ArrowLeft,
} from 'lucide-react'

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

interface ConversationalViewProps {
  className?: string
  /** 簽核者 ID */
  signerId?: string
  /** 簽核者名稱 */
  signerName?: string
}

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

export function ConversationalView({
  className,
  signerId = CURRENT_USER.id,
  signerName = CURRENT_USER.name,
}: ConversationalViewProps) {
  const t = useTranslations('approval')
  const tCommon = useTranslations('common')

  // Store
  const { signApproval, rejectApproval } = useApprovalStore()
  const pendingApprovals = usePendingApprovals()

  // SSE 連線狀態
  const { isConnected, status: sseStatus } = useApprovalSSE({ autoConnect: true })

  // 選中的 Approval
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [showShortcuts, setShowShortcuts] = useState(false)

  // Phase 11.3: 響應式面板狀態 (#54-55)
  // Mobile/Tablet: 控制是否顯示詳情面板
  const [showDetailPanel, setShowDetailPanel] = useState(false)

  // Phase 11.3: 觸控滑動支援
  const containerRef = useRef<HTMLDivElement>(null)
  const touchStartX = useRef<number>(0)
  const touchDeltaX = useRef<number>(0)

  // 轉換為前端格式
  const approvals = useMemo(() => {
    return pendingApprovals.map((a) => toFrontendApproval(a))
  }, [pendingApprovals])

  // 當前選中的 index
  const selectedIndex = useMemo(() => {
    if (!selectedId) return -1
    return approvals.findIndex((a) => a.id === selectedId)
  }, [selectedId, approvals])

  // 選中的 Approval 詳情
  const selectedApproval = useMemo(() => {
    return approvals.find((a) => a.id === selectedId) || null
  }, [selectedId, approvals])

  // 自動選中第一個
  useEffect(() => {
    if (!selectedId && approvals.length > 0) {
      setSelectedId(approvals[0].id)
    }
    // 如果選中的已被處理，選下一個
    if (selectedId && !approvals.find((a) => a.id === selectedId)) {
      if (approvals.length > 0) {
        setSelectedId(approvals[0].id)
      } else {
        setSelectedId(null)
      }
      // Phase 11.3: 關閉詳情面板
      setShowDetailPanel(false)
    }
  }, [approvals, selectedId])

  // Phase 11.3: 選擇項目並顯示詳情面板 (#54-55)
  const handleSelectApproval = useCallback((id: string) => {
    setSelectedId(id)
    setShowDetailPanel(true)
  }, [])

  // Phase 11.3: 返回列表 (#55)
  const handleBackToList = useCallback(() => {
    setShowDetailPanel(false)
  }, [])

  // Phase 11.3: 觸控滑動處理 (#54 Tablet)
  const handleTouchStart = useCallback((e: React.TouchEvent) => {
    touchStartX.current = e.touches[0].clientX
    touchDeltaX.current = 0
  }, [])

  const handleTouchMove = useCallback((e: React.TouchEvent) => {
    touchDeltaX.current = e.touches[0].clientX - touchStartX.current
  }, [])

  const handleTouchEnd = useCallback(() => {
    const threshold = 80 // 最小滑動距離
    if (touchDeltaX.current > threshold && showDetailPanel) {
      // 向右滑動：返回列表
      setShowDetailPanel(false)
    } else if (touchDeltaX.current < -threshold && !showDetailPanel && selectedId) {
      // 向左滑動：顯示詳情
      setShowDetailPanel(true)
    }
    touchDeltaX.current = 0
  }, [showDetailPanel, selectedId])

  // 導航函數
  const goToPrev = useCallback(() => {
    if (selectedIndex > 0) {
      setSelectedId(approvals[selectedIndex - 1].id)
    }
  }, [selectedIndex, approvals])

  const goToNext = useCallback(() => {
    if (selectedIndex < approvals.length - 1) {
      setSelectedId(approvals[selectedIndex + 1].id)
    }
  }, [selectedIndex, approvals])

  // 簽核/拒絕處理
  const handleApprove = useCallback(async (id: string) => {
    await signApproval(id, signerId, signerName, 'Approved via Conversational UI')
  }, [signApproval, signerId, signerName])

  const handleReject = useCallback(async (id: string) => {
    await rejectApproval(id, signerId, signerName, 'Rejected via Conversational UI')
  }, [rejectApproval, signerId, signerName])

  // 鍵盤快捷鍵 (Phase 11.4: Y/N 支援)
  const { isYKeyHolding, yKeyProgress } = useKeyboardShortcuts({
    holdDuration: 2000,
    onApprove: useCallback(() => {
      if (selectedId) {
        handleApprove(selectedId)
      }
    }, [selectedId, handleApprove]),
    onReject: useCallback(() => {
      if (selectedId) {
        handleReject(selectedId)
      }
    }, [selectedId, handleReject]),
    onPrev: goToPrev,
    onNext: goToNext,
    onShowShortcuts: useCallback(() => setShowShortcuts((s) => !s), []),
    onClose: useCallback(() => setShowShortcuts(false), []),
    enabled: selectedApproval !== null,
  })

  return (
    <div
      ref={containerRef}
      className={cn('flex h-full bg-nothing-gray-50 overflow-hidden', className)}
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
    >
      {/* Phase 11.3: 響應式佈局容器 (#54-55) */}
      {/*
        Desktop (≥1024px): 正常 flex 雙欄，左側固定 w-80，右側 flex-1
        Tablet (768-1024px): 200% 寬度 + transform 滑動切換
        Mobile (<768px): 列表全寬 + 詳情 fixed overlay
      */}

      {/* 左側: 對話列表 */}
      <div className={cn(
        'flex-shrink-0 border-r border-nothing-gray-200 bg-white flex flex-col',
        // Desktop (≥1024px): 固定寬度，永遠顯示
        'lg:w-80',
        // Tablet (768-1024px): 50% 寬度用於滑動 (#54)
        'md:w-1/2',
        // Mobile (<768px): 全寬，詳情時隱藏 (#55)
        'w-full',
        // Mobile: 詳情面板打開時隱藏列表
        showDetailPanel && 'hidden md:flex'
      )}>
        {/* 列表 Header */}
        <div className="flex-shrink-0 p-4 border-b border-nothing-gray-100">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <MessageSquare className="w-5 h-5 text-claw-blue" />
              <h2 className="font-heading text-base font-bold text-nothing-gray-900">
                {t('pendingApprovals')}
              </h2>
            </div>
            <div className="flex items-center gap-2">
              {/* SSE 連線狀態 */}
              <div
                className={cn(
                  'flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-body',
                  isConnected
                    ? 'bg-status-healthy/10 text-status-healthy'
                    : 'bg-status-warning/10 text-status-warning'
                )}
                title={`SSE: ${sseStatus}`}
              >
                {isConnected ? (
                  <Wifi className="w-3 h-3" />
                ) : (
                  <WifiOff className="w-3 h-3" />
                )}
                <span>{approvals.length}</span>
              </div>
              {/* 快捷鍵提示 */}
              <button
                onClick={() => setShowShortcuts((s) => !s)}
                className="p-1.5 rounded-lg hover:bg-nothing-gray-100 transition-colors"
                title={`${tCommon('keyboardShortcuts')} (?)`}
              >
                <Keyboard className="w-4 h-4 text-nothing-gray-400" />
              </button>
            </div>
          </div>

          {/* 導航提示 */}
          {approvals.length > 1 && (
            <div className="mt-2 flex items-center justify-between text-xs text-nothing-gray-400">
              <span className="font-body">
                {selectedIndex + 1} / {approvals.length}
              </span>
              <div className="flex items-center gap-1">
                <button
                  onClick={goToPrev}
                  disabled={selectedIndex <= 0}
                  className={cn(
                    'p-1 rounded transition-colors',
                    selectedIndex <= 0
                      ? 'text-nothing-gray-300 cursor-not-allowed'
                      : 'hover:bg-nothing-gray-100 text-nothing-gray-500'
                  )}
                >
                  <ChevronLeft className="w-4 h-4" />
                </button>
                <button
                  onClick={goToNext}
                  disabled={selectedIndex >= approvals.length - 1}
                  className={cn(
                    'p-1 rounded transition-colors',
                    selectedIndex >= approvals.length - 1
                      ? 'text-nothing-gray-300 cursor-not-allowed'
                      : 'hover:bg-nothing-gray-100 text-nothing-gray-500'
                  )}
                >
                  <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            </div>
          )}
        </div>

        {/* 列表內容 */}
        <div className="flex-1 overflow-y-auto p-2 space-y-2">
          {approvals.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-nothing-gray-400">
              <StatusOrb status="healthy" size="lg" />
              <p className="mt-4 text-sm font-body">{t('noPendingApprovals')}</p>
            </div>
          ) : (
            approvals.map((approval) => (
              <ApprovalThreadItem
                key={approval.id}
                approval={approval}
                isSelected={approval.id === selectedId}
                onSelect={() => handleSelectApproval(approval.id)}
              />
            ))
          )}
        </div>
      </div>

      {/* 右側: 詳情面板 */}
      {/*
        Desktop (≥1024px): flex-1 填滿剩餘空間
        Tablet (768-1024px): 50% 寬度 (#54)
        Mobile (<768px): fixed 全屏覆蓋 (#55)
      */}
      <div
        className={cn(
          'flex flex-col overflow-hidden relative bg-nothing-gray-50',
          // Desktop (≥1024px): 填滿剩餘空間，永遠顯示
          'lg:flex-1 lg:relative lg:inset-auto lg:z-auto',
          // Tablet (768-1024px): 50% 寬度 (#54)
          'md:flex md:w-1/2 md:relative md:inset-auto md:z-auto',
          // Mobile (<768px): 全屏覆蓋模式 (#55)
          showDetailPanel
            ? 'fixed inset-0 w-full'
            : 'hidden'
        )}
        style={showDetailPanel ? { zIndex: Z_INDEX.SIDEBAR } : undefined}
      >
          {/* Phase 11.3: Mobile/Tablet 返回按鈕 (#55) */}
          <div className={cn(
            'flex-shrink-0 flex items-center justify-between p-4 border-b border-nothing-gray-200 bg-white',
            // Desktop: 隱藏返回按鈕
            'lg:hidden'
          )}>
            <button
              onClick={handleBackToList}
              className="flex items-center gap-2 text-claw-blue hover:text-claw-blue/80 transition-colors focus:outline-none focus:ring-2 focus:ring-claw-blue/50 rounded-lg px-2 py-1 -ml-2"
              aria-label={t('backToList')}
            >
              <ArrowLeft className="w-5 h-5" aria-hidden="true" />
              <span className="text-sm font-medium">{t('backToList')}</span>
            </button>
            <div className="flex items-center gap-2">
              {/* 分頁指示器 */}
              <div className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-body bg-nothing-gray-100">
                <span>{selectedIndex + 1} / {approvals.length}</span>
              </div>
              {/* 快速導航按鈕 */}
              <div className="flex items-center gap-1">
                <button
                  onClick={goToPrev}
                  disabled={selectedIndex <= 0}
                  className={cn(
                    'p-1.5 rounded-lg transition-colors',
                    selectedIndex <= 0
                      ? 'text-nothing-gray-300 cursor-not-allowed'
                      : 'text-nothing-gray-600 hover:bg-nothing-gray-100 active:bg-nothing-gray-200'
                  )}
                  aria-label={t('previousApproval')}
                >
                  <ChevronLeft className="w-4 h-4" aria-hidden="true" />
                </button>
                <button
                  onClick={goToNext}
                  disabled={selectedIndex >= approvals.length - 1}
                  className={cn(
                    'p-1.5 rounded-lg transition-colors',
                    selectedIndex >= approvals.length - 1
                      ? 'text-nothing-gray-300 cursor-not-allowed'
                      : 'text-nothing-gray-600 hover:bg-nothing-gray-100 active:bg-nothing-gray-200'
                  )}
                  aria-label={t('nextApproval')}
                >
                  <ChevronRight className="w-4 h-4" aria-hidden="true" />
                </button>
              </div>
            </div>
          </div>

          {/* Y 鍵長按進度指示器 */}
          {isYKeyHolding && (
            <div className="absolute top-0 left-0 right-0 h-1 bg-nothing-gray-200 z-10 lg:top-0">
              <div
                className="h-full bg-status-healthy transition-all duration-100"
                style={{ width: `${yKeyProgress}%` }}
              />
            </div>
          )}

          {selectedApproval ? (
            <div className="flex-1 overflow-y-auto p-4 md:p-6">
              <ApprovalCard
                request={selectedApproval}
                onApprove={handleApprove}
                onReject={handleReject}
                holdDuration={2000}
              />
            </div>
          ) : (
            <div className="flex-1 flex items-center justify-center">
              <div className="text-center text-nothing-gray-400">
                <MessageSquare className="w-12 h-12 mx-auto mb-4 opacity-50" aria-hidden="true" />
                <p className="text-sm font-body">{t('selectApproval')}</p>
              </div>
            </div>
          )}
      </div>

      {/* 快捷鍵說明 Modal */}
      {showShortcuts && (
        <div
          className="fixed inset-0 flex items-center justify-center bg-black/50"
          style={{ zIndex: Z_INDEX.DIALOG }}
          onClick={() => setShowShortcuts(false)}
        >
          <div
            className="bg-white rounded-xl shadow-2xl p-6 max-w-sm w-full mx-4"
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="font-heading text-lg font-bold text-nothing-gray-900 mb-4">
              {tCommon('keyboardShortcuts')}
            </h3>
            <div className="space-y-3">
              <ShortcutRow keys={['Y']} label={t('holdYToApprove')} highlight />
              <ShortcutRow keys={['N']} label={t('pressNToReject')} />
              <ShortcutRow keys={['↑', '←']} label={t('previousApproval')} />
              <ShortcutRow keys={['↓', '→']} label={t('nextApproval')} />
              <ShortcutRow keys={['?']} label={tCommon('showShortcuts')} />
              <ShortcutRow keys={['Esc']} label={tCommon('close')} />
            </div>
            <p className="mt-4 text-xs text-nothing-gray-400 font-body">
              {t('holdToApproveHint')}
            </p>
          </div>
        </div>
      )}
    </div>
  )
}

// =============================================================================
// Sub-components
// =============================================================================

function ShortcutRow({
  keys,
  label,
  highlight,
}: {
  keys: string[]
  label: string
  highlight?: boolean
}) {
  return (
    <div className="flex items-center justify-between">
      <div className="flex items-center gap-1">
        {keys.map((key) => (
          <kbd
            key={key}
            className={cn(
              'px-2 py-1 rounded text-xs font-body border',
              highlight
                ? 'bg-status-healthy/10 text-status-healthy border-status-healthy/30'
                : 'bg-nothing-gray-100 text-nothing-gray-700 border-nothing-gray-200'
            )}
          >
            {key}
          </kbd>
        ))}
      </div>
      <span className={cn(
        'text-sm',
        highlight ? 'text-status-healthy font-medium' : 'text-nothing-gray-600'
      )}>
        {label}
      </span>
    </div>
  )
}
