import { useState, useEffect } from 'react'
import { api } from './api'
import { StatCard } from './components/StatCard'
import { SettingsPanel } from './components/SettingsPanel'
import type { LinkGraphResult, LinkSuggestion, SemanticSuggestion, Cluster, DuplicatePair, WPPost } from './types'

type Tab = 'graph' | 'suggestions' | 'clusters' | 'duplicates' | 'settings'

export function App() {
  const [tab, setTab] = useState<Tab>('graph')
  const [posts, setPosts] = useState<WPPost[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const [graphResult, setGraphResult] = useState<LinkGraphResult | null>(null)
  const [graphLoading, setGraphLoading] = useState(false)

  const [selectedSlug, setSelectedSlug] = useState('')
  const [selectedPostId, setSelectedPostId] = useState<number | null>(null)
  const [suggestions, setSuggestions] = useState<LinkSuggestion[]>([])
  const [semanticSuggestions, setSemanticSuggestions] = useState<SemanticSuggestion[]>([])
  const [suggestLoading, setSuggestLoading] = useState(false)
  const [useSemanticEngine, setUseSemanticEngine] = useState(false)

  const [clusters, setClusters] = useState<Cluster[]>([])
  const [clusterLoading, setClusterLoading] = useState(false)

  const [duplicates, setDuplicates] = useState<DuplicatePair[]>([])
  const [dupThreshold, setDupThreshold] = useState(0.7)
  const [dupLoading, setDupLoading] = useState(false)

  useEffect(() => {
    api.getPosts().catch(() => []).then((postsData) => {
      setPosts(postsData)
      setLoading(false)
    })
  }, [])

  async function handleBuildGraph() {
    setGraphLoading(true)
    setError('')
    try {
      const result = await api.buildLinkGraph()
      setGraphResult(result)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to build link graph')
    } finally {
      setGraphLoading(false)
    }
  }

  async function handleSuggest() {
    if (!selectedSlug) return
    setSuggestLoading(true)
    setError('')
    setSuggestions([])
    setSemanticSuggestions([])
    try {
      if (useSemanticEngine) {
        if (!selectedPostId) {
          setError('Post ID unavailable — try reloading the page')
          return
        }
        const result = await api.semanticSuggestLinks(selectedPostId)
        setSemanticSuggestions(result.suggestions || [])
      } else {
        const result = await api.suggestLinks(selectedSlug)
        setSuggestions(result.suggestions || [])
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to get suggestions')
    } finally {
      setSuggestLoading(false)
    }
  }

  async function handleClusters() {
    setClusterLoading(true)
    setError('')
    try {
      const result = await api.detectClusters()
      setClusters(result.clusters || [])
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to detect clusters')
    } finally {
      setClusterLoading(false)
    }
  }

  async function handleDuplicates() {
    setDupLoading(true)
    setError('')
    try {
      const result = await api.findDuplicates(dupThreshold)
      setDuplicates((result.duplicates || []).sort((a, b) => b.similarity - a.similarity))
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to find duplicates')
    } finally {
      setDupLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#6C63FF]" />
      </div>
    )
  }

  return (
    <div className="max-w-5xl mx-auto p-6 font-sans">
      <div className="flex items-center gap-3 mb-6">
        <img src={window.supacoContentBridge.logoUrl} alt="Ganda Tech Services" className="h-10 w-auto" />
        <div>
          <h1 className="text-xl font-bold text-[#2E2A59] leading-tight">Supan Content</h1>
          <p className="text-xs text-gray-500">by <a href="https://spectra.cchk.info" target="_blank" rel="noopener noreferrer" className="text-[#6C63FF] hover:underline">Ganda Tech Services</a></p>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-3 bg-red-50 text-red-700 rounded-lg text-sm">{error}</div>
      )}

      {/* Tabs */}
      <div className="flex gap-1 bg-gray-100 p-1 rounded-lg mb-6 w-fit">
        {(['graph', 'suggestions', 'clusters', 'duplicates', 'settings'] as Tab[]).map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            className={`px-4 py-2 text-sm font-medium rounded-md transition-colors capitalize ${
              tab === t ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'
            }`}
          >
            {t === 'graph' ? 'Link Graph' : t === 'suggestions' ? 'Suggestions' : t}
          </button>
        ))}
      </div>

      {/* Link Graph Tab */}
      {tab === 'graph' && (
        <div className="space-y-6">
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h2 className="text-lg font-semibold">Internal Link Graph</h2>
                <p className="text-sm text-gray-500 mt-1">Analyze the link structure across {posts.length} posts</p>
              </div>
              <button onClick={handleBuildGraph} disabled={graphLoading}
                className="px-6 py-2.5 bg-[#6C63FF] text-white rounded-lg font-medium hover:bg-[#5B52E0] disabled:opacity-50 transition-colors">
                {graphLoading ? 'Building...' : 'Build Graph'}
              </button>
            </div>
          </div>

          {graphResult && (
            <>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                <StatCard label="Total Pages" value={Object.keys(graphResult.graph).length} />
                <StatCard label="Orphan Pages" value={graphResult.orphans.length} />
                <StatCard label="Linked Pages" value={Object.keys(graphResult.graph).length - graphResult.orphans.length} />
              </div>

              <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50 border-b border-gray-200">
                    <tr>
                      <th className="text-left px-4 py-3 font-medium text-gray-600">Slug</th>
                      <th className="text-center px-4 py-3 font-medium text-gray-600">Outgoing</th>
                      <th className="text-center px-4 py-3 font-medium text-gray-600">Incoming</th>
                      <th className="text-center px-4 py-3 font-medium text-gray-600">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100">
                    {Object.entries(graphResult.graph).map(([slug, entry]) => (
                      <tr key={slug} className="hover:bg-gray-50">
                        <td className="px-4 py-2 font-mono text-xs">{slug}</td>
                        <td className="px-4 py-2 text-center">{entry.outgoing.length}</td>
                        <td className="px-4 py-2 text-center">{entry.incoming.length}</td>
                        <td className="px-4 py-2 text-center">
                          {graphResult.orphans.includes(slug) ? (
                            <span className="text-xs bg-red-100 text-red-700 px-2 py-0.5 rounded-full">Orphan</span>
                          ) : (
                            <span className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full">Linked</span>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          )}
        </div>
      )}

      {/* Suggestions Tab */}
      {tab === 'suggestions' && (
        <div className="space-y-6">
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <h2 className="text-lg font-semibold mb-4">Get Link Suggestions</h2>
            <div className="flex gap-3 mb-3">
              <select
                value={selectedSlug}
                onChange={(e) => {
                  const slug = e.target.value
                  setSelectedSlug(slug)
                  const post = posts.find((p) => p.slug === slug)
                  setSelectedPostId(post ? post.id : null)
                }}
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#6C63FF] outline-none text-sm"
              >
                <option value="">Select a post...</option>
                {posts.map((p) => (
                  <option key={p.id} value={p.slug}>{p.title}</option>
                ))}
              </select>
              <button onClick={handleSuggest} disabled={!selectedSlug || suggestLoading}
                className="px-6 py-2.5 bg-[#6C63FF] text-white rounded-lg font-medium hover:bg-[#5B52E0] disabled:opacity-50 transition-colors">
                {suggestLoading ? 'Loading...' : 'Get Suggestions'}
              </button>
            </div>
            <label className="flex items-center gap-2 text-sm text-gray-600 cursor-pointer">
              <input
                type="checkbox"
                checked={useSemanticEngine}
                onChange={e => setUseSemanticEngine(e.target.checked)}
                className="rounded"
              />
              Use semantic engine
              <span className="text-xs bg-purple-100 text-purple-700 px-1.5 py-0.5 rounded">
                AI-powered
              </span>
            </label>
          </div>

          {suggestions.length > 0 && (
            <div className="space-y-3">
              {suggestions.map((s, i) => (
                <div key={i} className="bg-white rounded-xl border border-gray-200 p-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium text-sm">{s.target_title}</p>
                      <p className="text-xs text-gray-500 mt-1">{s.reason}</p>
                    </div>
                    <span className={`text-xs font-bold px-2 py-1 rounded-full ${
                      s.relevance_score >= 0.8 ? 'bg-green-100 text-green-700' :
                      s.relevance_score >= 0.5 ? 'bg-yellow-100 text-yellow-700' :
                      'bg-gray-100 text-gray-600'
                    }`}>
                      {Math.round(s.relevance_score * 100)}%
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}

          {semanticSuggestions.length > 0 && (
            <div className="space-y-3">
              <p className="text-xs text-purple-600 font-medium uppercase tracking-wide">
                AI-powered semantic suggestions
              </p>
              {semanticSuggestions.map((s, i) => (
                <div key={i} className="bg-white rounded-xl border border-purple-200 p-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium text-sm">{s.title}</p>
                      <p className="text-xs text-gray-500 mt-1">{s.reason}</p>
                    </div>
                    <span className={`text-xs font-bold px-2 py-1 rounded-full ${
                      s.relevance >= 0.8 ? 'bg-green-100 text-green-700' :
                      s.relevance >= 0.5 ? 'bg-yellow-100 text-yellow-700' :
                      'bg-gray-100 text-gray-600'
                    }`}>
                      {Math.round(s.relevance * 100)}%
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Clusters Tab */}
      {tab === 'clusters' && (
        <div className="space-y-6">
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-lg font-semibold">Topic Clusters</h2>
                <p className="text-sm text-gray-500 mt-1">Detect content groups by topic</p>
              </div>
              <button onClick={handleClusters} disabled={clusterLoading}
                className="px-6 py-2.5 bg-[#6C63FF] text-white rounded-lg font-medium hover:bg-[#5B52E0] disabled:opacity-50 transition-colors">
                {clusterLoading ? 'Detecting...' : 'Detect Clusters'}
              </button>
            </div>
          </div>

          {clusters.length > 0 && (
            <div className="grid gap-4 md:grid-cols-2">
              {clusters.map((c, i) => (
                <div key={i} className="bg-white rounded-xl border border-gray-200 p-4">
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-medium text-sm">{c.tag}</span>
                    <span className="text-xs bg-purple-100 text-purple-700 px-2 py-0.5 rounded-full">{c.size} posts</span>
                  </div>
                  <div className="flex flex-wrap gap-1">
                    {c.posts.map((slug) => (
                      <span key={slug} className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded">{slug}</span>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Duplicates Tab */}
      {tab === 'duplicates' && (
        <div className="space-y-6">
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h2 className="text-lg font-semibold">Duplicate Content</h2>
                <p className="text-sm text-gray-500 mt-1">Find near-duplicate posts by similarity</p>
              </div>
              <button onClick={handleDuplicates} disabled={dupLoading}
                className="px-6 py-2.5 bg-[#6C63FF] text-white rounded-lg font-medium hover:bg-[#5B52E0] disabled:opacity-50 transition-colors">
                {dupLoading ? 'Scanning...' : 'Find Duplicates'}
              </button>
            </div>
            <div>
              <label className="text-sm text-gray-600">Similarity threshold: {Math.round(dupThreshold * 100)}%</label>
              <input type="range" min="50" max="100" value={dupThreshold * 100}
                onChange={(e) => setDupThreshold(Number(e.target.value) / 100)}
                className="w-full mt-1"
              />
            </div>
          </div>

          {duplicates.length > 0 && (
            <div className="space-y-3">
              {duplicates.map((d, i) => (
                <div key={i} className={`rounded-xl border p-4 ${
                  d.similarity >= 0.9 ? 'bg-red-50 border-red-200' :
                  d.similarity >= 0.7 ? 'bg-yellow-50 border-yellow-200' :
                  'bg-purple-50 border-purple-200'
                }`}>
                  <div className="flex items-center justify-between">
                    <div className="text-sm">
                      <span className="font-mono">{d.slug_a}</span>
                      <span className="text-gray-400 mx-2">&harr;</span>
                      <span className="font-mono">{d.slug_b}</span>
                    </div>
                    <span className="text-xs font-bold px-2 py-1 rounded-full bg-white/80">
                      {Math.round(d.similarity * 100)}%
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Settings Tab */}
      {tab === 'settings' && (
        <SettingsPanel />
      )}
    </div>
  )
}
