import { useEffect, useState } from 'react'
import { apiFetch } from '@core/lib/api'
import { Card, CardContent, CardHeader, CardTitle } from '@core/components/ui/card'
import { Skeleton } from '@core/components/ui/skeleton'
import { Bot, CheckCircle, AlertTriangle, ThumbsDown, BookOpen, RefreshCw } from 'lucide-react'

interface AIMetrics {
  ai_attempted?: number
  ai_resolved?: number
  human_escalations?: number
  thumbs_down_rate?: number
  kb_articles_created?: number
  kb_reuse_count?: number
}

interface FeedbackItem {
  id: string
  created_at: string
  data?: {
    kb_candidate?: boolean
    customer_feedback?: string
    thread_id?: string
  }
}

const METRIC_CARDS = [
  {
    key: 'ai_attempted' as keyof AIMetrics,
    label: 'AI Attempted',
    icon: Bot,
    color: 'text-purple-600',
    bg: 'bg-purple-50',
    format: (v: number) => v.toLocaleString(),
  },
  {
    key: 'ai_resolved' as keyof AIMetrics,
    label: 'AI Resolved',
    icon: CheckCircle,
    color: 'text-green-600',
    bg: 'bg-green-50',
    format: (v: number) => v.toLocaleString(),
  },
  {
    key: 'human_escalations' as keyof AIMetrics,
    label: 'Human Escalations',
    icon: AlertTriangle,
    color: 'text-amber-600',
    bg: 'bg-amber-50',
    format: (v: number) => v.toLocaleString(),
  },
  {
    key: 'thumbs_down_rate' as keyof AIMetrics,
    label: 'Not-Helpful Rate',
    icon: ThumbsDown,
    color: 'text-red-600',
    bg: 'bg-red-50',
    format: (v: number) => `${(v * 100).toFixed(1)}%`,
  },
  {
    key: 'kb_articles_created' as keyof AIMetrics,
    label: 'KB Articles Created',
    icon: BookOpen,
    color: 'text-blue-600',
    bg: 'bg-blue-50',
    format: (v: number) => v.toLocaleString(),
  },
  {
    key: 'kb_reuse_count' as keyof AIMetrics,
    label: 'KB Reuse Count',
    icon: RefreshCw,
    color: 'text-indigo-600',
    bg: 'bg-indigo-50',
    format: (v: number) => v.toLocaleString(),
  },
]

export default function AIDashboardPage() {
  const [metrics, setMetrics] = useState<AIMetrics | null>(null)
  const [metricsLoading, setMetricsLoading] = useState(true)
  const [gaps, setGaps] = useState<FeedbackItem[]>([])
  const [gapsLoading, setGapsLoading] = useState(true)

  useEffect(() => {
    apiFetch('/api/observability?action=ai_support_metrics')
      .then(r => r.json())
      .then(j => setMetrics(j?.metrics ?? j?.data?.metrics ?? j ?? null))
      .catch(() => setMetrics(null))
      .finally(() => setMetricsLoading(false))
  }, [])

  useEffect(() => {
    apiFetch('/api/admin-data?entity=items&type_slug=ai_feedback_record&limit=20')
      .then(r => r.json())
      .then(j => {
        const all: FeedbackItem[] = Array.isArray(j?.data) ? j.data : Array.isArray(j) ? j : []
        setGaps(all.filter(item => item.data?.kb_candidate === false && item.data?.customer_feedback === 'not_helpful'))
      })
      .catch(() => setGaps([]))
      .finally(() => setGapsLoading(false))
  }, [])

  return (
    <div className="flex flex-col h-full overflow-auto">
      <div className="px-6 py-4 border-b border-border shrink-0">
        <h1 className="text-base font-semibold">AI Dashboard</h1>
        <p className="text-xs text-muted-foreground mt-0.5">AI support performance metrics</p>
      </div>

      <div className="flex-1 p-6 space-y-8">
        {/* Metric Cards — 2×3 grid */}
        <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
          {METRIC_CARDS.map(card => {
            const Icon = card.icon
            const rawValue = metrics?.[card.key]
            const value = rawValue != null ? card.format(rawValue as number) : null

            return (
              <Card key={card.key}>
                <CardHeader className="pb-2">
                  <div className="flex items-center gap-2">
                    <div className={`p-1.5 rounded-md ${card.bg}`}>
                      <Icon className={`h-4 w-4 ${card.color}`} />
                    </div>
                    <CardTitle className="text-xs font-medium text-muted-foreground">{card.label}</CardTitle>
                  </div>
                </CardHeader>
                <CardContent>
                  {metricsLoading ? (
                    <Skeleton className="h-8 w-20" />
                  ) : (
                    <p className="text-2xl font-bold">{value ?? '—'}</p>
                  )}
                </CardContent>
              </Card>
            )
          })}
        </div>

        {/* Knowledge Gaps */}
        <div>
          <h2 className="text-sm font-semibold mb-3">Knowledge Gaps</h2>
          <p className="text-xs text-muted-foreground mb-3">
            AI feedback records where no KB article was created and the customer marked the response as not helpful.
          </p>

          {gapsLoading ? (
            <div className="space-y-2">
              {Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-10 w-full" />)}
            </div>
          ) : gaps.length === 0 ? (
            <div className="rounded-lg border border-border p-6 text-center text-muted-foreground">
              <CheckCircle className="h-8 w-8 mx-auto mb-2 opacity-30" />
              <p className="text-sm">No knowledge gaps detected.</p>
            </div>
          ) : (
            <div className="rounded-lg border border-border divide-y divide-border">
              {gaps.map(item => (
                <div key={item.id} className="px-4 py-3 flex items-center justify-between">
                  <div>
                    <p className="text-xs font-mono text-muted-foreground">
                      {item.data?.thread_id ? `Thread: ${String(item.data.thread_id).slice(0, 8)}…` : `Record: ${item.id.slice(0, 8)}…`}
                    </p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      {new Date(item.created_at).toLocaleDateString()}
                    </p>
                  </div>
                  <span className="text-xs bg-red-100 text-red-700 px-2 py-0.5 rounded">not helpful</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
