'use client'

import { useEffect, useState } from 'react'
import { Link2, Loader2, Sparkles } from 'lucide-react'
import { fetchLinkSuggestions, type LinkSuggestion } from '../../lib/seo-service.js'

export function SeoLinkingSection({
  entityType,
  entityId,
  internalLinks,
  externalLinks,
  internalLinkOk,
  externalLinkOk,
}: {
  entityType: 'page' | 'post'
  entityId: string | null
  internalLinks: number
  externalLinks: number
  internalLinkOk: boolean
  externalLinkOk: boolean
}) {
  const [loading, setLoading] = useState(false)
  const [suggestions, setSuggestions] = useState<LinkSuggestion[]>([])
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!entityId) {
      setSuggestions([])
      setError(null)
      return
    }
    let alive = true
    setLoading(true)
    setError(null)
    fetchLinkSuggestions({ targetEntityType: entityType, targetEntityId: entityId, limit: 5 })
      .then((res) => {
        if (!alive) return
        if (res.error) {
          setError(res.error)
          setSuggestions([])
          return
        }
        setSuggestions(res.data?.suggestions ?? [])
      })
      .finally(() => alive && setLoading(false))
    return () => {
      alive = false
    }
  }, [entityType, entityId])

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-3">
        <LinkCountCard
          label="Internal links"
          count={internalLinks}
          ok={internalLinkOk}
          hint={
            internalLinkOk
              ? 'Links to other pages on your site.'
              : 'Add links to related content — aim for at least one.'
          }
        />
        <LinkCountCard
          label="Outbound links"
          count={externalLinks}
          ok={externalLinkOk}
          hint={
            externalLinkOk
              ? 'Links to external sources.'
              : 'Consider linking to authoritative external sources.'
          }
        />
      </div>

      {!entityId ? (
        <p className="rounded-[7px] border border-[var(--bdr)] bg-[var(--bg)] p-3 text-[11.5px] text-[var(--sub)]">
          Save a draft first to load AI link opportunities for this page.
        </p>
      ) : loading ? (
        <div className="flex items-center gap-2 text-[12px] text-[var(--muted)]">
          <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
          Finding link opportunities…
        </div>
      ) : error ? (
        <p className="text-[11.5px] text-[var(--err)]">{error}</p>
      ) : suggestions.length > 0 ? (
        <div>
          <div className="mb-2 flex items-center gap-1.5 text-[12px] font-medium text-[var(--txt)]">
            <Sparkles className="h-3.5 w-3.5 text-[var(--acc)]" aria-hidden />
            Link opportunities
          </div>
          <ul className="space-y-2">
            {suggestions.map((s) => (
              <li
                key={`${s.sourceEntityId}-${s.anchorText}`}
                className="rounded-[7px] border border-[var(--bdr)] bg-[var(--card)] p-2.5"
              >
                <div className="text-[12.5px] font-medium text-[var(--txt)]">{s.sourceTitle}</div>
                <p className="mt-0.5 text-[11px] text-[var(--muted)]">{s.sourceUrl}</p>
                <p className="mt-1 text-[11.5px] text-[var(--sub)]">
                  Suggested anchor: <span className="text-[var(--txt)]">{s.anchorText}</span>
                </p>
                {s.excerpt && (
                  <p className="mt-1 line-clamp-2 text-[11px] text-[var(--muted)]">{s.excerpt}</p>
                )}
              </li>
            ))}
          </ul>
        </div>
      ) : (
        <p className="text-[11.5px] text-[var(--sub)]">
          No inbound link suggestions yet. Run the site link index from SEO → Links to improve AI
          recommendations.
        </p>
      )}

      <div className="flex items-start gap-2 rounded-[7px] border border-[var(--bdr)] bg-[var(--bg)] p-2.5 text-[11px] text-[var(--sub)]">
        <Link2 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-[var(--acc)]" aria-hidden />
        <span>
          Best practice: mix internal links (site structure + crawl paths) with selective outbound
          links (trust signals). We flag counts here; apply links in the content editor.
        </span>
      </div>
    </div>
  )
}

function LinkCountCard({
  label,
  count,
  ok,
  hint,
}: {
  label: string
  count: number
  ok: boolean
  hint: string
}) {
  return (
    <div className="rounded-[7px] border border-[var(--bdr)] bg-[var(--card)] p-3">
      <div className="flex items-center justify-between gap-2">
        <span className="text-[11.5px] font-medium text-[var(--sub)]">{label}</span>
        <span className={`text-lg font-medium ${ok ? 'text-[var(--suc)]' : 'text-[var(--warn)]'}`}>
          {count}
        </span>
      </div>
      <p className="mt-1 text-[10.5px] text-[var(--muted)]">{hint}</p>
    </div>
  )
}
