'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-green-600' : score >= 60 ? 'text-amber-500' : 'text-red-500'
  const bg = score >= 80 ? 'bg-green-50' : score >= 60 ? 'bg-amber-50' : 'bg-red-50'
  return (
    <span
      className={`inline-flex h-9 w-9 items-center justify-center rounded-full text-sm font-semibold ${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="rounded-lg border border-gray-200 bg-white">
      <div className="flex items-center justify-between border-b border-gray-200 p-4">
        <div className="flex items-center gap-2">
          <Search className="h-4 w-4 text-gray-500" />
          <h2 className="text-sm font-semibold text-gray-900">SEO Performance</h2>
        </div>
        {totalIssues > 0 && (
          <span className="text-xs text-gray-500">
            {totalIssues} issue{totalIssues !== 1 ? 's' : ''} found
          </span>
        )}
      </div>

      <div className="grid grid-cols-1 divide-y divide-gray-200 lg:grid-cols-12 lg:divide-x lg:divide-y-0">
        <div className="p-4 lg:col-span-7">
          <h3 className="mb-3 text-sm font-medium text-gray-700">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="truncate text-sm font-medium text-gray-900">{item.title}</p>
                  <p className="text-xs text-gray-500 capitalize">{item.collection}</p>
                </div>
                <ScoreBadge score={item.score} />
              </div>
            ))}
            {visible.length === 0 && (
              <p className="py-4 text-center text-sm text-gray-400">No published content yet</p>
            )}
          </div>
          {topContent.length > perPage && (
            <div className="mt-3 flex items-center justify-between border-t border-gray-100 pt-3 text-xs text-gray-500">
              <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="rounded p-1 hover:bg-gray-100 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="rounded p-1 hover:bg-gray-100 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="mb-3 text-sm font-medium text-gray-700">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-sm text-gray-700">Missing meta descriptions</span>
              </div>
              <span className="text-sm font-semibold text-gray-900">
                {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-sm text-gray-700">Broken internal links</span>
              </div>
              <span className="text-sm font-semibold text-gray-900">
                {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-sm text-gray-700">Missing alt text</span>
              </div>
              <span className="text-sm font-semibold text-gray-900">{issues.missingAltText}</span>
            </div>
          </div>
          {totalIssues > 0 && (
            <button
              onClick={() => onNavigate?.('/seo')}
              className="mt-4 text-sm font-medium text-blue-600 hover:text-blue-700"
            >
              View All Issues
            </button>
          )}
        </div>
      </div>
    </div>
  )
}
