'use client'

import { useEffect, useState } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { CommandCenterLayout } from '@/components/CommandCenterLayout'
import { PageContainer, StatCard, Badge } from '@/components/PremiumTable'
import {
  Search,
  Link2,
  Globe,
  Shield,
  TrendingUp,
  Loader2,
  AlertCircle,
  X,
  ExternalLink,
  Crown,
  CheckCircle,
  Sparkles,
  BookOpen,
  Building,
  GraduationCap,
  Newspaper,
  Lock,
  Star,
} from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

interface SEOData {
  domain: string
  seo_score: number
  value_category: string
  metrics: {
    domain_authority: number | null
    page_authority: number | null
    spam_score: number | null
    total_backlinks: number | null
    referring_domains: number | null
  }
  notable_links: {
    has_wikipedia: boolean
    has_gov: boolean
    has_edu: boolean
    has_news: boolean
    notable_domains: string[]
  }
  top_backlinks: Array<{
    domain: string
    authority: number
    page: string
  }>
  estimated_value: number | null
  data_source: string
  last_updated: string | null
  is_estimated: boolean
}

export default function SEOPage() {
  const { subscription } = useStore()
  
  const [domain, setDomain] = useState('')
  const [loading, setLoading] = useState(false)
  const [seoData, setSeoData] = useState<SEOData | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [recentSearches, setRecentSearches] = useState<string[]>([])

  const tier = subscription?.tier?.toLowerCase() || 'scout'
  const isTycoon = tier === 'tycoon'

  useEffect(() => {
    // Load recent searches from localStorage
    const saved = localStorage.getItem('seo-recent-searches')
    if (saved) {
      setRecentSearches(JSON.parse(saved))
    }
  }, [])

  const saveRecentSearch = (domain: string) => {
    const updated = [domain, ...recentSearches.filter(d => d !== domain)].slice(0, 5)
    setRecentSearches(updated)
    localStorage.setItem('seo-recent-searches', JSON.stringify(updated))
  }

  const cleanDomain = (d: string): string => {
    // Remove whitespace, protocol, www, and trailing slashes
    return d.trim()
      .toLowerCase()
      .replace(/\s+/g, '')
      .replace(/^https?:\/\//, '')
      .replace(/^www\./, '')
      .replace(/\/.*$/, '')
  }

  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault()
    const cleanedDomain = cleanDomain(domain)
    if (!cleanedDomain) return

    setLoading(true)
    setError(null)
    setSeoData(null)

    try {
      const data = await api.request<SEOData>(`/seo/${encodeURIComponent(cleanedDomain)}`)
      setSeoData(data)
      saveRecentSearch(cleanedDomain)
    } catch (err: any) {
      setError(err.message || 'Failed to analyze domain')
    } finally {
      setLoading(false)
    }
  }

  const handleQuickSearch = async (searchDomain: string) => {
    const cleanedDomain = cleanDomain(searchDomain)
    setDomain(cleanedDomain)
    setLoading(true)
    setError(null)
    setSeoData(null)

    try {
      const data = await api.request<SEOData>(`/seo/${encodeURIComponent(cleanedDomain)}`)
      setSeoData(data)
    } catch (err: any) {
      setError(err.message || 'Failed to analyze domain')
    } finally {
      setLoading(false)
    }
  }

  const getScoreColor = (score: number) => {
    if (score >= 60) return 'text-accent'
    if (score >= 40) return 'text-amber-400'
    if (score >= 20) return 'text-orange-400'
    return 'text-foreground-muted'
  }

  const getScoreBg = (score: number) => {
    if (score >= 60) return 'bg-accent/10 border-accent/30'
    if (score >= 40) return 'bg-amber-500/10 border-amber-500/30'
    if (score >= 20) return 'bg-orange-500/10 border-orange-500/30'
    return 'bg-foreground/5 border-border'
  }

  const formatNumber = (num: number | null) => {
    if (num === null) return '-'
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
    if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
    return num.toString()
  }

  // Show upgrade prompt for non-Tycoon users
  if (!isTycoon) {
    return (
      <CommandCenterLayout
        title="SEO Juice Detector"
        subtitle="Backlink analysis & domain authority"
      >
        <PageContainer>
          <div className="text-center py-16 bg-gradient-to-br from-accent/10 to-accent/5 border border-accent/20 rounded-2xl">
            <div className="w-20 h-20 bg-accent/20 rounded-full flex items-center justify-center mx-auto mb-6">
              <Crown className="w-10 h-10 text-accent" />
            </div>
            <h2 className="text-2xl font-semibold text-foreground mb-3">Tycoon Feature</h2>
            <p className="text-foreground-muted max-w-lg mx-auto mb-8">
              SEO Juice Detector is a premium feature for serious domain investors. 
              Analyze backlinks, domain authority, and find hidden gems that SEO agencies pay 
              $100-$500 for — even if the name is "ugly".
            </p>
            
            <div className="grid sm:grid-cols-3 gap-4 max-w-2xl mx-auto mb-8">
              <div className="p-4 bg-background/50 rounded-xl">
                <Link2 className="w-6 h-6 text-accent mx-auto mb-2" />
                <p className="text-sm text-foreground font-medium">Backlink Analysis</p>
                <p className="text-xs text-foreground-muted">Top referring domains</p>
              </div>
              <div className="p-4 bg-background/50 rounded-xl">
                <TrendingUp className="w-6 h-6 text-accent mx-auto mb-2" />
                <p className="text-sm text-foreground font-medium">Domain Authority</p>
                <p className="text-xs text-foreground-muted">Moz DA/PA scores</p>
              </div>
              <div className="p-4 bg-background/50 rounded-xl">
                <Star className="w-6 h-6 text-accent mx-auto mb-2" />
                <p className="text-sm text-foreground font-medium">Notable Links</p>
                <p className="text-xs text-foreground-muted">Wikipedia, .gov, .edu</p>
              </div>
            </div>
            
            <Link
              href="/pricing"
              className="inline-flex items-center gap-2 px-6 py-3 bg-accent text-background font-medium rounded-xl hover:bg-accent-hover transition-all"
            >
              <Crown className="w-5 h-5" />
              Upgrade to Tycoon
            </Link>
          </div>
        </PageContainer>
      </CommandCenterLayout>
    )
  }

  return (
    <CommandCenterLayout
      title="SEO Juice Detector"
      subtitle="Analyze backlinks, domain authority & find hidden SEO gems"
    >
      <PageContainer>
        {/* Error Message */}
        {error && (
          <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-xl flex items-center gap-3">
            <AlertCircle className="w-5 h-5 text-red-400" />
            <p className="text-sm text-red-400 flex-1">{error}</p>
            <button onClick={() => setError(null)}><X className="w-4 h-4 text-red-400" /></button>
          </div>
        )}

        {/* Search Form */}
        <div className="p-6 bg-background-secondary/30 border border-border rounded-2xl">
          <form onSubmit={handleSearch} className="flex gap-3">
            <div className="relative flex-1">
              <Globe className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-foreground-subtle" />
              <input
                type="text"
                value={domain}
                onChange={(e) => setDomain(e.target.value)}
                placeholder="Enter domain to analyze (e.g., example.com)"
                className="w-full pl-12 pr-4 py-3 bg-background border border-border rounded-xl
                           text-foreground placeholder:text-foreground-subtle
                           focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent"
              />
            </div>
            <button
              type="submit"
              disabled={loading || !domain.trim()}
              className="flex items-center gap-2 px-6 py-3 bg-accent text-background font-medium rounded-xl
                         hover:bg-accent-hover transition-all disabled:opacity-50"
            >
              {loading ? (
                <Loader2 className="w-5 h-5 animate-spin" />
              ) : (
                <Search className="w-5 h-5" />
              )}
              Analyze
            </button>
          </form>

          {/* Recent Searches */}
          {recentSearches.length > 0 && !seoData && (
            <div className="mt-4 flex items-center gap-2 flex-wrap">
              <span className="text-xs text-foreground-muted">Recent:</span>
              {recentSearches.map((d) => (
                <button
                  key={d}
                  onClick={() => handleQuickSearch(d)}
                  className="px-3 py-1 text-xs bg-foreground/5 text-foreground-muted rounded-full hover:bg-foreground/10 transition-colors"
                >
                  {d}
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Loading State */}
        {loading && (
          <div className="flex flex-col items-center justify-center py-16">
            <Loader2 className="w-8 h-8 text-accent animate-spin mb-4" />
            <p className="text-foreground-muted">Analyzing backlinks & authority...</p>
          </div>
        )}

        {/* Results */}
        {seoData && !loading && (
          <div className="space-y-6 animate-slide-up">
            {/* Header with Score */}
            <div className="p-6 bg-background-secondary/30 border border-border rounded-2xl">
              <div className="flex flex-wrap items-start justify-between gap-4">
                <div>
                  <h2 className="font-mono text-2xl font-medium text-foreground mb-1">
                    {seoData.domain}
                  </h2>
                  <div className="flex items-center gap-2">
                    <Badge variant={seoData.is_estimated ? 'warning' : 'success'}>
                      {seoData.data_source === 'moz' ? 'Moz Data' : 'Estimated'}
                    </Badge>
                    <span className="text-sm text-foreground-muted">{seoData.value_category}</span>
                  </div>
                </div>
                <div className={clsx(
                  "w-24 h-24 rounded-2xl border flex flex-col items-center justify-center",
                  getScoreBg(seoData.seo_score)
                )}>
                  <span className={clsx("text-3xl font-semibold", getScoreColor(seoData.seo_score))}>
                    {seoData.seo_score}
                  </span>
                  <span className="text-xs text-foreground-muted">SEO Score</span>
                </div>
              </div>

              {/* Estimated Value */}
              {seoData.estimated_value && (
                <div className="mt-4 p-4 bg-accent/10 border border-accent/20 rounded-xl">
                  <p className="text-sm text-foreground-muted mb-1">Estimated SEO Value</p>
                  <p className="text-2xl font-semibold text-accent">
                    ${seoData.estimated_value.toLocaleString()}
                  </p>
                  <p className="text-xs text-foreground-subtle mt-1">
                    Based on domain authority & backlink profile
                  </p>
                </div>
              )}
            </div>

            {/* Metrics Grid */}
            <div className="grid grid-cols-2 lg:grid-cols-5 gap-4">
              <StatCard
                title="Domain Authority"
                value={seoData.metrics.domain_authority || 0}
                icon={TrendingUp}
                subtitle="/100"
              />
              <StatCard
                title="Page Authority"
                value={seoData.metrics.page_authority || 0}
                icon={Globe}
                subtitle="/100"
              />
              <StatCard
                title="Backlinks"
                value={formatNumber(seoData.metrics.total_backlinks)}
                icon={Link2}
              />
              <StatCard
                title="Referring Domains"
                value={formatNumber(seoData.metrics.referring_domains)}
                icon={ExternalLink}
              />
              <StatCard
                title="Spam Score"
                value={seoData.metrics.spam_score || 0}
                icon={Shield}
                subtitle={seoData.metrics.spam_score && seoData.metrics.spam_score > 30 ? '⚠️ High' : '✓ Low'}
              />
            </div>

            {/* Notable Links */}
            <div className="p-6 bg-background-secondary/30 border border-border rounded-2xl">
              <h3 className="text-lg font-medium text-foreground mb-4">Notable Backlinks</h3>
              <div className="grid sm:grid-cols-4 gap-4">
                <div className={clsx(
                  "p-4 rounded-xl border flex items-center gap-3",
                  seoData.notable_links.has_wikipedia
                    ? "bg-accent/10 border-accent/30"
                    : "bg-foreground/5 border-border"
                )}>
                  <BookOpen className={clsx(
                    "w-6 h-6",
                    seoData.notable_links.has_wikipedia ? "text-accent" : "text-foreground-subtle"
                  )} />
                  <div>
                    <p className="text-sm font-medium text-foreground">Wikipedia</p>
                    <p className="text-xs text-foreground-muted">
                      {seoData.notable_links.has_wikipedia ? '✓ Found' : 'Not found'}
                    </p>
                  </div>
                </div>

                <div className={clsx(
                  "p-4 rounded-xl border flex items-center gap-3",
                  seoData.notable_links.has_gov
                    ? "bg-accent/10 border-accent/30"
                    : "bg-foreground/5 border-border"
                )}>
                  <Building className={clsx(
                    "w-6 h-6",
                    seoData.notable_links.has_gov ? "text-accent" : "text-foreground-subtle"
                  )} />
                  <div>
                    <p className="text-sm font-medium text-foreground">.gov Links</p>
                    <p className="text-xs text-foreground-muted">
                      {seoData.notable_links.has_gov ? '✓ Found' : 'Not found'}
                    </p>
                  </div>
                </div>

                <div className={clsx(
                  "p-4 rounded-xl border flex items-center gap-3",
                  seoData.notable_links.has_edu
                    ? "bg-accent/10 border-accent/30"
                    : "bg-foreground/5 border-border"
                )}>
                  <GraduationCap className={clsx(
                    "w-6 h-6",
                    seoData.notable_links.has_edu ? "text-accent" : "text-foreground-subtle"
                  )} />
                  <div>
                    <p className="text-sm font-medium text-foreground">.edu Links</p>
                    <p className="text-xs text-foreground-muted">
                      {seoData.notable_links.has_edu ? '✓ Found' : 'Not found'}
                    </p>
                  </div>
                </div>

                <div className={clsx(
                  "p-4 rounded-xl border flex items-center gap-3",
                  seoData.notable_links.has_news
                    ? "bg-accent/10 border-accent/30"
                    : "bg-foreground/5 border-border"
                )}>
                  <Newspaper className={clsx(
                    "w-6 h-6",
                    seoData.notable_links.has_news ? "text-accent" : "text-foreground-subtle"
                  )} />
                  <div>
                    <p className="text-sm font-medium text-foreground">News Sites</p>
                    <p className="text-xs text-foreground-muted">
                      {seoData.notable_links.has_news ? '✓ Found' : 'Not found'}
                    </p>
                  </div>
                </div>
              </div>

              {/* Notable Domains List */}
              {seoData.notable_links.notable_domains.length > 0 && (
                <div className="mt-4">
                  <p className="text-sm text-foreground-muted mb-2">High-authority referring domains:</p>
                  <div className="flex flex-wrap gap-2">
                    {seoData.notable_links.notable_domains.map((d) => (
                      <span key={d} className="px-3 py-1 bg-accent/10 text-accent text-sm rounded-full">
                        {d}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Top Backlinks */}
            {seoData.top_backlinks.length > 0 && (
              <div className="p-6 bg-background-secondary/30 border border-border rounded-2xl">
                <h3 className="text-lg font-medium text-foreground mb-4">Top Backlinks</h3>
                <div className="space-y-2">
                  {seoData.top_backlinks.map((link, idx) => (
                    <div
                      key={idx}
                      className="flex items-center justify-between p-3 bg-background rounded-xl border border-border/50"
                    >
                      <div className="flex items-center gap-3">
                        <div className={clsx(
                          "w-8 h-8 rounded-lg flex items-center justify-center text-sm font-medium",
                          link.authority >= 60 ? "bg-accent/10 text-accent" :
                          link.authority >= 40 ? "bg-amber-500/10 text-amber-400" :
                          "bg-foreground/5 text-foreground-muted"
                        )}>
                          {link.authority}
                        </div>
                        <div>
                          <p className="font-mono text-sm text-foreground">{link.domain}</p>
                          {link.page && (
                            <p className="text-xs text-foreground-muted truncate max-w-xs">{link.page}</p>
                          )}
                        </div>
                      </div>
                      <a
                        href={`https://${link.domain}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="p-2 text-foreground-subtle hover:text-accent transition-colors"
                      >
                        <ExternalLink className="w-4 h-4" />
                      </a>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Data Source Note */}
            {seoData.is_estimated && (
              <div className="p-4 bg-amber-500/10 border border-amber-500/20 rounded-xl">
                <p className="text-sm text-amber-400">
                  <AlertCircle className="w-4 h-4 inline mr-2" />
                  This data is estimated based on domain characteristics. 
                  For live Moz data, configure MOZ_ACCESS_ID and MOZ_SECRET_KEY in the backend.
                </p>
              </div>
            )}
          </div>
        )}

        {/* Empty State */}
        {!seoData && !loading && !error && (
          <div className="text-center py-16">
            <Sparkles className="w-16 h-16 text-foreground-subtle mx-auto mb-6" />
            <h2 className="text-xl font-medium text-foreground mb-2">SEO Juice Detector</h2>
            <p className="text-foreground-muted max-w-md mx-auto">
              Enter a domain above to analyze its backlink profile, domain authority, 
              and find hidden SEO value that others miss.
            </p>
          </div>
        )}
      </PageContainer>
    </CommandCenterLayout>
  )
}

