'use client'

import { useState, useMemo } from 'react'
import { analyzeSEO } from '@actuate-media/cms-core/page-builder'
import type {
  PageNode,
  BuilderSEOAnalysis,
  BuilderSEOCheck,
  BuilderReadabilityResult,
} from '@actuate-media/cms-core'
import type { PageSettings } from '../../hooks/useBuilderState.js'
import {
  CheckCircle2,
  AlertCircle,
  XCircle,
  ChevronDown,
  ChevronUp,
  Search,
  Globe,
  Type,
  FileText,
  Clock,
  BarChart3,
  Target,
  Eye,
} from 'lucide-react'

export interface BuilderSEOPanelProps {
  tree: PageNode
  pageSettings: PageSettings
  onPageSettingsChange: (settings: Partial<PageSettings>) => void
  selectedNodeId: string | null
}

function getScoreColor(score: number): string {
  if (score >= 70) return 'text-green-500'
  if (score >= 40) return 'text-amber-500'
  return 'text-red-500'
}

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

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

function StatusIcon({ status }: { status: BuilderSEOCheck['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 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="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)}`}>{score}</span>
      </div>
    </div>
  )
}

function ScoreSummary({ checks }: { checks: BuilderSEOCheck[] }) {
  const passed = checks.filter((c) => c.status === 'good').length
  const warnings = checks.filter((c) => c.status === 'warning').length
  const errors = checks.filter((c) => c.status === 'error').length

  return (
    <div className="flex flex-col gap-1">
      <div className="flex items-center gap-1.5">
        <CheckCircle2 size={12} className="text-green-500" />
        <span className="text-muted-foreground text-xs">{passed} passed</span>
      </div>
      <div className="flex items-center gap-1.5">
        <AlertCircle size={12} className="text-amber-500" />
        <span className="text-muted-foreground text-xs">{warnings} warnings</span>
      </div>
      <div className="flex items-center gap-1.5">
        <XCircle size={12} className="text-red-500" />
        <span className="text-muted-foreground text-xs">{errors} issues</span>
      </div>
    </div>
  )
}

function CollapsibleSection({
  title,
  icon: Icon,
  expanded,
  onToggle,
  children,
}: {
  title: string
  icon: typeof Search
  expanded: boolean
  onToggle: () => void
  children: React.ReactNode
}) {
  return (
    <div className="border-border border-b last:border-b-0">
      <button
        type="button"
        className="hover:bg-muted/50 flex w-full items-center justify-between px-4 py-3 text-left transition-colors"
        onClick={onToggle}
        aria-expanded={expanded}
      >
        <div className="flex items-center gap-2">
          <Icon size={14} className="text-muted-foreground" />
          <span className="text-foreground text-xs font-medium">{title}</span>
        </div>
        {expanded ? (
          <ChevronUp size={14} className="text-muted-foreground" />
        ) : (
          <ChevronDown size={14} className="text-muted-foreground" />
        )}
      </button>
      {expanded && <div className="px-4 pb-4">{children}</div>}
    </div>
  )
}

function SEOChecksList({ checks }: { checks: BuilderSEOCheck[] }) {
  return (
    <div className="flex flex-col gap-2">
      {checks.map((check) => (
        <div key={check.id} className="flex items-start gap-2">
          <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>
  )
}

function ReadabilityGrid({ readability }: { readability: BuilderReadabilityResult }) {
  const fleschLabel =
    readability.fleschScore >= 60
      ? 'Easy'
      : readability.fleschScore >= 30
        ? 'Moderate'
        : 'Difficult'

  return (
    <div className="grid grid-cols-2 gap-3">
      <div className="bg-muted/50 flex flex-col gap-1 rounded-md p-3">
        <div className="flex items-center gap-1.5">
          <BarChart3 size={12} className="text-muted-foreground" />
          <span className="text-muted-foreground text-xs">Flesch Score</span>
        </div>
        <span className={`text-sm font-medium ${getScoreColor(readability.fleschScore)}`}>
          {readability.fleschScore}
        </span>
        <span className="text-muted-foreground text-xs">{fleschLabel}</span>
      </div>

      <div className="bg-muted/50 flex flex-col gap-1 rounded-md p-3">
        <div className="flex items-center gap-1.5">
          <Type size={12} className="text-muted-foreground" />
          <span className="text-muted-foreground text-xs">Word Count</span>
        </div>
        <span className="text-foreground text-sm font-medium">{readability.wordCount}</span>
        <span className="text-muted-foreground text-xs">
          {readability.wordCount >= 300 ? 'Good length' : 'Short'}
        </span>
      </div>

      <div className="bg-muted/50 flex flex-col gap-1 rounded-md p-3">
        <div className="flex items-center gap-1.5">
          <FileText size={12} className="text-muted-foreground" />
          <span className="text-muted-foreground text-xs">Avg Sentence</span>
        </div>
        <span className="text-foreground text-sm font-medium">
          {readability.avgSentenceLength} words
        </span>
        <span className="text-muted-foreground text-xs">
          {readability.avgSentenceLength <= 20 ? 'Good' : 'Long'}
        </span>
      </div>

      <div className="bg-muted/50 flex flex-col gap-1 rounded-md p-3">
        <div className="flex items-center gap-1.5">
          <Clock size={12} className="text-muted-foreground" />
          <span className="text-muted-foreground text-xs">Reading Time</span>
        </div>
        <span className="text-foreground text-sm font-medium">{readability.readingTime} min</span>
        <span className="text-muted-foreground text-xs">~{readability.wordCount} words</span>
      </div>
    </div>
  )
}

function PerBlockHints({ hints }: { hints: BuilderSEOCheck[] }) {
  return (
    <div className="flex flex-col gap-2">
      {hints.map((hint, index) => (
        <div key={`${hint.id}-${index}`} className="flex items-start gap-2">
          <StatusIcon status={hint.status} />
          <div className="flex flex-col">
            <span className="text-foreground text-xs font-medium">{hint.label}</span>
            <span className="text-muted-foreground text-xs">{hint.detail}</span>
          </div>
        </div>
      ))}
    </div>
  )
}

function BasicSEOFields({
  pageSettings,
  onPageSettingsChange,
}: {
  pageSettings: PageSettings
  onPageSettingsChange: (settings: Partial<PageSettings>) => void
}) {
  const metaTitleLength = (pageSettings.metaTitle || '').length
  const metaDescLength = (pageSettings.metaDescription || '').length

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-col gap-1.5">
        <div className="flex items-center justify-between">
          <label className="text-foreground text-xs font-medium">Meta Title</label>
          <span
            className={`text-xs ${metaTitleLength > 60 ? 'text-red-500' : metaTitleLength > 0 ? 'text-muted-foreground' : 'text-muted-foreground'}`}
          >
            {metaTitleLength}/60
          </span>
        </div>
        <input
          type="text"
          value={pageSettings.metaTitle || ''}
          onChange={(e) => onPageSettingsChange({ metaTitle: e.target.value })}
          placeholder="Page title for search engines"
          className="bg-input-background border-border text-foreground placeholder:text-muted-foreground focus:ring-primary w-full rounded-md border px-3 py-2 text-sm focus:ring-1 focus:outline-none"
        />
      </div>

      <div className="flex flex-col gap-1.5">
        <div className="flex items-center justify-between">
          <label className="text-foreground text-xs font-medium">Meta Description</label>
          <span
            className={`text-xs ${metaDescLength > 160 ? 'text-red-500' : metaDescLength > 0 ? 'text-muted-foreground' : 'text-muted-foreground'}`}
          >
            {metaDescLength}/160
          </span>
        </div>
        <textarea
          value={pageSettings.metaDescription || ''}
          onChange={(e) => onPageSettingsChange({ metaDescription: e.target.value })}
          placeholder="Brief description of the page content"
          rows={3}
          className="bg-input-background border-border text-foreground placeholder:text-muted-foreground focus:ring-primary w-full resize-none rounded-md border px-3 py-2 text-sm focus:ring-1 focus:outline-none"
        />
      </div>

      <div className="flex flex-col gap-1.5">
        <label className="text-foreground text-xs font-medium">Focus Keyphrase</label>
        <input
          type="text"
          value={pageSettings.focusKeyphrase || ''}
          onChange={(e) => onPageSettingsChange({ focusKeyphrase: e.target.value })}
          placeholder="Primary keyword or phrase"
          className="bg-input-background border-border text-foreground placeholder:text-muted-foreground focus:ring-primary w-full rounded-md border px-3 py-2 text-sm focus:ring-1 focus:outline-none"
        />
      </div>
    </div>
  )
}

function SearchPreview({ pageSettings }: { pageSettings: PageSettings }) {
  const title = pageSettings.metaTitle || pageSettings.title || 'Untitled Page'
  const description = pageSettings.metaDescription || 'No description set'
  const slug = pageSettings.slug || 'page'

  return (
    <div className="bg-background border-border rounded-md border p-4">
      <p className="text-muted-foreground mb-2 text-xs">Google Search Preview</p>
      <div className="flex flex-col gap-1">
        <p className="text-primary truncate text-sm">{title}</p>
        <p className="truncate text-xs text-green-600">example.com/{slug}</p>
        <p className="text-muted-foreground line-clamp-2 text-xs">{description}</p>
      </div>
    </div>
  )
}

function SocialPreview({ pageSettings }: { pageSettings: PageSettings }) {
  const title = pageSettings.metaTitle || pageSettings.title || 'Untitled Page'
  const description = pageSettings.metaDescription || 'No description set'

  return (
    <div className="bg-background border-border overflow-hidden rounded-md border">
      <p className="text-muted-foreground px-4 pt-3 pb-2 text-xs">Open Graph Preview</p>
      {pageSettings.ogImage && (
        <div className="bg-muted flex h-32 w-full items-center justify-center overflow-hidden">
          <img src={pageSettings.ogImage} alt="OG preview" className="h-full w-full object-cover" />
        </div>
      )}
      {!pageSettings.ogImage && (
        <div className="bg-muted flex h-32 w-full items-center justify-center">
          <Globe size={24} className="text-muted-foreground" />
        </div>
      )}
      <div className="flex flex-col gap-1 p-3">
        <p className="text-muted-foreground text-xs uppercase">example.com</p>
        <p className="text-foreground truncate text-sm font-medium">{title}</p>
        <p className="text-muted-foreground line-clamp-2 text-xs">{description}</p>
      </div>
    </div>
  )
}

export function BuilderSEOPanel({
  tree,
  pageSettings,
  onPageSettingsChange,
  selectedNodeId,
}: BuilderSEOPanelProps) {
  const analysis = useMemo<BuilderSEOAnalysis>(
    () => analyzeSEO(tree, pageSettings as any),
    [tree, pageSettings],
  )

  const [expandedSections, setExpandedSections] = useState<string[]>(['checks'])

  const toggleSection = (section: string) => {
    setExpandedSections((prev) =>
      prev.includes(section) ? prev.filter((s) => s !== section) : [...prev, section],
    )
  }

  const blockHints = useMemo(() => {
    if (!selectedNodeId) return []
    return analysis.perBlockHints.get(selectedNodeId) || []
  }, [analysis.perBlockHints, selectedNodeId])

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

  return (
    <div className="flex flex-col">
      <div className="border-border flex items-center gap-4 border-b px-4 py-5">
        <ScoreRing score={analysis.score} />
        <div className="flex flex-col gap-1">
          <span className="text-foreground text-xs font-medium">
            {getScoreLabel(analysis.score)}
          </span>
          <ScoreSummary checks={analysis.checks} />
        </div>
      </div>

      <div className="flex flex-col">
        <CollapsibleSection
          title="SEO Checks"
          icon={Search}
          expanded={expandedSections.includes('checks')}
          onToggle={() => toggleSection('checks')}
        >
          <SEOChecksList checks={analysis.checks} />
        </CollapsibleSection>

        <CollapsibleSection
          title="Readability"
          icon={BarChart3}
          expanded={expandedSections.includes('readability')}
          onToggle={() => toggleSection('readability')}
        >
          <ReadabilityGrid readability={analysis.readability} />
        </CollapsibleSection>

        {blockHints.length > 0 && (
          <CollapsibleSection
            title="Block Hints"
            icon={Target}
            expanded={expandedSections.includes('blockHints')}
            onToggle={() => toggleSection('blockHints')}
          >
            <PerBlockHints hints={blockHints} />
          </CollapsibleSection>
        )}

        <CollapsibleSection
          title="Basic SEO"
          icon={FileText}
          expanded={expandedSections.includes('basicSeo')}
          onToggle={() => toggleSection('basicSeo')}
        >
          <BasicSEOFields pageSettings={pageSettings} onPageSettingsChange={onPageSettingsChange} />
        </CollapsibleSection>

        <CollapsibleSection
          title="Search Preview"
          icon={Eye}
          expanded={expandedSections.includes('searchPreview')}
          onToggle={() => toggleSection('searchPreview')}
        >
          <SearchPreview pageSettings={pageSettings} />
        </CollapsibleSection>

        <CollapsibleSection
          title="Social Preview"
          icon={Globe}
          expanded={expandedSections.includes('socialPreview')}
          onToggle={() => toggleSection('socialPreview')}
        >
          <SocialPreview pageSettings={pageSettings} />
        </CollapsibleSection>
      </div>
    </div>
  )
}
