'use client'

import {
  Search,
  AlertTriangle,
  FileWarning,
  ImageOff,
  LinkIcon,
  ChevronLeft,
  ChevronRight,
} from 'lucide-react'
import { useState } from 'react'
import { useApiData } from '../lib/useApiData.js'

interface SEOSummary {
  totalPages: number
  issuesSummary: {
    missingMetaDescriptions: number
    brokenInternalLinks: number
    missingAltText: number
  }
  topContent: { id: string; title: string; collection: string; score: number }[]
}

function ScoreBadge({ score }: { score: number }) {
  const color = score >= 80 ? 'text-success' : score >= 60 ? 'text-warning' : 'text-destructive'
  const bg = score >= 80 ? 'bg-success/10' : score >= 60 ? 'bg-warning/10' : 'bg-destructive/10'
  return (
    <span
      className={`inline-flex h-9 w-9 items-center justify-center rounded-full text-sm font-medium ${color} ${bg}`}
    >
      {score}
    </span>
  )
}

export interface SEOPerformanceProps {
  onNavigate?: (path: string) => void
}

export function SEOPerformance({ onNavigate }: SEOPerformanceProps) {
  const { data, loading, error } = useApiData<SEOSummary>('/seo/summary')
  const [page, setPage] = useState(0)
  const perPage = 5

  if (loading || error || !data) return null

  const issues = data.issuesSummary
  const totalIssues =
    issues.missingMetaDescriptions + issues.brokenInternalLinks + issues.missingAltText
  const topContent = data.topContent ?? []
  const totalPages = Math.max(1, Math.ceil(topContent.length / perPage))
  const visible = topContent.slice(page * perPage, (page + 1) * perPage)

  return (
    <div className="border-border bg-card rounded-lg border">
      <div className="border-border flex items-center justify-between border-b p-4">
        <div className="flex items-center gap-2">
          <Search className="text-muted-foreground h-4 w-4" />
          <h2 className="text-foreground text-sm font-medium">SEO Performance</h2>
        </div>
        {totalIssues > 0 && (
          <span className="text-muted-foreground text-xs">
            {totalIssues} issue{totalIssues !== 1 ? 's' : ''} found
          </span>
        )}
      </div>

      <div className="divide-border grid grid-cols-1 divide-y lg:grid-cols-12 lg:divide-x lg:divide-y-0">
        <div className="p-4 lg:col-span-7">
          <h3 className="text-foreground mb-3 text-sm font-medium">Top Performing Content</h3>
          <div className="space-y-2">
            {visible.map((item) => (
              <div key={item.id} className="flex items-center justify-between py-2">
                <div className="mr-3 min-w-0 flex-1">
                  <p className="text-foreground truncate text-sm font-medium">{item.title}</p>
                  <p className="text-muted-foreground text-xs capitalize">{item.collection}</p>
                </div>
                <ScoreBadge score={item.score} />
              </div>
            ))}
            {visible.length === 0 && (
              <p className="text-muted-foreground py-4 text-center text-sm">
                No published content yet
              </p>
            )}
          </div>
          {topContent.length > perPage && (
            <div className="text-muted-foreground mt-3 flex items-center justify-between border-t border-gray-100 pt-3 text-xs">
              <span>
                Showing {page * perPage + 1}-{Math.min((page + 1) * perPage, topContent.length)} of{' '}
                {topContent.length}
              </span>
              <div className="flex items-center gap-1">
                <button
                  onClick={() => setPage(Math.max(0, page - 1))}
                  disabled={page === 0}
                  className="hover:bg-accent rounded p-1 disabled:opacity-30"
                >
                  <ChevronLeft className="h-3.5 w-3.5" />
                </button>
                <span>
                  Page {page + 1} of {totalPages}
                </span>
                <button
                  onClick={() => setPage(Math.min(totalPages - 1, page + 1))}
                  disabled={page >= totalPages - 1}
                  className="hover:bg-accent rounded p-1 disabled:opacity-30"
                >
                  <ChevronRight className="h-3.5 w-3.5" />
                </button>
              </div>
            </div>
          )}
        </div>

        <div className="p-4 lg:col-span-5">
          <h3 className="text-foreground mb-3 text-sm font-medium">SEO Issues</h3>
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <FileWarning className="h-4 w-4 text-red-400" />
                <span className="text-foreground text-sm">Missing meta descriptions</span>
              </div>
              <span className="text-foreground text-sm font-medium">
                {issues.missingMetaDescriptions}
              </span>
            </div>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <LinkIcon className="h-4 w-4 text-red-400" />
                <span className="text-foreground text-sm">Broken internal links</span>
              </div>
              <span className="text-foreground text-sm font-medium">
                {issues.brokenInternalLinks}
              </span>
            </div>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <ImageOff className="h-4 w-4 text-red-400" />
                <span className="text-foreground text-sm">Missing alt text</span>
              </div>
              <span className="text-foreground text-sm font-medium">{issues.missingAltText}</span>
            </div>
          </div>
          {totalIssues > 0 && (
            <button
              onClick={() => onNavigate?.('/seo')}
              className="text-primary hover:text-primary/80 mt-4 text-sm font-medium"
            >
              View All Issues
            </button>
          )}
        </div>
      </div>
    </div>
  )
}
