/**
 * BoostMedia AI Content Generator Admin - RecentActivity Component
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { RefreshCw, Sparkles, FileCheck, AlertCircle, Search } from 'lucide-react'
import { Card, CardHeader, CardTitle, CardContent, Badge, EmptyState } from '../common'
import { useLogs } from '../../hooks'
import { t, tf } from '../../lib/i18n'
import type { LogActionType, LogStatus } from '../../types'
import type { ReactNode } from 'react'

const actionIcons: Record<LogActionType, ReactNode> = {
  scan: <Search className="w-4 h-4" />,
  analyze: <RefreshCw className="w-4 h-4" />,
  generate: <Sparkles className="w-4 h-4" />,
  publish: <FileCheck className="w-4 h-4" />,
}

const actionKeys: Record<LogActionType, string> = {
  scan: 'Scanning',
  analyze: 'Analysis',
  generate: 'Content Creation',
  publish: 'Publishing',
}

const statusVariants: Record<LogStatus, 'success' | 'error' | 'warning'> = {
  success: 'success',
  error: 'error',
  warning: 'warning',
}

const statusKeys: Record<LogStatus, string> = {
  success: 'Succeeded',
  error: 'Failed',
  warning: 'Warning',
}

function formatTimeAgo(dateString: string): string {
  const date = new Date(dateString)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)

  if (diffMins < 1) return t('just now')
  if (diffMins < 60) return tf('%d minutes ago', diffMins)
  if (diffHours < 24) return tf('%d hours ago', diffHours)
  return tf('%d days ago', diffDays)
}

export function RecentActivity() {
  const { logs, loading, error } = useLogs({ limit: 5 })

  if (loading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>{t('Recent Activity')}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="animate-pulse space-y-4">
            {[1, 2, 3].map((i) => (
              <div key={i} className="flex gap-4">
                <div className="w-10 h-10 bg-bc-gray-200 rounded-full" />
                <div className="flex-1 space-y-2">
                  <div className="h-4 bg-bc-gray-200 rounded w-1/3" />
                  <div className="h-3 bg-bc-gray-100 rounded w-1/2" />
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t('Recent Activity')}</CardTitle>
      </CardHeader>
      <CardContent>
        {error ? (
          <div className="text-sm text-red-500 p-4">
            {t('Failed to load recent activity')}
          </div>
        ) : logs.length === 0 ? (
          <EmptyState
            variant="inbox"
            title={t('No activity yet')}
            description={t('Actions you perform will appear here')}
          />
        ) : (
          <div className="space-y-4">
            {logs.map((log) => (
              <div
                key={log.id}
                className="flex items-start gap-4 p-3 rounded-bc hover:bg-bc-gray-50 transition-colors"
              >
                {/* Icon */}
                <div
                  className={`
                    p-2 rounded-full shrink-0
                    ${
                      log.status === 'success'
                        ? 'bg-green-100 text-green-600'
                        : log.status === 'error'
                        ? 'bg-red-100 text-red-600'
                        : 'bg-yellow-100 text-yellow-600'
                    }
                  `}
                >
                  {log.status === 'error' ? (
                    <AlertCircle className="w-4 h-4" />
                  ) : (
                    actionIcons[log.action_type] || actionIcons.scan
                  )}
                </div>

                {/* Content */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="font-medium text-bc-gray-800">
                      {t(actionKeys[log.action_type] || 'Activity')}
                    </span>
                    {log.post_type && (
                      <Badge variant="default">{log.post_type}</Badge>
                    )}
                    <Badge variant={statusVariants[log.status] || 'warning'}>
                      {t(statusKeys[log.status] || 'Activity')}
                    </Badge>
                  </div>

                  {/* Details */}
                  <div className="flex items-center gap-3 mt-1 text-sm text-bc-gray-500">
                    <span>{formatTimeAgo(log.created_at)}</span>
                    {log.duration_ms > 0 && (
                      <span>•</span>
                    )}
                    {log.duration_ms > 0 && (
                      <span>{(log.duration_ms / 1000).toFixed(1)} {t('seconds')}</span>
                    )}
                    {log.tokens_used > 0 && (
                      <>
                        <span>•</span>
                        <span>{log.tokens_used.toLocaleString()} tokens</span>
                      </>
                    )}
                  </div>

                  {/* Error Message */}
                  {log.error_message && (
                    <p className="mt-1 text-sm text-red-600 truncate">
                      {log.error_message}
                    </p>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  )
}
