import { useState, useCallback, useEffect } from 'react'
import Tree from 'react-d3-tree'
import { ZoomIn, ZoomOut, Maximize2 } from 'lucide-react'
import './PedigreeTree.css'

const PedigreeTree = ({ dogId, pedigreeData, coi }) => {
  const [translate, setTranslate] = useState({ x: 0, y: 0 })
  const [zoom, setZoom] = useState(0.8)
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 })

  useEffect(() => {
    const updateDimensions = () => {
      const container = document.getElementById('tree-container')
      if (container) {
        setDimensions({ width: container.offsetWidth, height: container.offsetHeight })
        setTranslate({ x: container.offsetWidth / 4, y: container.offsetHeight / 2 })
      }
    }
    updateDimensions()
    window.addEventListener('resize', updateDimensions)
    return () => window.removeEventListener('resize', updateDimensions)
  }, [])

  const handleZoomIn  = () => setZoom(z => Math.min(z + 0.2, 2))
  const handleZoomOut = () => setZoom(z => Math.max(z - 0.2, 0.2))
  const handleReset   = () => {
    setZoom(0.8)
    setTranslate({ x: dimensions.width / 4, y: dimensions.height / 2 })
  }

  const renderCustomNode = ({ nodeDatum }) => {
    const isRoot   = nodeDatum.attributes?.isRoot
    const isMale   = nodeDatum.attributes?.sex === 'male'
    const hasId    = !!nodeDatum.attributes?.id
    const breed    = nodeDatum.attributes?.breed

    // Colour palette aligned to app theme
    const maleColor   = '#3b82f6'
    const femaleColor = '#ec4899'
    const rootGold    = '#c2862a'   // --primary
    const rootAccent  = '#9b3a10'   // --accent

    const nodeColor   = isRoot ? rootGold : (isMale ? maleColor : femaleColor)
    const glowColor   = isRoot
      ? 'rgba(194,134,42,0.35)'
      : (isMale ? 'rgba(59,130,246,0.3)' : 'rgba(236,72,153,0.3)')
    const ringColor   = isRoot ? rootAccent : nodeColor

    const r = isRoot ? 34 : 28

    return (
      <g>
        {/* Glow halo */}
        <circle
          r={r + 10}
          fill={glowColor}
          style={{ filter: 'blur(6px)' }}
        />

        {/* Outer ring */}
        <circle
          r={r + 4}
          fill="none"
          stroke={ringColor}
          strokeWidth={isRoot ? 2 : 1.5}
          strokeOpacity={0.5}
        />

        {/* Main node */}
        <circle
          r={r}
          fill={isRoot
            ? `url(#rootGradient)`
            : nodeColor}
          stroke="rgba(255,255,255,0.15)"
          strokeWidth={2}
          style={{
            cursor: hasId ? 'pointer' : 'default',
            filter: isRoot ? 'drop-shadow(0 0 8px rgba(194,134,42,0.6))' : 'none'
          }}
          onClick={() => {
            if (hasId) window.location.href = `/dogs/${nodeDatum.attributes.id}`
          }}
        />

        {/* SVG gradient definition for root node */}
        {isRoot && (
          <defs>
            <radialGradient id="rootGradient" cx="35%" cy="35%">
              <stop offset="0%"  stopColor="#e0a84a" />
              <stop offset="100%" stopColor="#9b3a10" />
            </radialGradient>
          </defs>
        )}

        {/* Gender / crown icon */}
        <text
          fill={isRoot ? '#fff' : '#fff'}
          fontSize={isRoot ? 22 : 18}
          textAnchor="middle"
          dy="7"
          style={{ pointerEvents: 'none', userSelect: 'none' }}
        >
          {isRoot ? '👑' : (isMale ? '♂' : '♀')}
        </text>

        {/* Name label */}
        <text
          fill="var(--text-primary, #f5f0e8)"
          fontSize={isRoot ? 15 : 13}
          fontWeight={isRoot ? '700' : '600'}
          fontFamily="Inter, sans-serif"
          textAnchor="middle"
          x="0"
          y={r + 18}
          style={{ pointerEvents: 'none' }}
        >
          {nodeDatum.name}
        </text>

        {/* Breed label (subtle) */}
        {breed && (
          <text
            fill="var(--text-muted, #8c8472)"
            fontSize="10"
            fontFamily="Inter, sans-serif"
            textAnchor="middle"
            x="0"
            y={r + 31}
            style={{ pointerEvents: 'none' }}
          >
            {breed}
          </text>
        )}

        {/* Registration number */}
        {nodeDatum.attributes?.registration && (
          <text
            fill="var(--text-muted, #8c8472)"
            fontSize="10"
            fontFamily="Inter, sans-serif"
            textAnchor="middle"
            x="0"
            y={r + (breed ? 44 : 31)}
            style={{ pointerEvents: 'none' }}
          >
            {nodeDatum.attributes.registration}
          </text>
        )}

        {/* Birth year */}
        {nodeDatum.attributes?.birth_year && (
          <text
            fill="var(--text-muted, #8c8472)"
            fontSize="10"
            fontFamily="Inter, sans-serif"
            textAnchor="middle"
            x="0"
            y={r + (breed ? 57 : (nodeDatum.attributes?.registration ? 44 : 31))}
            style={{ pointerEvents: 'none' }}
          >
            ({nodeDatum.attributes.birth_year})
          </text>
        )}
      </g>
    )
  }

  return (
    <div className="pedigree-tree-wrapper">

      {/* Controls */}
      <div className="pedigree-controls">
        <div className="control-group">
          <button onClick={handleZoomIn}  className="control-btn" title="Zoom In">
            <ZoomIn size={18} />
          </button>
          <button onClick={handleZoomOut} className="control-btn" title="Zoom Out">
            <ZoomOut size={18} />
          </button>
          <button onClick={handleReset}   className="control-btn" title="Reset View">
            <Maximize2 size={18} />
          </button>
        </div>

        {coi !== null && coi !== undefined && (
          <div className="coi-display">
            <span className="coi-label">COI</span>
            <span className={`coi-value ${coi > 10 ? 'high' : coi > 5 ? 'medium' : 'low'}`}>
              {coi.toFixed(2)}%
            </span>
          </div>
        )}
      </div>

      {/* Legend */}
      <div className="pedigree-legend">
        <div className="legend-item">
          <div className="legend-color male" />
          <span>Sire</span>
        </div>
        <div className="legend-item">
          <div className="legend-color female" />
          <span>Dam</span>
        </div>
        <div className="legend-item">
          <div style={{
            width: 14, height: 14, borderRadius: '50%',
            background: 'linear-gradient(135deg, #e0a84a, #9b3a10)',
            boxShadow: '0 0 8px rgba(194,134,42,0.5)',
            border: '2px solid rgba(255,255,255,0.15)'
          }} />
          <span>Subject</span>
        </div>
      </div>

      {/* Zoom indicator */}
      <div className="zoom-indicator">
        {Math.round(zoom * 100)}%
      </div>

      {/* Tree canvas */}
      <div id="tree-container" className="tree-container">
        {pedigreeData && dimensions.width > 0 && (
          <Tree
            data={pedigreeData}
            translate={translate}
            zoom={zoom}
            onUpdate={({ zoom: z, translate: t }) => {
              setZoom(z)
              setTranslate(t)
            }}
            orientation="horizontal"
            pathFunc="step"
            separation={{ siblings: 1.6, nonSiblings: 2.2 }}
            nodeSize={{ x: 220, y: 160 }}
            renderCustomNodeElement={renderCustomNode}
            enableLegacyTransitions
            transitionDuration={300}
          />
        )}
      </div>
    </div>
  )
}

export default PedigreeTree
