import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAppPath } from '@core/hooks/useAppPath'
import { apiFetch } from '@core/lib/api'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@core/components/ui/tabs'
import { Badge } from '@core/components/ui/badge'
import { Button } from '@core/components/ui/button'
import { Skeleton } from '@core/components/ui/skeleton'
import { ScrollArea } from '@core/components/ui/scroll-area'
import { ClipboardList, AlertCircle, ThumbsDown, BookOpen } from 'lucide-react'

interface Item {
  id: string
  title: string
  status?: string
  created_at: string
  updated_at?: string
  data?: Record<string, any>
}

function ageLabel(dateStr: string) {
  const diff = Date.now() - new Date(dateStr).getTime()
  const hours = Math.floor(diff / 3600000)
  if (hours < 1) return 'just now'
  if (hours < 24) return `${hours}h ago`
  return `${Math.floor(hours / 24)}d ago`
}

function daysAgo(dateStr: string) {
  const diff = Date.now() - new Date(dateStr).getTime()
  return Math.floor(diff / 86400000)
}

// --- KB Candidates Tab ---
function KBCandidatesTab() {
  const [items, setItems] = useState<Item[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    apiFetch('/api/admin-data?entity=items&type_slug=kb_article&status=draft&limit=50')
      .then(r => r.json())
      .then(j => {
        const all: Item[] = Array.isArray(j?.data) ? j.data : Array.isArray(j) ? j : []
        setItems(all.filter(item => item.data?.kb_type === 'postmortem'))
      })
      .catch(() => setItems([]))
      .finally(() => setLoading(false))
  }, [])

  const handleApprove = async (item: Item) => {
    await apiFetch(`/api/admin-data?entity=items&id=${item.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status: 'published' }),
    })
    setItems(prev => prev.filter(i => i.id !== item.id))
  }

  if (loading) {
    return (
      <div className="p-4 space-y-3">
        {Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}
      </div>
    )
  }

  if (items.length === 0) {
    return (
      <div className="p-12 text-center text-muted-foreground">
        <ClipboardList className="h-10 w-10 mx-auto mb-3 opacity-30" />
        <p className="text-sm">No postmortem KB drafts awaiting review.</p>
      </div>
    )
  }

  return (
    <ScrollArea className="flex-1">
      <div className="divide-y divide-border">
        {items.map(item => (
          <div key={item.id} className="px-5 py-4 flex items-start justify-between gap-4 hover:bg-accent/30 transition-colors">
            <div className="min-w-0 flex-1">
              <p className="text-sm font-medium truncate">{item.title}</p>
              <div className="flex items-center gap-2 mt-1 flex-wrap">
                <span className="text-xs text-muted-foreground">{ageLabel(item.created_at)}</span>
                {item.data?.source_ticket_id && (
                  <Badge variant="outline" className="text-xs">
                    Ticket: {String(item.data.source_ticket_id).slice(0, 8)}…
                  </Badge>
                )}
                {item.data?.automation_potential && (
                  <Badge variant="secondary" className="text-xs capitalize">
                    {item.data.automation_potential} automation
                  </Badge>
                )}
              </div>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              <Button size="sm" variant="outline" className="text-xs" onClick={() => handleApprove(item)}>
                Approve
              </Button>
            </div>
          </div>
        ))}
      </div>
    </ScrollArea>
  )
}

// --- Escalations Tab ---
function EscalationsTab() {
  const navigate = useNavigate()
  const appPath = useAppPath()
  const [items, setItems] = useState<Item[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    apiFetch('/api/admin-data?entity=items&type_slug=support_ticket&status=human_assigned&limit=50')
      .then(r => r.json())
      .then(j => setItems(Array.isArray(j?.data) ? j.data : Array.isArray(j) ? j : []))
      .catch(() => setItems([]))
      .finally(() => setLoading(false))
  }, [])

  if (loading) {
    return (
      <div className="p-4 space-y-3">
        {Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}
      </div>
    )
  }

  if (items.length === 0) {
    return (
      <div className="p-12 text-center text-muted-foreground">
        <AlertCircle className="h-10 w-10 mx-auto mb-3 opacity-30" />
        <p className="text-sm">No escalated tickets right now.</p>
      </div>
    )
  }

  const PRIORITY_COLORS: Record<string, string> = {
    low: 'bg-muted text-muted-foreground',
    medium: 'bg-blue-100 text-blue-700',
    high: 'bg-orange-100 text-orange-700',
    urgent: 'bg-red-100 text-red-700',
  }

  return (
    <ScrollArea className="flex-1">
      <div className="divide-y divide-border">
        {items.map(item => (
          <div key={item.id} className="px-5 py-4 flex items-start justify-between gap-4 hover:bg-accent/30 transition-colors">
            <div className="min-w-0 flex-1">
              <p className="text-sm font-medium truncate">{item.title}</p>
              <div className="flex items-center gap-2 mt-1 flex-wrap">
                <span className="text-xs text-muted-foreground">{ageLabel(item.created_at)}</span>
                {item.data?.priority && (
                  <Badge className={`text-xs ${PRIORITY_COLORS[item.data.priority] || 'bg-muted text-muted-foreground'}`}>
                    {item.data.priority}
                  </Badge>
                )}
                {item.data?.aim_escalation_reason && (
                  <Badge variant="outline" className="text-xs">
                    {item.data.aim_escalation_reason.replace(/_/g, ' ')}
                  </Badge>
                )}
                {item.data?.aim_confidence_at_response != null && (
                  <span className="text-xs text-muted-foreground">
                    AI conf: {Math.round(item.data.aim_confidence_at_response * 100)}%
                  </span>
                )}
              </div>
            </div>
            <div className="shrink-0">
              <Button
                size="sm"
                variant="outline"
                className="text-xs"
                onClick={() => navigate(appPath(`/support/${item.id}`))}
              >
                View
              </Button>
            </div>
          </div>
        ))}
      </div>
    </ScrollArea>
  )
}

// --- Thumbs Down Tab ---
function ThumbsDownTab() {
  const [count, setCount] = useState<number | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    apiFetch('/api/admin-data?entity=items&type_slug=support_ticket&limit=500')
      .then(r => r.json())
      .then(j => {
        const all: Item[] = Array.isArray(j?.data) ? j.data : Array.isArray(j) ? j : []
        setCount(all.filter(t => t.data?.aim_escalation_reason === 'thumbs_down').length)
      })
      .catch(() => setCount(0))
      .finally(() => setLoading(false))
  }, [])

  return (
    <div className="p-6 space-y-4">
      <div className="flex items-center gap-3 p-4 rounded-lg bg-amber-50 border border-amber-200">
        <ThumbsDown className="h-5 w-5 text-amber-600 shrink-0" />
        <p className="text-sm text-amber-800">
          Feedback data is captured on individual tickets. View ticket detail for feedback context.
        </p>
      </div>

      <div className="p-4 rounded-lg border bg-muted/30">
        <p className="text-xs text-muted-foreground mb-1">Tickets with thumbs-down escalation reason</p>
        {loading ? (
          <Skeleton className="h-7 w-16" />
        ) : (
          <p className="text-2xl font-bold">{count ?? 0}</p>
        )}
      </div>
    </div>
  )
}

// --- Stale KB Tab ---
function StaleKBTab() {
  const [items, setItems] = useState<Item[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    apiFetch('/api/admin-data?entity=items&type_slug=kb_article&status=published&limit=100')
      .then(r => r.json())
      .then(j => {
        const all: Item[] = Array.isArray(j?.data) ? j.data : Array.isArray(j) ? j : []
        setItems(all.filter(item => daysAgo(item.updated_at || item.created_at) >= 90))
      })
      .catch(() => setItems([]))
      .finally(() => setLoading(false))
  }, [])

  const handleMarkReviewed = async (item: Item) => {
    await apiFetch(`/api/admin-data?entity=items&id=${item.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ updated_at: new Date().toISOString() }),
    })
    setItems(prev => prev.filter(i => i.id !== item.id))
  }

  const handleArchive = async (item: Item) => {
    await apiFetch(`/api/admin-data?entity=items&id=${item.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status: 'archived' }),
    })
    setItems(prev => prev.filter(i => i.id !== item.id))
  }

  if (loading) {
    return (
      <div className="p-4 space-y-3">
        {Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}
      </div>
    )
  }

  if (items.length === 0) {
    return (
      <div className="p-12 text-center text-muted-foreground">
        <BookOpen className="h-10 w-10 mx-auto mb-3 opacity-30" />
        <p className="text-sm">No published articles are 90+ days stale.</p>
      </div>
    )
  }

  return (
    <ScrollArea className="flex-1">
      <div className="divide-y divide-border">
        {items.map(item => (
          <div key={item.id} className="px-5 py-4 flex items-start justify-between gap-4 hover:bg-accent/30 transition-colors">
            <div className="min-w-0 flex-1">
              <p className="text-sm font-medium truncate">{item.title}</p>
              <p className="text-xs text-muted-foreground mt-1">
                Last updated {daysAgo(item.updated_at || item.created_at)} days ago
              </p>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              <Button size="sm" variant="outline" className="text-xs" onClick={() => handleMarkReviewed(item)}>
                Mark Reviewed
              </Button>
              <Button size="sm" variant="outline" className="text-xs text-destructive border-destructive/40 hover:bg-destructive/10" onClick={() => handleArchive(item)}>
                Archive
              </Button>
            </div>
          </div>
        ))}
      </div>
    </ScrollArea>
  )
}

// --- Main Page ---
export default function ReviewQueuePage() {
  return (
    <div className="flex flex-col h-full">
      <div className="px-6 py-4 border-b border-border shrink-0">
        <h1 className="text-base font-semibold">Review Queue</h1>
        <p className="text-xs text-muted-foreground mt-0.5">Items requiring human review and action</p>
      </div>

      <Tabs defaultValue="kb-candidates" className="flex flex-col flex-1 min-h-0">
        <div className="px-6 pt-3 border-b border-border shrink-0">
          <TabsList className="h-8">
            <TabsTrigger value="kb-candidates" className="text-xs gap-1">
              <ClipboardList className="h-3 w-3" /> KB Candidates
            </TabsTrigger>
            <TabsTrigger value="escalations" className="text-xs gap-1">
              <AlertCircle className="h-3 w-3" /> Escalations
            </TabsTrigger>
            <TabsTrigger value="thumbs-down" className="text-xs gap-1">
              <ThumbsDown className="h-3 w-3" /> Thumbs Down
            </TabsTrigger>
            <TabsTrigger value="stale-kb" className="text-xs gap-1">
              <BookOpen className="h-3 w-3" /> Stale KB
            </TabsTrigger>
          </TabsList>
        </div>

        <TabsContent value="kb-candidates" className="flex-1 min-h-0 mt-0 flex flex-col">
          <KBCandidatesTab />
        </TabsContent>
        <TabsContent value="escalations" className="flex-1 min-h-0 mt-0 flex flex-col">
          <EscalationsTab />
        </TabsContent>
        <TabsContent value="thumbs-down" className="flex-1 min-h-0 mt-0 flex flex-col">
          <ThumbsDownTab />
        </TabsContent>
        <TabsContent value="stale-kb" className="flex-1 min-h-0 mt-0 flex flex-col">
          <StaleKBTab />
        </TabsContent>
      </Tabs>
    </div>
  )
}
