import { useState, useCallback, useMemo } from 'react'
import {
  Trash2,
  ScanLine,
  BarChart3,
  Sparkles,
  Send,
  Clock,
  CheckCircle,
  AlertTriangle,
  XCircle,
  Filter,
} from 'lucide-react'
import { Header } from '../components/layout/Header'
import { Card, CardContent, Badge, Button, EmptyState, PageLoader } from '../components/common'
import { useLogs } from '../hooks'
import { endpoints, getErrorMessage } from '../api/client'
import { formatTimeAgo, formatNumber } from '../utils'
import { t } from '../lib/i18n'
import type { LogActionType, LogStatus } from '../types'

function getActionConfig(): Record<LogActionType, { label: string; icon: typeof ScanLine; color: string }> {
  return {
    scan: { label: t('Scanning'), icon: ScanLine, color: 'text-blue-600 bg-blue-50' },
    analyze: { label: t('Analysis'), icon: BarChart3, color: 'text-purple-600 bg-purple-50' },
    generate: { label: t('Generation'), icon: Sparkles, color: 'text-bc-primary bg-bc-primary-light' },
    publish: { label: t('Publishing'), icon: Send, color: 'text-green-600 bg-green-50' },
  }
}

function getStatusBadge(): Record<LogStatus, { label: string; variant: 'success' | 'warning' | 'error' }> {
  return {
    success: { label: t('Succeeded'), variant: 'success' },
    warning: { label: t('Warning'), variant: 'warning' },
    error: { label: t('Error'), variant: 'error' },
  }
}

type FilterAction = 'all' | LogActionType

