'use client'

import { useState, useMemo } from 'react'
import { analyzeDesign } from '@actuate-media/cms-core/page-builder'
import type {
  PageNode,
  DesignAnalysis,
  DesignCategory,
  BuilderDesignCheck,
  DesignSuggestion,
} from '@actuate-media/cms-core'
import {
  CheckCircle2,
  AlertCircle,
  XCircle,
  ChevronDown,
  ChevronUp,
  Lightbulb,
  Palette,
} from 'lucide-react'

export interface DesignScorePanelProps {
  tree: PageNode
}

function getScoreColor(score: number, max: number): string {
  const ratio = max > 0 ? score / max : 0
  if (ratio >= 0.8) return 'text-green-500'
  if (ratio >= 0.5) return 'text-amber-500'
  return 'text-red-500'
}

function getBarColor(score: number, max: number): string {
  const ratio = max > 0 ? score / max : 0
  if (ratio >= 0.8) return 'bg-green-500'
  if (ratio >= 0.5) return 'bg-amber-500'
  return 'bg-red-500'
}

function getScoreLabel(score: number): string {
  if (score >= 80) return 'Excellent'
  if (score >= 65) return 'Good'
  if (score >= 50) return 'Needs Work'
  return 'Poor'
}

function getRingStrokeColor(score: number): string {
  if (score >= 80) return 'rgb(34, 197, 94)'
  if (score >= 50) return 'rgb(245, 158, 11)'
  return 'rgb(239, 68, 68)'
}

function StatusIcon({ status }: { status: BuilderDesignCheck['status'] }) {
  switch (status) {
    case 'good':
      return <CheckCircle2 size={14} className="shrink-0 text-green-500" />
    case 'warning':
      return <AlertCircle size={14} className="shrink-0 text-amber-500" />
    case 'error':
      return <XCircle size={14} className="shrink-0 text-red-500" />
  }
}

function SeverityBadge({ severity }: { severity: DesignSuggestion['severity'] }) {
  const classes: Record<DesignSuggestion['severity'], string> = {
    important: 'bg-red-100 text-red-700',
    suggestion: 'bg-amber-100 text-amber-700',
    info: 'bg-blue-100 text-blue-700',
  }

  return (
    <span className={`inline-block rounded px-1.5 py-0.5 text-xs font-medium ${classes[severity]}`}>
      {severity}
    </span>
  )
}

function ScoreRing({ score }: { score: number }) {
  const radius = 32
  const strokeWidth = 6
  const circumference = 2 * Math.PI * radius
  const progress = Math.min(score, 100) / 100
  const dashOffset = circumference * (1 - progress)
  const size = (radius + strokeWidth) * 2

  return (
    <div className="flex flex-col items-center gap-2">
      <div className="relative">
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="-rotate-90">
          <circle
            cx={size / 2}
            cy={size / 2}
            r={radius}
            fill="none"
            stroke="var(--border)"
            strokeWidth={strokeWidth}
          />
          <circle
            cx={size / 2}
            cy={size / 2}
            r={radius}
            fill="none"
            stroke={getRingStrokeColor(score)}
            strokeWidth={strokeWidth}
            strokeDasharray={circumference}
            strokeDashoffset={dashOffset}
            strokeLinecap="round"
            className="transition-all duration-700 ease-out"
          />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center">
          <span className={`text-lg font-medium ${getScoreColor(score, 100)}`}>{score}</span>
        </div>
      </div>
      <span className="text-muted-foreground text-xs">{getScoreLabel(score)}</span>
    </div>
  )
}

function CategoryRow({
  category,
  expanded,
  onToggle,
}: {
  category: DesignCategory
  expanded: boolean
  onToggle: () => void
}) {
  const percentage = category.maxScore > 0 ? (category.score / category.maxScore) * 100 : 0

  return (
    <div className="border-border border-b last:border-b-0">
      <button
        type="button"
        className="hover:bg-muted/50 flex w-full flex-col gap-2 px-4 py-3 text-left transition-colors"
        onClick={onToggle}
        aria-expanded={expanded}
      >
        <div className="flex items-center justify-between">
          <span className="text-foreground text-xs font-medium">{category.label}</span>
          <div className="flex items-center gap-2">
            <span className="text-muted-foreground text-xs">
              {category.score}/{category.maxScore}
            </span>
            {expanded ? (
              <ChevronUp size={14} className="text-muted-foreground" />
            ) : (
              <ChevronDown size={14} className="text-muted-foreground" />
            )}
          </div>
        </div>
        <div className="bg-muted h-1.5 w-full overflow-hidden rounded-full">
          <div
            className={`h-full rounded-full transition-all duration-500 ease-out ${getBarColor(category.score, category.maxScore)}`}
            style={{ width: `${percentage}%` }}
          />
        </div>
      </button>

      {expanded && category.checks.length > 0 && (
        <div className="flex flex-col gap-2 px-4 pb-3">
          {category.checks.map((check) => (
            <div key={check.id} className="flex items-start gap-2 pl-1">
              <StatusIcon status={check.status} />
              <div className="flex flex-col">
                <span className="text-foreground text-xs font-medium">{check.label}</span>
                <span className="text-muted-foreground text-xs">{check.detail}</span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

function SuggestionsList({ suggestions }: { suggestions: DesignSuggestion[] }) {
  const sorted = useMemo(() => {
    const order: Record<DesignSuggestion['severity'], number> = {
      important: 0,
      suggestion: 1,
      info: 2,
    }
    return [...suggestions].sort((a, b) => order[a.severity] - order[b.severity])
  }, [suggestions])

  if (sorted.length === 0) return null

  return (
    <div className="border-border border-t px-4 py-3">
      <div className="mb-3 flex items-center gap-2">
        <Lightbulb size={14} className="text-muted-foreground" />
        <span className="text-foreground text-xs font-medium">Suggestions</span>
      </div>
      <div className="flex flex-col gap-2.5">
        {sorted.map((suggestion) => (
          <div key={suggestion.id} className="flex items-start gap-2">
            <SeverityBadge severity={suggestion.severity} />
            <span className="text-muted-foreground text-xs leading-relaxed">
              {suggestion.message}
            </span>
          </div>
        ))}
      </div>
    </div>
  )
}

export function DesignScorePanel({ tree }: DesignScorePanelProps) {
  const analysis = useMemo(() => analyzeDesign(tree), [tree])
  const [expandedCategories, setExpandedCategories] = useState<string[]>([])

  const toggleCategory = (name: string) => {
    setExpandedCategories((prev) =>
      prev.includes(name) ? prev.filter((n) => n !== name) : [...prev, name],
    )
  }

  if (!tree.children || tree.children.length === 0) {
    return (
      <div className="flex min-h-[200px] flex-col items-center justify-center p-6 text-center">
        <Palette size={32} className="text-muted-foreground mb-3" />
        <p className="text-foreground mb-1 text-sm font-medium">Design Score</p>
        <p className="text-muted-foreground text-xs">
          Add sections to your page to see the design analysis
        </p>
      </div>
    )
  }

  return (
    <div className="flex flex-col">
      <div className="border-border flex flex-col items-center border-b py-5">
        <ScoreRing score={analysis.score} />
      </div>

      <div className="flex flex-col">
        {analysis.categories.map((category) => (
          <CategoryRow
            key={category.name}
            category={category}
            expanded={expandedCategories.includes(category.name)}
            onToggle={() => toggleCategory(category.name)}
          />
        ))}
      </div>

      <SuggestionsList suggestions={analysis.suggestions} />
    </div>
  )
}
