'use client'

/**
 * Content SEO tab — pages/posts list with per-item SEO editing in an inline
 * 380px inspector pane (design split-pane pattern; previously an overlay
 * drawer). Row click toggles the pane; deep links
 * (`?tab=content&entityType=…&entityId=…`) open it on mount.
 */
import { useMemo, useState } from 'react'
import { Search, FileText } 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 { InspectorPane, SplitPaneLayout, SplitPaneList } from '../../components/ui/InspectorPane.js'
import { SeoEditorPane } from '../../components/seo/SeoEditorPane.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-[var(--bdr)] bg-input-background py-2 pl-9 pr-3 text-base text-[var(--txt)] placeholder:text-[var(--sub)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--ring)]'

type SeoEntityType = 'page' | 'post'
type Selection = { type: SeoEntityType; id: string } | null

function parseEntityType(value: string | null | undefined): SeoEntityType | null {
  return value === 'page' || value === 'post' ? value : null
}

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 [selection, setSelection] = useState<Selection>(() => {
    const type = parseEntityType(initialEntityType)
    return type && initialEntityId ? { type, id: initialEntityId } : null
  })

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

  const toggleRow = (type: SeoEntityType, id: string) => {
    setSelection((prev) => (prev?.type === type && prev.id === id ? null : { type, id }))
  }

  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="pointer-events-none absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-[var(--sub)]"
            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={`rounded-md px-3 py-1.5 text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none ${
                filter === f.id
                  ? 'bg-primary text-primary-foreground'
                  : 'text-[var(--sub)] hover:bg-[var(--acc-l)] hover:text-[var(--txt)]'
              }`}
            >
              {f.label}
            </button>
          ))}
        </div>
      </div>

      {/* The SEO page scrolls (tabbed layout), so the split area takes a
          viewport-derived height to keep the pane's body/footer independently
          scrollable, matching the design's fixed-height content region. */}
      <SplitPaneLayout className="h-[calc(100vh-280px)] min-h-[440px]">
        <SplitPaneList>
          <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 min-w-[640px] text-sm" aria-label="Content SEO">
                  <thead>
                    <tr className="border-b border-[var(--bdr)] text-left text-[var(--sub)]">
                      <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 text-right font-medium">Score</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-[var(--bdr)]">
                    {rows.map((r) => {
                      const isSelected =
                        selection?.type === r.entityType && selection.id === r.entityId
                      return (
                        <tr
                          key={`${r.entityType}-${r.entityId}`}
                          className={`cursor-pointer transition-colors ${
                            isSelected ? 'bg-[var(--acc-l)]' : 'hover:bg-[var(--acc-l)]'
                          }`}
                          onClick={() => toggleRow(r.entityType, r.entityId)}
                        >
                          <td className="py-2.5 pr-4">
                            <button
                              type="button"
                              onClick={(e) => {
                                e.stopPropagation()
                                toggleRow(r.entityType, r.entityId)
                              }}
                              aria-expanded={isSelected}
                              className="text-left"
                            >
                              <span className="block font-medium text-[var(--txt)]">{r.title}</span>
                              <span className="block truncate text-[var(--sub)]">{r.url}</span>
                            </button>
                          </td>
                          <td className="py-2.5 pr-4 capitalize">
                            <span className="text-[var(--sub)]">{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 text-right">
                            <ScorePill score={r.seoScore} />
                          </td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </SectionCard>
        </SplitPaneList>

        <InspectorPane open={selection !== null} width={380} aria-label="SEO editor">
          {selection && (
            <SeoEditorPane
              key={`${selection.type}-${selection.id}`}
              entityType={selection.type}
              entityId={selection.id}
              onClose={() => setSelection(null)}
              onSaved={refetch}
            />
          )}
        </InspectorPane>
      </SplitPaneLayout>
    </div>
  )
}
