'use client'

import { useState, useMemo } from 'react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { Loader2, ChevronDown, CheckCircle2, X } from 'lucide-react'

export type RecommendationItem = {
  projectId: string
  rank: number
  score: number
  category: string
  strengths: string[]
  concerns: string[]
  recommendation: string
}

export type AIRecommendationsDisplayProps = {
  recommendations: { STARTUP: RecommendationItem[]; BUSINESS_CONCEPT: RecommendationItem[] }
  projectStates: any[] | undefined
  roundId: string
  onClear: () => void
  onApplied: () => void
}

export function AIRecommendationsDisplay({
  recommendations,
  projectStates,
  roundId,
  onClear,
  onApplied,
}: AIRecommendationsDisplayProps) {
  const [expandedId, setExpandedId] = useState<string | null>(null)
  const [applying, setApplying] = useState(false)

  // Initialize selected with all recommended project IDs
  const allRecommendedIds = useMemo(() => {
    const ids = new Set<string>()
    for (const item of recommendations.STARTUP) ids.add(item.projectId)
    for (const item of recommendations.BUSINESS_CONCEPT) ids.add(item.projectId)
    return ids
  }, [recommendations])

  const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set(allRecommendedIds))

  // Build projectId → title map from projectStates
  const projectTitleMap = useMemo(() => {
    const map = new Map<string, string>()
    if (projectStates) {
      for (const ps of projectStates) {
        if (ps.project?.id && ps.project?.title) {
          map.set(ps.project.id, ps.project.title)
        }
      }
    }
    return map
  }, [projectStates])

  const transitionMutation = trpc.roundEngine.transitionProject.useMutation()

  const toggleProject = (projectId: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev)
      if (next.has(projectId)) next.delete(projectId)
      else next.add(projectId)
      return next
    })
  }

  const selectedStartups = recommendations.STARTUP.filter((item) => selectedIds.has(item.projectId)).length
  const selectedConcepts = recommendations.BUSINESS_CONCEPT.filter((item) => selectedIds.has(item.projectId)).length

  const handleApply = async () => {
    setApplying(true)
    try {
      // Transition all selected projects to PASSED
      const promises = Array.from(selectedIds).map((projectId) =>
        transitionMutation.mutateAsync({ projectId, roundId, newState: 'PASSED' }).catch(() => {
          // Project might already be PASSED — that's OK
        })
      )
      await Promise.all(promises)
      toast.success(`Marked ${selectedIds.size} project(s) as passed`)
      onApplied()
    } catch (error) {
      toast.error('Failed to apply recommendations')
    } finally {
      setApplying(false)
    }
  }

  const renderCategory = (label: string, items: RecommendationItem[], colorClass: string) => {
    if (items.length === 0) return (
      <div className="text-center py-4 text-muted-foreground text-sm">
        No {label.toLowerCase()} projects evaluated
      </div>
    )

    return (
      <div className="space-y-2">
        {items.map((item) => {
          const isExpanded = expandedId === `${item.category}-${item.projectId}`
          const isSelected = selectedIds.has(item.projectId)
          const projectTitle = projectTitleMap.get(item.projectId) || item.projectId

          return (
            <div
              key={item.projectId}
              className={cn(
                'border rounded-lg overflow-hidden transition-colors',
                !isSelected && 'opacity-50',
              )}
            >
              <div className="flex items-center gap-2 p-3">
                <Checkbox
                  checked={isSelected}
                  onCheckedChange={() => toggleProject(item.projectId)}
                  className="shrink-0"
                />
                <button
                  onClick={() => setExpandedId(isExpanded ? null : `${item.category}-${item.projectId}`)}
                  className="flex-1 flex items-center gap-3 text-left hover:bg-muted/30 rounded transition-colors min-w-0"
                >
                  <span className={cn(
                    'h-7 w-7 rounded-full flex items-center justify-center text-xs font-bold text-white shrink-0 shadow-sm',
                    colorClass === 'bg-blue-500' ? 'bg-gradient-to-br from-blue-400 to-blue-600' : 'bg-gradient-to-br from-purple-400 to-purple-600',
                  )}>
                    {item.rank}
                  </span>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium truncate">{projectTitle}</p>
                    <p className="text-xs text-muted-foreground truncate">{item.recommendation}</p>
                  </div>
                  <Badge variant="outline" className="shrink-0 text-xs font-mono">
                    {item.score}/100
                  </Badge>
                  <ChevronDown className={cn(
                    'h-4 w-4 text-muted-foreground transition-transform shrink-0',
                    isExpanded && 'rotate-180',
                  )} />
                </button>
              </div>
              {isExpanded && (
                <div className="px-3 pb-3 pt-0 space-y-2 border-t bg-muted/10">
                  <div className="pt-2">
                    <p className="text-xs font-medium text-emerald-700 mb-1">Strengths</p>
                    <ul className="text-xs text-muted-foreground space-y-0.5 pl-4 list-disc">
                      {item.strengths.map((s, i) => <li key={i}>{s}</li>)}
                    </ul>
                  </div>
                  {item.concerns.length > 0 && (
                    <div>
                      <p className="text-xs font-medium text-amber-700 mb-1">Concerns</p>
                      <ul className="text-xs text-muted-foreground space-y-0.5 pl-4 list-disc">
                        {item.concerns.map((c, i) => <li key={i}>{c}</li>)}
                      </ul>
                    </div>
                  )}
                  <div>
                    <p className="text-xs font-medium text-blue-700 mb-1">Recommendation</p>
                    <p className="text-xs text-muted-foreground">{item.recommendation}</p>
                  </div>
                </div>
              )}
            </div>
          )
        })}
      </div>
    )
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="text-base">AI Shortlist Recommendations</CardTitle>
            <CardDescription>
              Ranked independently per category — {selectedStartups} of {recommendations.STARTUP.length} startups, {selectedConcepts} of {recommendations.BUSINESS_CONCEPT.length} concepts selected
            </CardDescription>
          </div>
          <Button variant="ghost" size="sm" onClick={onClear}>
            <X className="h-4 w-4 mr-1" />
            Dismiss
          </Button>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        <div className="grid gap-6 lg:grid-cols-2">
          <div>
            <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
              <div className="h-2 w-2 rounded-full bg-blue-500" />
              Startup ({recommendations.STARTUP.length})
            </h4>
            {renderCategory('Startup', recommendations.STARTUP, 'bg-blue-500')}
          </div>
          <div>
            <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
              <div className="h-2 w-2 rounded-full bg-purple-500" />
              Business Concept ({recommendations.BUSINESS_CONCEPT.length})
            </h4>
            {renderCategory('Business Concept', recommendations.BUSINESS_CONCEPT, 'bg-purple-500')}
          </div>
        </div>

        {/* Apply button */}
        <div className="flex items-center justify-between pt-4 border-t">
          <p className="text-sm text-muted-foreground">
            {selectedIds.size} project{selectedIds.size !== 1 ? 's' : ''} will be marked as <strong>Passed</strong>
          </p>
          <Button
            onClick={handleApply}
            disabled={selectedIds.size === 0 || applying}
            className="bg-[#053d57] hover:bg-[#053d57]/90 text-white"
          >
            {applying ? (
              <><Loader2 className="h-4 w-4 mr-1.5 animate-spin" />Applying...</>
            ) : (
              <><CheckCircle2 className="h-4 w-4 mr-1.5" />Apply &amp; Mark as Passed</>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}