export default function LogsPage() {
  const [filterAction, setFilterAction] = useState<FilterAction>('all')
  const [isClearing, setIsClearing] = useState(false)
  const [clearError, setClearError] = useState<string | null>(null)
  const [isRefreshing, setIsRefreshing] = useState(false)

  const { logs, loading, refetch } = useLogs({ limit: 100 })

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true)
    await refetch()
    setIsRefreshing(false)
  }, [refetch])

  const handleClearLogs = async () => {
    if (!confirm(t('Delete all logs?'))) return
    setIsClearing(true)
    setClearError(null)
    try {
      await endpoints.deleteLogs()
      await refetch()
    } catch (err) {
      setClearError(getErrorMessage(err, t('Failed to clear logs')))
    } finally {
      setIsClearing(false)
    }
  }

  const filteredLogs = useMemo(() =>
    filterAction === 'all' ? logs : logs.filter(l => l.action_type === filterAction),
    [logs, filterAction]
  )

  const actionCounts = useMemo(() => ({
    all: logs.length,
    scan: logs.filter(l => l.action_type === 'scan').length,
    analyze: logs.filter(l => l.action_type === 'analyze').length,
    generate: logs.filter(l => l.action_type === 'generate').length,
    publish: logs.filter(l => l.action_type === 'publish').length,
  }), [logs])

  const totalTokens = useMemo(
    () => logs.reduce((sum, l) => sum + (l.tokens_used || 0), 0),
    [logs]
  )

  if (loading) return <PageLoader />

  const actionConfig = getActionConfig()
  const statusBadge = getStatusBadge()

  return (
    <div className="min-h-screen">
      <Header
        title={t('Logs')}
        subtitle={t('System activity tracking')}
        onRefresh={handleRefresh}
        isRefreshing={isRefreshing}
        helpContent={[
          t('Logs track all plugin activity: scans, analyses, content generation, and publishing events.'),
          t('Use the filter buttons to show specific log types (Critical, Errors, Warnings, Info).'),
          t('Click "Clear Logs" to delete all log entries. Logs are automatically cleaned up based on the retention setting.'),
          t('If a generation fails, check the logs for error details and the specific error message from the AI service.'),
        ]}
      />

      <div className="p-6">
        {/* Summary stats */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
          <div className="bg-white rounded-bc border border-bc-gray-200 p-4 text-center">
            <div className="text-2xl font-bold text-bc-gray-800">{logs.length}</div>
            <div className="text-xs text-bc-gray-500 mt-1">{t('Total records')}</div>
          </div>
          <div className="bg-white rounded-bc border border-bc-gray-200 p-4 text-center">
            <div className="text-2xl font-bold text-green-600">
              {logs.filter(l => l.status === 'success').length}
            </div>
            <div className="text-xs text-bc-gray-500 mt-1">{t('Succeeded count')}</div>
          </div>
          <div className="bg-white rounded-bc border border-bc-gray-200 p-4 text-center">
            <div className="text-2xl font-bold text-red-600">
              {logs.filter(l => l.status === 'error').length}
            </div>
            <div className="text-xs text-bc-gray-500 mt-1">{t('Errors count')}</div>
          </div>
          <div className="bg-white rounded-bc border border-bc-gray-200 p-4 text-center">
            <div className="text-2xl font-bold text-bc-primary">{formatNumber(totalTokens)}</div>
            <div className="text-xs text-bc-gray-500 mt-1">{t('Tokens used')}</div>
          </div>
        </div>

        {/* Filter tabs */}
        <div className="flex items-center gap-2 mb-4 flex-wrap">
          <Filter className="w-4 h-4 text-bc-gray-400" />
          {([
            { key: 'all' as FilterAction, label: t('All (filter)') },
            { key: 'scan' as FilterAction, label: t('Scans') },
            { key: 'analyze' as FilterAction, label: t('Analyses') },
            { key: 'generate' as FilterAction, label: t('Generations') },
            { key: 'publish' as FilterAction, label: t('Publications') },
          ]).map(tab => (
            <button
              key={tab.key}
              onClick={() => setFilterAction(tab.key)}
              className={`px-3 py-1.5 rounded-full text-sm transition-colors ${
                filterAction === tab.key
                  ? 'bg-bc-primary text-white'
                  : 'bg-bc-gray-100 text-bc-gray-600 hover:bg-bc-gray-200'
              }`}
            >
              {tab.label}
              {actionCounts[tab.key] > 0 && (
                <span className={`ms-1.5 text-xs ${
                  filterAction === tab.key ? 'opacity-80' : 'text-bc-gray-400'
                }`}>
                  ({actionCounts[tab.key]})
                </span>
              )}
            </button>
          ))}

          <div className="flex-1" />

          {logs.length > 0 && (
            <Button
              variant="ghost"
              onClick={handleClearLogs}
              loading={isClearing}
              className="text-red-500 hover:text-red-600 hover:bg-red-50"
            >
              <Trash2 className="w-4 h-4" />
              {t('Delete logs')}
            </Button>
          )}
        </div>

        {clearError && (
          <div className="text-sm text-red-500 mb-2 flex items-center gap-2">
            <span>{clearError}</span>
            <button onClick={() => setClearError(null)} className="hover:text-red-700">✕</button>
          </div>
        )}

        {/* Logs list */}
        {filteredLogs.length === 0 ? (
          <Card>
            <CardContent>
              <EmptyState
                variant="inbox"
                title={logs.length === 0 ? t('No logs yet') : t('No logs in current filter')}
                description={logs.length === 0
                  ? t('Logs will appear here after scanning, analyzing or creating content')
                  : t('Try changing the filter')
                }
              />
            </CardContent>
          </Card>
        ) : (
          <Card padding="none">
            <CardContent>
              <div className="divide-y divide-bc-gray-100">
                {filteredLogs.map(log => {
                  const action = actionConfig[log.action_type] || actionConfig.scan
                  const status = statusBadge[log.status] || statusBadge.success
                  const ActionIcon = action.icon
                  const StatusIcon = log.status === 'success' ? CheckCircle
                    : log.status === 'warning' ? AlertTriangle
                    : XCircle

                  return (
                    <div key={log.id} className="px-5 py-4 hover:bg-bc-gray-50 transition-colors">
                      <div className="flex items-start gap-3">
                        <div className={`w-9 h-9 rounded-bc flex items-center justify-center shrink-0 ${action.color}`}>
                          <ActionIcon className="w-4.5 h-4.5" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-0.5">
                            <span className="font-medium text-sm text-bc-gray-800">{action.label}</span>
                            {log.post_type && (
                              <Badge variant="default">{log.post_type}</Badge>
                            )}
                            <Badge variant={status.variant} dot>
                              <StatusIcon className="w-3 h-3 inline -mt-0.5" />
                              <span className="ms-1">{status.label}</span>
                            </Badge>
                          </div>
                          <div className="flex items-center gap-3 text-xs text-bc-gray-500">
                            <span className="flex items-center gap-1">
                              <Clock className="w-3 h-3" />
                              {formatTimeAgo(log.created_at)}
                            </span>
                            {log.duration_ms > 0 && (
                              <span>{(log.duration_ms / 1000).toFixed(1)} {t('seconds')}</span>
                            )}
                            {log.tokens_used > 0 && (
                              <span>{formatNumber(log.tokens_used)} {t('tokens')}</span>
                            )}
                          </div>
                          {log.error_message && (
                            <p className="text-xs text-red-600 mt-1">{log.error_message}</p>
                          )}
                          {log.details && Object.keys(log.details).length > 0 && (
                            <div className="flex flex-wrap gap-2 mt-1.5">
                              {Object.entries(log.details).map(([key, value]) => (
                                <span key={key} className="text-xs bg-bc-gray-50 text-bc-gray-600 px-2 py-0.5 rounded-full">
                                  {formatDetailKey(key)}: {String(value)}
                                </span>
                              ))}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  )
}

function formatDetailKey(key: string): string {
  const map: Record<string, string> = {
    found_meta_fields: t('meta fields'),
    found_taxonomies: t('taxonomies'),
    samples_analyzed: t('samples'),
    category: t('category'),
    count: t('count'),
    post_type: t('content type'),
  }
  return map[key] || key.replace(/_/g, ' ')
}
