import { useEffect, useState } from 'react'
import { Link } from 'react-router'
import { useAuth } from '~/lib/auth-context'
import { SITE_NAME } from '~/lib/site-config'
import { listPublications, migratePipupEntries, type Publication } from '~/lib/api-client'
import CreatePublication from '~/components/CreatePublication'
import CenteredMessage from '~/components/CenteredMessage'
import PageLayout from '~/components/PageLayout'
import Spinner from '~/components/Spinner'

export function meta() {
  return [{ title: `Settings — ${SITE_NAME}` }]
}

export default function Settings() {
  const { session, loading } = useAuth()

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <Spinner />
      </div>
    )
  }

  if (!session) {
    return <CenteredMessage message="Sign in to access settings." action={{ label: 'Sign in', to: '/' }} />
  }

  return (
    <PageLayout spacing="10">
      <h1 className="font-display text-2xl font-semibold text-stone-900 dark:text-white">Settings</h1>
      <MigrateSection session={session} />
      <footer className="pt-4 border-t border-stone-200 dark:border-stone-800 flex gap-4 text-sm text-stone-400 dark:text-stone-500">
        <Link to="/tos" className="hover:text-stone-700 dark:hover:text-stone-300 transition-colors">Terms of Service</Link>
        <Link to="/privacy" className="hover:text-stone-700 dark:hover:text-stone-300 transition-colors">Privacy Policy</Link>
      </footer>
    </PageLayout>
  )
}

function MigrateSection({ session }: { session: NonNullable<ReturnType<typeof useAuth>['session']> }) {
  const [publications, setPublications] = useState<Publication[] | null>(null)
  const [status, setStatus] = useState<'idle' | 'running' | 'done' | 'error'>('idle')
  const [result, setResult] = useState<{ migrated: number; skipped: number; errors: Array<{ title: string; reason: string }> } | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    listPublications(session)
      .then(setPublications)
      .catch(() => setPublications([]))
  }, [session])

  // Find the publication that belongs to this app's domain
  const matchingPub = publications?.find((pub) => {
    try { return new URL(pub.url).origin === window.location.origin } catch { return false }
  }) ?? null

  async function handleMigrate() {
    if (!matchingPub) return
    setStatus('running')
    setError(null)
    setResult(null)
    try {
      const r = await migratePipupEntries(session, matchingPub.atUri)
      setResult(r)
      setStatus('done')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Migration failed')
      setStatus('error')
    }
  }

  return (
    <section className="space-y-4">
      <div className="border-b border-stone-200 dark:border-stone-800 pb-3">
        <h2 className="font-display text-lg font-semibold text-stone-900 dark:text-white">
          Migrate old blog entries
        </h2>
        <p className="text-sm text-stone-500 dark:text-stone-400 mt-1">
          Convert old PiPup records
          on your PDS to <code className="text-xs bg-stone-100 dark:bg-stone-800 px-1 py-0.5 rounded">site.standard.document</code> records.
          Original records are not deleted.
        </p>
      </div>

      {publications === null ? (
        <div className="flex items-center gap-2 text-sm text-stone-500 dark:text-stone-400">
          <Spinner size="xs" muted />
          Loading publications…
        </div>
      ) : matchingPub ? (
        <div className="space-y-4">
          <div className="rounded-lg border border-stone-200 dark:border-stone-700/80 px-4 py-3 bg-white dark:bg-stone-900/40 flex items-center justify-between gap-4">
            <div className="min-w-0">
              <p className="text-sm font-medium text-stone-900 dark:text-white truncate">{matchingPub.name}</p>
              <p className="text-sm text-stone-400 dark:text-stone-500 truncate mt-0.5">{new URL(matchingPub.url).host}</p>
            </div>
            <span className="shrink-0 text-sm text-stone-400 dark:text-stone-500">Target publication</span>
          </div>

          {status === 'idle' && (
            <button
              onClick={handleMigrate}
              className="rounded-lg bg-stone-900 dark:bg-stone-100 hover:bg-stone-700 dark:hover:bg-stone-200 px-4 py-2.5 text-sm font-semibold text-white dark:text-stone-900 transition-colors"
            >
              Migrate entries
            </button>
          )}

          {status === 'running' && (
            <div className="flex items-center gap-2 text-sm text-stone-500 dark:text-stone-400">
              <Spinner size="xs" muted />
              Migrating…
            </div>
          )}

          {status === 'done' && result && (
            <div className="space-y-3">
              <p className="text-sm text-stone-700 dark:text-stone-300">
                Migration complete —{' '}
                <span className="font-medium">{result.migrated} migrated</span>
                {result.skipped > 0 && `, ${result.skipped} skipped (no title)`}
                {result.errors.length > 0 && (
                  <span className="text-red-500">, {result.errors.length} errors</span>
                )}
              </p>
              {result.migrated === 0 && result.skipped === 0 && result.errors.length === 0 && (
                <p className="text-sm text-stone-500 dark:text-stone-400">No old entries found.</p>
              )}
              {result.errors.length > 0 && (
                <ul className="space-y-1.5">
                  {result.errors.map((e, i) => (
                    <li key={i} className="text-sm">
                      <span className="font-medium text-stone-700 dark:text-stone-300">{e.title}</span>
                      <span className="text-red-500 ml-2">{e.reason}</span>
                    </li>
                  ))}
                </ul>
              )}
              <button
                onClick={() => { setStatus('idle'); setResult(null) }}
                className="text-sm text-stone-400 hover:text-stone-700 dark:hover:text-stone-300 underline transition-colors"
              >
                Run again
              </button>
            </div>
          )}

          {status === 'error' && (
            <div className="space-y-2">
              <p className="text-sm text-red-500">{error}</p>
              <button
                onClick={() => { setStatus('idle'); setError(null) }}
                className="text-sm text-stone-400 hover:text-stone-700 dark:hover:text-stone-300 underline transition-colors"
              >
                Try again
              </button>
            </div>
          )}
        </div>
      ) : (
        <div className="space-y-4">
          <p className="text-sm text-stone-500 dark:text-stone-400">
            You need a publication for <span className="font-medium text-stone-700 dark:text-stone-300">{window.location.host}</span> before migrating.
          </p>
          <CreatePublication
            session={session}
            onCreated={(pub) => setPublications((prev) => [...(prev ?? []), pub])}
          />
        </div>
      )}
    </section>
  )
}
