'use client'

import { useMemo } from 'react'
import { ScatterChart, Scatter, XAxis, YAxis, ZAxis, ResponsiveContainer, Tooltip, Cell } from 'recharts'
import { useTheme } from '@/hooks/useTheme'
import { getChartChrome, getTooltipStyle, severityColor } from '../utils/chartTheme'
import { ChartCard } from './ChartCard'
import type { CveChain, Exploit } from '../types'

interface CvssExploitScatterProps {
  cveChains: CveChain[] | undefined
  exploits: Exploit[] | undefined
  isLoading: boolean
}

interface ScatterPoint {
  cveId: string
  cvss: number
  capecCount: number
  severity: string
  hasExploit: boolean
  tech: string
}

export function CvssExploitScatter({ cveChains, exploits, isLoading }: CvssExploitScatterProps) {
  const { theme } = useTheme()
  const chrome = useMemo(() => getChartChrome(), [theme])
  const tooltipStyle = useMemo(() => getTooltipStyle(), [theme])

  const chartData = useMemo(() => {
    if (!cveChains?.length) return []

    // Build a set of CVE IDs that have confirmed exploits
    const exploitedCves = new Set<string>()
    for (const ex of exploits || []) {
      for (const id of ex.cveIds || []) exploitedCves.add(id)
    }

    // Aggregate: group by CVE ID
    const byId = new Map<string, ScatterPoint>()
    for (const chain of cveChains) {
      if (!chain.cveId || chain.cvss == null) continue
      const existing = byId.get(chain.cveId)
      if (existing) {
        if (chain.capecId) existing.capecCount++
      } else {
        byId.set(chain.cveId, {
          cveId: chain.cveId,
          cvss: chain.cvss,
          capecCount: chain.capecId ? 1 : 0,
          severity: (chain.cveSeverity || 'unknown').toLowerCase(),
          hasExploit: exploitedCves.has(chain.cveId),
          tech: chain.tech,
        })
      }
    }

    return Array.from(byId.values())
  }, [cveChains, exploits])

  return (
    <ChartCard
      title="CVSS vs Exploitability"
      subtitle={`${chartData.length} CVEs`}
      isLoading={isLoading}
      isEmpty={chartData.length === 0}
    >
      <ResponsiveContainer width="100%" height={220}>
        <ScatterChart margin={{ left: 0, right: 8, top: 8, bottom: 8 }}>
          <XAxis
            dataKey="cvss"
            type="number"
            domain={[0, 10]}
            name="CVSS"
            tick={{ fontSize: 11, fill: chrome.axisColor }}
            axisLine={false}
            tickLine={false}
            label={{ value: 'CVSS', position: 'insideBottom', offset: -2, fontSize: 10, fill: chrome.axisColor }}
          />
          <YAxis
            dataKey="capecCount"
            type="number"
            name="Attack Patterns"
            tick={{ fontSize: 11, fill: chrome.axisColor }}
            axisLine={false}
            tickLine={false}
            width={35}
            label={{ value: 'CAPEC', angle: -90, position: 'insideLeft', fontSize: 10, fill: chrome.axisColor }}
          />
          <ZAxis dataKey="capecCount" range={[40, 200]} />
          <Tooltip
            content={({ payload }) => {
              if (!payload?.length) return null
              const d = payload[0].payload as ScatterPoint
              return (
                <div style={{ ...tooltipStyle, padding: '8px 12px' }}>
                  <div style={{ fontWeight: 600, marginBottom: 4 }}>{d.cveId}</div>
                  <div style={{ fontSize: 11 }}>CVSS: {d.cvss} ({d.severity})</div>
                  <div style={{ fontSize: 11 }}>Attack patterns: {d.capecCount}</div>
                  <div style={{ fontSize: 11 }}>Technology: {d.tech}</div>
                  {d.hasExploit && (
                    <div style={{ fontSize: 11, color: '#e53935', fontWeight: 600, marginTop: 2 }}>
                      Confirmed exploit
                    </div>
                  )}
                </div>
              )
            }}
          />
          <Scatter data={chartData} isAnimationActive={false}>
            {chartData.map((entry, i) => (
              <Cell
                key={i}
                fill={severityColor(entry.severity)}
                stroke={entry.hasExploit ? '#e53935' : 'none'}
                strokeWidth={entry.hasExploit ? 2 : 0}
                opacity={0.75}
              />
            ))}
          </Scatter>
        </ScatterChart>
      </ResponsiveContainer>
    </ChartCard>
  )
}
