"use client";

import Image from "next/image";
import Link from "next/link";
import { useActionState } from "react";
import { savePostAction } from "@/app/admin/actions";
import type { ActionState, PostFormValues } from "@/lib/form";

export function PostForm({
  initial,
  categories,
  mode,
}: {
  initial: PostFormValues;
  categories: string[];
  mode: "new" | "edit";
}) {
  const [state, formAction, pending] = useActionState<ActionState, FormData>(
    savePostAction,
    null,
  );

  return (
    <form action={formAction} className="space-y-6">
      <input type="hidden" name="originalSlug" value={mode === "edit" ? initial.slug : ""} />

      {state?.error ? (
        <p
          role="alert"
          className="rounded-xl border border-coral/40 bg-coral-soft px-4 py-3 text-sm font-medium text-coral-dark"
        >
          {state.error}
        </p>
      ) : null}

      <div className="grid gap-6 lg:grid-cols-[1.6fr_1fr]">
        {/* Main column */}
        <div className="space-y-6">
          <section className="card-soft space-y-5 p-7">
            <h2 className="display-3">Content</h2>
            <div>
              <label htmlFor="title" className="field-label">
                Title *
              </label>
              <input
                id="title"
                name="title"
                type="text"
                required
                defaultValue={initial.title}
                placeholder="Warm Minimalism: Less, But Softer"
                className="field-input"
              />
            </div>
            <div>
              <label htmlFor="slug" className="field-label">
                URL slug
              </label>
              <input
                id="slug"
                name="slug"
                type="text"
                defaultValue={initial.slug}
                placeholder="auto-generated from the title"
                className="field-input"
              />
            </div>
            <div>
              <label htmlFor="excerpt" className="field-label">
                Excerpt (used in listings and as the SEO fallback)
              </label>
              <textarea
                id="excerpt"
                name="excerpt"
                rows={3}
                defaultValue={initial.excerpt}
                placeholder="A short, compelling summary of the article…"
                className="field-textarea resize-y"
              />
            </div>
            <div>
              <label htmlFor="content" className="field-label">
                Article body * (supports ## headings, - bullets, **bold**)
              </label>
              <textarea
                id="content"
                name="content"
                rows={16}
                required
                defaultValue={initial.content}
                placeholder={"Write your article…\n\n## A section heading\n\nParagraph text with **bold** and *italic*."}
                className="field-textarea resize-y font-mono text-[0.9rem] leading-relaxed"
              />
            </div>
          </section>

          {/* SEO */}
          <section className="card-soft space-y-5 p-7">
            <div>
              <h2 className="display-3">SEO</h2>
              <p className="mt-1 text-sm text-ink-mute">
                Controls the search result preview and social sharing card.
              </p>
            </div>
            <div>
              <label htmlFor="metaTitle" className="field-label">
                Meta title
              </label>
              <input
                id="metaTitle"
                name="metaTitle"
                type="text"
                maxLength={70}
                defaultValue={initial.metaTitle}
                placeholder={initial.title || "Falls back to the post title"}
                className="field-input"
              />
            </div>
            <div>
              <label htmlFor="metaDescription" className="field-label">
                Meta description
              </label>
              <textarea
                id="metaDescription"
                name="metaDescription"
                rows={3}
                maxLength={180}
                defaultValue={initial.metaDescription}
                placeholder="Falls back to the excerpt"
                className="field-textarea resize-y"
              />
            </div>
            <div className="grid gap-5 sm:grid-cols-2">
              <div>
                <label htmlFor="keywords" className="field-label">
                  Keywords (comma separated)
                </label>
                <input
                  id="keywords"
                  name="keywords"
                  type="text"
                  defaultValue={initial.keywords}
                  placeholder="interior design, small rooms"
                  className="field-input"
                />
              </div>
              <div>
                <label htmlFor="ogImage" className="field-label">
                  Social share image URL
                </label>
                <input
                  id="ogImage"
                  name="ogImage"
                  type="text"
                  defaultValue={initial.ogImage}
                  placeholder="https://… (falls back to the cover image)"
                  className="field-input"
                />
              </div>
            </div>
            <label className="flex items-center gap-3 text-sm text-ink-soft">
              <input
                type="checkbox"
                name="noindex"
                defaultChecked={initial.noindex}
                className="h-4 w-4 accent-[#0f7b7b]"
              />
              Hide from search engines (noindex)
            </label>
          </section>
        </div>

        {/* Side column */}
        <div className="space-y-6">
          <section className="card-soft space-y-5 p-7">
            <h2 className="display-3">Publish</h2>
            <label className="flex items-center gap-3 text-sm font-medium text-ink">
              <input
                type="checkbox"
                name="published"
                defaultChecked={initial.published}
                className="h-4 w-4 accent-[#0f7b7b]"
              />
              Published (visible on the website)
            </label>
            <div className="grid gap-4">
              <div>
                <label htmlFor="date" className="field-label">
                  Date
                </label>
                <input
                  id="date"
                  name="date"
                  type="date"
                  defaultValue={initial.date}
                  className="field-input"
                />
              </div>
              <div>
                <label htmlFor="category" className="field-label">
                  Category
                </label>
                <input
                  id="category"
                  name="category"
                  type="text"
                  list="category-options"
                  defaultValue={initial.category}
                  className="field-input"
                />
                <datalist id="category-options">
                  {categories.map((c) => (
                    <option key={c} value={c} />
                  ))}
                </datalist>
              </div>
              <div>
                <label htmlFor="readTime" className="field-label">
                  Read time
                </label>
                <input
                  id="readTime"
                  name="readTime"
                  type="text"
                  defaultValue={initial.readTime}
                  placeholder="5 min"
                  className="field-input"
                />
              </div>
            </div>
          </section>

          <section className="card-soft space-y-5 p-7">
            <h2 className="display-3">Cover image</h2>
            {initial.coverImage ? (
              <div className="relative aspect-[4/3] overflow-hidden rounded-xl border border-linen">
                <Image
                  src={initial.coverImage}
                  alt="Current cover"
                  fill
                  unoptimized
                  className="object-cover"
                />
              </div>
            ) : (
              <p className="rounded-xl bg-mint px-4 py-3 text-sm text-ink-mute">
                No cover image yet — the listing will use a stock interior photo.
              </p>
            )}
            <div>
              <label htmlFor="coverFile" className="field-label">
                Upload image (JPG, PNG, WebP, AVIF, GIF — max 5 MB)
              </label>
              <input
                id="coverFile"
                name="coverFile"
                type="file"
                accept="image/jpeg,image/png,image/webp,image/avif,image/gif"
                className="block w-full text-sm text-ink-soft file:mr-4 file:rounded-full file:border-0 file:bg-teal file:px-4 file:py-2 file:text-xs file:font-semibold file:text-white hover:file:bg-teal-dark"
              />
            </div>
            <div>
              <label htmlFor="coverImage" className="field-label">
                …or paste an image URL
              </label>
              <input
                id="coverImage"
                name="coverImage"
                type="text"
                defaultValue={initial.coverImage}
                placeholder="https://…"
                className="field-input"
              />
            </div>
          </section>
        </div>
      </div>

      <div className="flex flex-wrap items-center gap-4">
        <button
          type="submit"
          disabled={pending}
          className="btn btn-teal disabled:cursor-not-allowed disabled:opacity-60"
        >
          {pending ? "Saving…" : mode === "new" ? "Create post" : "Save changes"}
        </button>
        <Link href="/admin/posts" className="btn btn-outline">
          Cancel
        </Link>
      </div>
    </form>
  );
}
