'use client'

import { useMemo, useState } from 'react'
import { Search, FileText, Pencil } from 'lucide-react'
import {
  fetchSeoContentRecords,
  applyContentSeoQuery,
  type ContentSeoFilter,
} from '../../lib/seo-service.js'
import {
  SectionCard,
  SeoLoading,
  SeoEmptyState,
  SeoErrorState,
  ScorePill,
  SeoStatusBadge,
} from '../../components/seo/primitives.js'
import { SeoEditorDrawer } from '../../components/seo/SeoEditorDrawer.js'
import { useSeoResource } from './useSeoResource.js'

const FILTERS: { id: ContentSeoFilter; label: string }[] = [
  { id: 'all', label: 'All' },
  { id: 'pages', label: 'Pages' },
  { id: 'posts', label: 'Posts' },
]

const inputCls =
  'w-full rounded-md border border-border bg-input-background py-2 pl-9 pr-3 text-base text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'

export function ContentTab({
  initialEntityType,
  initialEntityId,
}: {
  initialEntityType?: string | null
  initialEntityId?: string | null
}) {
  const { data, loading, error, refetch } = useSeoResource(fetchSeoContentRecords, [])
  const [search, setSearch] = useState('')
  const [filter, setFilter] = useState<ContentSeoFilter>('all')
  const [editor, setEditor] = useState<{ type: string; id: string } | null>(
    initialEntityType && initialEntityId ? { type: initialEntityType, id: initialEntityId } : null,
  )

  const rows = useMemo(
    () => applyContentSeoQuery(data ?? [], { search, filter }),
    [data, search, filter],
  )

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="relative max-w-sm flex-1">
          <Search
            className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2"
            aria-hidden
          />
          <input
            className={inputCls}
            placeholder="Search content…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            aria-label="Search content"
          />
        </div>
        <div className="flex gap-1" role="group" aria-label="Content type filter">
          {FILTERS.map((f) => (
            <button
              key={f.id}
              type="button"
              aria-pressed={filter === f.id}
              onClick={() => setFilter(f.id)}
              className={`focus-visible:ring-ring rounded-md px-3 py-1.5 text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:outline-none ${
                filter === f.id
                  ? 'bg-primary text-primary-foreground'
                  : 'text-muted-foreground hover:bg-accent hover:text-foreground'
              }`}
            >
              {f.label}
            </button>
          ))}
        </div>
      </div>

      <SectionCard>
        {loading ? (
          <SeoLoading label="Loading content…" />
        ) : error ? (
          <SeoErrorState message={error} onRetry={refetch} />
        ) : rows.length === 0 ? (
          <SeoEmptyState
            icon={<FileText size={24} />}
            title={search || filter !== 'all' ? 'No matching content' : 'No content yet'}
            description={
              search || filter !== 'all'
                ? 'Try adjusting your search or filter.'
                : 'Publish pages or posts to manage their SEO here.'
            }
          />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm" aria-label="Content SEO">
              <thead>
                <tr className="text-muted-foreground border-border border-b text-left">
                  <th className="py-2 pr-4 font-medium">Title</th>
                  <th className="py-2 pr-4 font-medium">Type</th>
                  <th className="py-2 pr-4 font-medium">Meta</th>
                  <th className="py-2 pr-4 text-right font-medium">Score</th>
                  <th className="py-2 text-right font-medium">
                    <span className="sr-only">Actions</span>
                  </th>
                </tr>
              </thead>
              <tbody className="divide-border divide-y">
                {rows.map((r) => (
                  <tr key={`${r.entityType}-${r.entityId}`} className="hover:bg-accent/40">
                    <td className="py-2.5 pr-4">
                      <span className="text-foreground block font-medium">{r.title}</span>
                      <span className="text-muted-foreground block truncate">{r.url}</span>
                    </td>
                    <td className="py-2.5 pr-4 capitalize">
                      <span className="text-muted-foreground">{r.entityType}</span>
                    </td>
                    <td className="py-2.5 pr-4">
                      <span className="flex flex-wrap gap-1.5">
                        <SeoStatusBadge
                          label={r.metaTitle ? 'Title' : 'No title'}
                          tone={r.metaTitle ? 'good' : 'critical'}
                        />
                        <SeoStatusBadge
                          label={r.metaDescription ? 'Desc' : 'No desc'}
                          tone={r.metaDescription ? 'good' : 'critical'}
                        />
                        {r.noindex && <SeoStatusBadge label="No-index" tone="fair" />}
                      </span>
                    </td>
                    <td className="py-2.5 pr-4 text-right">
                      <ScorePill score={r.seoScore} />
                    </td>
                    <td className="py-2.5 text-right">
                      <button
                        onClick={() => setEditor({ type: r.entityType, id: r.entityId })}
                        className="text-primary hover:bg-accent focus-visible:ring-ring inline-flex items-center gap-1 rounded-md px-2 py-1 text-sm focus-visible:ring-2 focus-visible:outline-none"
                      >
                        <Pencil className="h-3.5 w-3.5" aria-hidden /> Edit
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>

      <SeoEditorDrawer
        open={editor !== null}
        onOpenChange={(o) => !o && setEditor(null)}
        entityType={editor?.type ?? null}
        entityId={editor?.id ?? null}
        onSaved={refetch}
      />
    </div>
  )
}
