'use client'

import { useEffect, useState } from 'react'
import { ArrowRight, ArrowLeft } from 'lucide-react'
import { fetchPostTypes, type PostType } from '../../lib/posts-service.js'
import { paletteFor } from '../../components/posts/badges.js'
import { resolvePostTypeIcon } from '../../components/posts/icons.js'

/**
 * Type-picker landing page for "+ New Post".
 *
 * Behavior by number of configured post types:
 *   - exactly one  → skip the picker and forward straight to that type's
 *     new-post editor (a one-card chooser adds nothing but a flash)
 *   - two or more  → show the chooser cards
 *   - zero         → show a "no post types configured" setup hint
 *
 * Picking a card navigates to the section-based Post editor's new-post
 * route (`/posts/<slug>/new`), which seeds the post from that type's
 * template so the author starts from the type's default layout.
 */

export function NewPostPicker({ onNavigate }: { onNavigate: (path: string) => void }) {
  const [types, setTypes] = useState<PostType[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    fetchPostTypes()
      .then((res) => {
        if (cancelled) return
        // With a single Post Type there's nothing to choose — forward
        // straight to its editor so the picker doesn't flash a
        // one-card screen.
        if (res.length === 1) {
          onNavigate(`/posts/${res[0]!.slug}/new`)
          return
        }
        setTypes(res)
        setLoading(false)
      })
      .catch((err: unknown) => {
        if (cancelled) return
        setError(err instanceof Error ? err.message : 'Failed to load Post Types')
        setLoading(false)
      })
    return () => {
      cancelled = true
    }
  }, [onNavigate])

  return (
    <div className="mx-auto flex h-full max-w-3xl flex-col gap-6 p-4 sm:p-6">
      <button
        type="button"
        onClick={() => onNavigate('/posts')}
        className="text-muted-foreground hover:text-foreground inline-flex w-fit items-center gap-1.5 text-sm transition-colors"
      >
        <ArrowLeft className="h-3.5 w-3.5" aria-hidden />
        Back to Posts
      </button>

      <div className="flex flex-col gap-1">
        <h1 className="text-foreground text-xl font-medium tracking-tight sm:text-2xl">
          Choose a Post Type
        </h1>
        <p className="text-muted-foreground text-sm">
          Pick which content model you want to use for this post. Each type has its own fields, URL
          base, and SEO defaults.
        </p>
      </div>

      {loading && <Skeleton />}
      {!loading && error && (
        <div className="border-border bg-card rounded-xl border p-8 text-center">
          <div className="text-foreground mb-2 text-sm font-medium">{error}</div>
        </div>
      )}
      {!loading && !error && types.length === 0 && (
        <div className="border-border bg-card rounded-xl border p-8 text-center">
          <div className="text-foreground mb-2 text-sm font-medium">No Post Types configured.</div>
          <p className="text-muted-foreground mb-4 text-sm">
            Add a collection with <code className="font-mono">type: 'post'</code> to your CMS config
            to start creating posts.
          </p>
          <button
            type="button"
            onClick={() => onNavigate('/posts/types/new')}
            className="text-primary text-sm hover:underline"
          >
            View setup instructions →
          </button>
        </div>
      )}
      {!loading && !error && types.length > 0 && (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
          {types.map((t) => {
            const palette = paletteFor(t.accentColor)
            const Icon = resolvePostTypeIcon(t.icon)
            return (
              <button
                key={t.slug}
                type="button"
                onClick={() => onNavigate(`/posts/${t.slug}/new`)}
                className="border-border bg-card focus-visible:ring-ring flex items-center gap-3 rounded-xl border p-4 text-left shadow-sm transition-shadow hover:shadow-md focus:outline-none focus-visible:ring-2"
              >
                <span
                  className={`inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg ${palette.bg} ${palette.text}`}
                >
                  <Icon className="h-5 w-5" aria-hidden />
                </span>
                <span className="min-w-0 flex-1">
                  <span className="text-foreground block text-sm font-medium">
                    {t.singularName}
                  </span>
                  <span className="text-muted-foreground block truncate text-xs">
                    {t.description ?? `New entry in ${t.name}`}
                  </span>
                </span>
                <ArrowRight className="text-muted-foreground h-4 w-4 shrink-0" aria-hidden />
              </button>
            )
          })}
        </div>
      )}
    </div>
  )
}

function Skeleton() {
  return (
    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
      {Array.from({ length: 4 }).map((_, i) => (
        <div
          key={i}
          className="border-border bg-card flex items-center gap-3 rounded-xl border p-4"
        >
          <div className="bg-muted h-10 w-10 animate-pulse rounded-lg" />
          <div className="flex-1">
            <div className="bg-muted mb-2 h-3 w-1/3 animate-pulse rounded" />
            <div className="bg-muted h-2.5 w-2/3 animate-pulse rounded" />
          </div>
        </div>
      ))}
    </div>
  )
}
