'use client'

import { useState, useEffect } from 'react'
import { NetworkGraph } from '@/components/network-graph'
import { useRouter } from 'next/navigation'
import { motion } from 'motion/react'
import { Sparkles, RefreshCw, Layers, Trophy, Zap, Lightbulb } from 'lucide-react'

interface Note {
  id: string
  title: string | null
  content: string
  clusterId?: number
}

interface Cluster {
  id: string
  clusterId: number
  name?: string
  noteIds: string[]
  color?: string
}

interface BridgeNote {
  noteId: string
  bridgeScore: number
  clustersConnected: number[]
  clusterNames?: string[]
  note?: {
    id: string
    title: string | null
    content: string
  }
}

interface BridgeSuggestion {
  clusterAId: number
  clusterBId: number
  clusterAName: string
  clusterBName: string
  suggestedTitle: string
  suggestedContent: string
  justification: string
}

const COLOR_PALETTE = ['#F87171', '#60A5FA', '#34D399', '#FBBF24', '#A78BFA', '#F472B6', '#2DD4BF']

export default function InsightsPage() {
  const router = useRouter()
  const [notes, setNotes] = useState<Note[]>([])
  const [clusters, setClusters] = useState<Cluster[]>([])
  const [bridgeNotes, setBridgeNotes] = useState<BridgeNote[]>([])
  const [suggestions, setSuggestions] = useState<BridgeSuggestion[]>([])
  const [loading, setLoading] = useState(true)
  const [isCalculating, setIsCalculating] = useState(false)

  useEffect(() => {
    loadInitialData()
  }, [])

  const loadInitialData = async () => {
    setLoading(true)
    try {
      // First, try to get cached clusters
      const res = await fetch('/api/clusters')
      if (res.ok) {
        const data = await res.json()

        // Check if we have clusters
        if (data.clusters && data.clusters.length > 0) {
          const clustersWithColors = data.clusters.map((c: Cluster, i: number) => ({
            ...c,
            id: c.clusterId.toString(),
            color: COLOR_PALETTE[i % COLOR_PALETTE.length]
          }))
          setNotes(data.notes || [])
          setClusters(clustersWithColors)

          // Load bridge notes
          const bridgeRes = await fetch('/api/bridge-notes?details=true')
          if (bridgeRes.ok) {
            const bridgeData = await bridgeRes.json()
            setBridgeNotes(bridgeData.bridgeNotes || [])
          }

          // Load suggestions
          const suggestionsRes = await fetch('/api/bridge-notes/suggestions')
          if (suggestionsRes.ok) {
            const suggestionsData = await suggestionsRes.json()
            setSuggestions(suggestionsData.suggestions || [])
          }
        } else {
          // No clusters - trigger calculation if we have enough notes
          if (data.totalNotes >= 10) {
            await performAnalysis()
          } else {
            // Not enough notes - show empty state
          }
        }
      }
    } catch (error) {
      console.error('Error loading data:', error)
    } finally {
      setLoading(false)
    }
  }

  const performAnalysis = async () => {
    setIsCalculating(true)
    try {
      const res = await fetch('/api/clusters', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ force: true })
      })

      if (res.ok) {
        const data = await res.json()
        const clustersWithColors = (data.clusters || []).map((c: Cluster, i: number) => ({
          ...c,
          id: c.clusterId.toString(),
          color: COLOR_PALETTE[i % COLOR_PALETTE.length]
        }))
        setNotes(data.notes || [])
        setClusters(clustersWithColors)
        setBridgeNotes(data.bridgeNotes || [])

        // Load suggestions (they were generated during POST)
        const suggestionsRes = await fetch('/api/bridge-notes/suggestions')
        if (suggestionsRes.ok) {
          const suggestionsData = await suggestionsRes.json()
          setSuggestions(suggestionsData.suggestions || [])
        }
      }
    } catch (error) {
      console.error('Error running analysis:', error)
    } finally {
      setIsCalculating(false)
    }
  }

  const handleNoteClick = (noteId: string) => {
    router.push(`/home?note=${noteId}`)
  }

  const bridgeList = bridgeNotes.map(b => ({
    ...b,
    title: b.note?.title || 'Unknown Note'
  }))

  return (
    <div className="h-full flex flex-col bg-paper dark:bg-[#0D0D0D] overflow-hidden">
      {/* Header */}
      <div className="p-8 border-b border-border/40 flex items-center justify-between backdrop-blur-xl bg-white/40 dark:bg-black/20 z-10">
        <div>
          <div className="flex items-center gap-3 mb-1">
            <div className="w-8 h-8 rounded-lg bg-indigo-500/10 flex items-center justify-center text-indigo-500">
              <Sparkles size={18} />
            </div>
            <h1 className="text-2xl font-serif font-medium text-ink dark:text-dark-ink">Semantic Insights</h1>
          </div>
          <p className="text-[11px] text-concrete tracking-[0.2em] uppercase font-bold">Discovering the hidden architecture of your knowledge</p>
        </div>
        <button
          onClick={performAnalysis}
          disabled={isCalculating}
          className="flex items-center gap-2 px-6 py-2.5 bg-ink text-paper dark:bg-white dark:text-black rounded-full text-xs font-bold uppercase tracking-widest hover:scale-105 active:scale-95 transition-all disabled:opacity-50"
        >
          {isCalculating ? <RefreshCw size={14} className="animate-spin" /> : <RefreshCw size={14} />}
          {isCalculating ? 'Mapping...' : 'Re-sync Network'}
        </button>
      </div>

      {/* Loading State */}
      {loading && (
        <div className="flex-1 flex items-center justify-center">
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="text-center"
          >
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-500 mx-auto mb-4"></div>
            <p className="text-concrete">Analyzing your notes...</p>
          </motion.div>
        </div>
      )}

      {/* Empty State - only if truly no notes */}
      {!loading && clusters.length === 0 && !isCalculating && (
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center max-w-md">
            <div className="w-24 h-24 rounded-full bg-concrete/10 flex items-center justify-center mx-auto mb-6">
              <Sparkles size={40} className="text-concrete/40" />
            </div>
            <h3 className="text-xl font-serif font-medium text-ink dark:text-dark-ink mb-2">
              Discover your knowledge clusters
            </h3>
            <p className="text-concrete mb-6">
              Click "Re-sync Network" to analyze your notes and find hidden connections
            </p>
          </div>
        </div>
      )}

      {/* Main Content */}
      {!loading && clusters.length > 0 && (
        <div className="flex-1 flex overflow-hidden">
          {/* Left: Graph View */}
          <div className="flex-[1.5] p-6 relative">
            <NetworkGraph
              notes={notes}
              clusters={clusters}
              bridgeNotes={bridgeNotes}
              onNoteSelect={handleNoteClick}
            />
          </div>

          {/* Right: Insight Dashboard */}
          <div className="flex-1 border-l border-border/40 flex flex-col h-full bg-paper/50 dark:bg-black/10 backdrop-blur-sm overflow-hidden">
            <div className="p-8 flex-1 overflow-y-auto custom-scrollbar space-y-12">
              {/* Stats Summary */}
              <div className="grid grid-cols-2 gap-4">
                <div className="p-5 rounded-2xl bg-white dark:bg-white/5 border border-border shadow-sm">
                  <div className="flex items-center gap-2 text-indigo-500 mb-2">
                    <Layers size={14} />
                    <span className="text-[10px] font-bold uppercase tracking-widest">Clusters</span>
                  </div>
                  <div className="text-3xl font-serif font-medium text-ink dark:text-dark-ink">{clusters.length}</div>
                </div>
                <div className="p-5 rounded-2xl bg-white dark:bg-white/5 border border-border shadow-sm">
                  <div className="flex items-center gap-2 text-ochre mb-2">
                    <Trophy size={14} />
                    <span className="text-[10px] font-bold uppercase tracking-widest">Bridge Notes</span>
                  </div>
                  <div className="text-3xl font-serif font-medium text-ink dark:text-dark-ink">{bridgeNotes.length}</div>
                </div>
              </div>

              {/* Bridge Notes Section */}
              <section>
                <div className="flex items-center gap-2 mb-6 px-1">
                  <Zap size={16} className="text-ochre" />
                  <h3 className="text-sm font-bold uppercase tracking-widest text-ink dark:text-dark-ink">Powerful Bridge Notes</h3>
                </div>
                <div className="space-y-3">
                  {bridgeList.map((bridge) => (
                    <motion.div
                      key={bridge.noteId}
                      whileHover={{ x: 4 }}
                      onClick={() => handleNoteClick(bridge.noteId)}
                      className="p-4 rounded-xl bg-white dark:bg-white/5 border border-border hover:border-ochre/40 transition-all cursor-pointer group"
                    >
                      <div className="flex items-center justify-between mb-2">
                        <h4 className="text-sm font-medium text-ink dark:text-dark-ink truncate flex-1">
                          {bridge.title}
                        </h4>
                        <span className="text-[10px] font-bold text-ochre bg-ochre/10 px-2 py-0.5 rounded-full">
                          Score: {(bridge.bridgeScore * 100).toFixed(0)}%
                        </span>
                      </div>
                      <div className="flex items-center gap-2">
                        {bridge.clusterNames?.map((name, i) => {
                          const cluster = clusters.find(c => c.name === name)
                          return (
                            <div key={i} className="flex items-center gap-1">
                              <div className="w-1.5 h-1.5 rounded-full" style={{ backgroundColor: cluster?.color || '#cbd5e1' }} />
                              <span className="text-[9px] text-concrete font-medium whitespace-nowrap">{name}</span>
                            </div>
                          )
                        })}
                      </div>
                    </motion.div>
                  ))}
                  {bridgeList.length === 0 && !isCalculating && (
                    <div className="text-xs text-concrete italic">No significant bridge notes found yet. Deepen your research to find new connections.</div>
                  )}
                </div>
              </section>

              {/* Connection Suggestions */}
              <section>
                <div className="flex items-center gap-2 mb-6 px-1">
                  <Lightbulb size={16} className="text-indigo-500" />
                  <h3 className="text-sm font-bold uppercase tracking-widest text-ink dark:text-dark-ink">Missing Links (AI Generated)</h3>
                </div>
                <div className="space-y-4">
                  {suggestions.map((s, idx) => (
                    <div key={`${s.clusterAId}-${s.clusterBId}`} className="p-6 rounded-2xl bg-gradient-to-br from-indigo-500/5 to-transparent border border-indigo-500/10 hover:border-indigo-500/30 transition-all">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-3 mb-4">
                            <div className="flex -space-x-2">
                              <div className="w-6 h-6 rounded-full border-2 border-paper bg-indigo-500 flex items-center justify-center text-[10px] text-white">A</div>
                              <div className="w-6 h-6 rounded-full border-2 border-paper bg-ochre flex items-center justify-center text-[10px] text-white">B</div>
                            </div>
                            <span className="text-[9px] font-bold uppercase tracking-widest text-indigo-500/60">
                              Bridging {s.clusterAName} & {s.clusterBName}
                            </span>
                          </div>
                          <h4 className="text-base font-serif font-medium text-ink dark:text-dark-ink mb-2">{s.suggestedTitle}</h4>
                          <p className="text-xs text-muted-ink leading-relaxed mb-4">{s.suggestedContent}</p>
                          <div className="p-3 bg-white/40 dark:bg-white/5 rounded-xl border border-border/40 text-[10px] italic text-concrete flex gap-2">
                            <Zap size={12} className="shrink-0" />
                            <span>{s.justification}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                  {suggestions.length === 0 && !isCalculating && (
                    <div className="text-center py-8 text-concrete">
                      <Lightbulb size={24} className="mx-auto mb-3 opacity-50" />
                      <p className="text-sm">No connection suggestions yet</p>
                      <p className="text-xs mt-1">All your clusters may already be connected!</p>
                    </div>
                  )}
                  {isCalculating && (
                    <div className="animate-pulse space-y-4">
                      {[1, 2].map(i => (
                        <div key={i} className="h-32 bg-indigo-500/5 rounded-2xl border border-indigo-500/10" />
                      ))}
                    </div>
                  )}
                </div>
              </section>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
