import { useState, useEffect } from 'react'
import {
  Lightbulb, Loader2, RefreshCw, CheckCircle2, Clock, Sparkles,
} from 'lucide-react'
import { flowProposalsApi } from '@/api'
import { toast } from '@/lib/toast'
import type { FlowProposalSummary, FlowProposalDetail, FlowProposalStats } from '@/types/flow-proposal'
import { ProposalCard } from '@/components/flowpilot/ProposalCard'
import { ProposalDetail } from '@/components/flowpilot/ProposalDetail'

const STATUS_TABS = [
  { key: 'pending', label: 'Pending' },
  { key: 'approved', label: 'Approved' },
  { key: 'rejected', label: 'Rejected' },
  { key: 'dismissed', label: 'Dismissed' },
  { key: '', label: 'All' },
] as const

export default function ReviewQueuePage() {
  const [proposals, setProposals] = useState<FlowProposalSummary[]>([])
  const [stats, setStats] = useState<FlowProposalStats | null>(null)
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [detail, setDetail] = useState<FlowProposalDetail | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isLoadingDetail, setIsLoadingDetail] = useState(false)
  const [activeTab, setActiveTab] = useState('pending')
  const [sortBy, setSortBy] = useState('newest')

  const loadProposals = async () => {
    setIsLoading(true)
    try {
      const [data, statsData] = await Promise.all([
        flowProposalsApi.list({
          status: activeTab || undefined,
          sort_by: sortBy,
          limit: 50,
        }),
        flowProposalsApi.getStats(),
      ])
      setProposals(data)
      setStats(statsData)
    } catch {
      toast.error('Failed to load proposals')
    } finally {
      setIsLoading(false)
    }
  }

  useEffect(() => {
    loadProposals()
  }, [activeTab, sortBy]) // eslint-disable-line react-hooks/exhaustive-deps

  const loadDetail = async (id: string) => {
    setSelectedId(id)
    setIsLoadingDetail(true)
    try {
      const data = await flowProposalsApi.get(id)
      setDetail(data)
    } catch {
      toast.error('Failed to load proposal')
    } finally {
      setIsLoadingDetail(false)
    }
  }

  const handleReview = async (action: 'approve' | 'reject' | 'modify' | 'dismiss', notes?: string) => {
    if (!selectedId) return
    try {
      await flowProposalsApi.review(selectedId, {
        action,
        reviewer_notes: notes || null,
      })
      toast.success(
        action === 'approve' ? 'Flow published!' :
        action === 'dismiss' ? 'Proposal dismissed' :
        action === 'reject' ? 'Proposal rejected' :
        'Flow published with modifications'
      )
      setSelectedId(null)
      setDetail(null)
      loadProposals()
    } catch {
      toast.error('Review action failed')
    }
  }

  return (
    <div className="flex h-full flex-col lg:flex-row overflow-hidden">
      {/* Left panel — Proposal list */}
      <div className="w-full shrink-0 border-b lg:border-b-0 lg:border-r lg:w-[380px] overflow-y-auto" style={{ borderColor: 'var(--color-border-default)' }}>
        {/* Header */}
        <div className="sticky top-0 z-10 p-3 sm:p-4 space-y-3" style={{ background: 'rgba(16, 17, 20, 0.95)', }}>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Lightbulb size={16} className="text-amber-400" />
              <h1 className="font-heading text-base font-semibold text-foreground">Review Queue</h1>
            </div>
            <button onClick={loadProposals} className="text-muted-foreground hover:text-foreground transition-colors">
              <RefreshCw size={14} />
            </button>
          </div>

          {/* Stats bar */}
          {stats && (
            <div className="flex items-center gap-3 text-xs text-muted-foreground">
              <span className="flex items-center gap-1">
                <Clock size={10} className="text-amber-400" />
                {stats.pending_count} pending
              </span>
              <span className="flex items-center gap-1">
                <CheckCircle2 size={10} className="text-emerald-400" />
                {stats.approved_this_week} approved
              </span>
              <span className="flex items-center gap-1">
                <Sparkles size={10} className="text-primary" />
                {stats.auto_reinforced_this_week} reinforced
              </span>
            </div>
          )}

          {/* Tabs */}
          <div className="flex gap-1 overflow-x-auto">
            {STATUS_TABS.map((tab) => (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className={`shrink-0 rounded-lg px-2.5 py-1 text-xs font-medium transition-colors ${
                  activeTab === tab.key
                    ? 'bg-accent-dim text-primary'
                    : 'text-muted-foreground hover:text-foreground'
                }`}
              >
                {tab.label}
                {tab.key === 'pending' && stats && stats.pending_count > 0 && (
                  <span className="ml-1 rounded-full bg-amber-500/20 px-1.5 text-[0.5625rem] text-amber-400">
                    {stats.pending_count}
                  </span>
                )}
              </button>
            ))}
          </div>

          {/* Sort */}
          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value)}
            className="w-full rounded-lg border border-border bg-card px-3 py-1.5 text-xs text-foreground"
          >
            <option value="newest">Newest first</option>
            <option value="confidence">Highest confidence</option>
            <option value="sessions">Most supporting sessions</option>
          </select>
        </div>

        {/* Proposal list */}
        <div className="p-3 space-y-2">
          {isLoading ? (
            <div className="flex justify-center py-12">
              <Loader2 size={20} className="animate-spin text-muted-foreground" />
            </div>
          ) : proposals.length === 0 ? (
            <div className="py-12 text-center">
              <Lightbulb size={24} className="mx-auto mb-2 text-muted-foreground/40" />
              <p className="text-sm text-muted-foreground">No proposals found</p>
            </div>
          ) : (
            proposals.map((proposal) => (
              <ProposalCard
                key={proposal.id}
                proposal={proposal}
                isSelected={selectedId === proposal.id}
                onClick={() => loadDetail(proposal.id)}
              />
            ))
          )}
        </div>
      </div>

      {/* Right panel — Detail */}
      <div className={`flex-1 overflow-y-auto ${!detail && !isLoadingDetail ? 'hidden lg:flex' : ''}`}>
        {isLoadingDetail ? (
          <div className="flex items-center justify-center h-full">
            <Loader2 size={20} className="animate-spin text-muted-foreground" />
          </div>
        ) : detail ? (
          <ProposalDetail
            proposal={detail}
            onReview={handleReview}
          />
        ) : (
          <div className="flex items-center justify-center h-full">
            <div className="text-center">
              <Lightbulb size={32} className="mx-auto mb-3 text-muted-foreground/30" />
              <p className="text-sm text-muted-foreground">Select a proposal to review</p>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
