"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { createPageAction, updatePageAction, deletePageAction } from "./_actions";

export interface PageFormData {
  id?: string;
  slug: string;
  title: string;
  content: string;
  status: string;
  metaTitle: string | null;
  metaDesc: string | null;
  metaKeywords: string | null;
  ogImage: string | null;
  canonicalUrl: string | null;
  noIndex: boolean;
  showInFooter: boolean;
  footerOrder: number;
  isSystem: boolean;
}

const EMPTY: PageFormData = {
  slug: "",
  title: "",
  content: "",
  status: "draft",
  metaTitle: null,
  metaDesc: null,
  metaKeywords: null,
  ogImage: null,
  canonicalUrl: null,
  noIndex: false,
  showInFooter: false,
  footerOrder: 0,
  isSystem: false,
};

export function PageForm({
  mode,
  page = EMPTY,
}: {
  mode: "create" | "edit";
  page?: PageFormData;
}) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const [savedAt, setSavedAt] = useState<Date | null>(null);

  function onSubmit(formData: FormData) {
    setError(null);
    startTransition(async () => {
      const result =
        mode === "create"
          ? await createPageAction(formData)
          : await updatePageAction(page.id!, formData);
      if (result && !result.ok) {
        setError(result.error);
      } else if (result?.ok) {
        setSavedAt(new Date());
        router.refresh();
      }
    });
  }

  function onDelete() {
    if (!page.id) return;
    if (page.isSystem) {
      alert("Không thể xoá trang hệ thống.");
      return;
    }
    if (!confirm(`Xoá vĩnh viễn trang "${page.title}"?`)) return;
    startTransition(async () => {
      const r = await deletePageAction(page.id!);
      if (r && !r.ok) setError(r.error ?? "Xoá thất bại.");
    });
  }

  return (
    <form action={onSubmit} className="space-y-6">
      {error ? (
        <div className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm text-rose-200">
          {error}
        </div>
      ) : null}

      <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-5 space-y-4">
        <div>
          <label className="block text-xs font-medium text-ink-muted uppercase tracking-wider mb-1.5">
            Tiêu đề
          </label>
          <input
            name="title"
            defaultValue={page.title}
            required
            className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-base focus:outline-none focus:border-accent-primary"
          />
        </div>

        <div>
          <label className="block text-xs font-medium text-ink-muted uppercase tracking-wider mb-1.5">
            Slug (đường dẫn /...)
          </label>
          <input
            name="slug"
            defaultValue={page.slug}
            placeholder="auto từ tiêu đề nếu để trống"
            disabled={page.isSystem}
            className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm font-mono focus:outline-none focus:border-accent-primary disabled:opacity-60"
          />
          {page.isSystem ? (
            <p className="mt-1 text-xs text-amber-300">
              Trang hệ thống — slug khoá để tránh vỡ link.
            </p>
          ) : null}
        </div>

        <div>
          <label className="block text-xs font-medium text-ink-muted uppercase tracking-wider mb-1.5">
            Nội dung (Markdown)
          </label>
          <textarea
            name="content"
            defaultValue={page.content}
            required
            rows={20}
            className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm font-mono focus:outline-none focus:border-accent-primary"
          />
          <p className="mt-1 text-xs text-ink-muted">
            Hỗ trợ Markdown: ## tiêu đề, **đậm**, [link](url), ![ảnh](url), bảng, code blocks.
          </p>
        </div>
      </div>

      {/* SEO */}
      <details className="rounded-xl border border-stroke-subtle bg-bg-elevated/40">
        <summary className="px-5 py-3 cursor-pointer font-medium select-none">SEO</summary>
        <div className="px-5 pb-5 space-y-4">
          <div>
            <label className="block text-xs font-medium text-ink-muted uppercase tracking-wider mb-1.5">
              Meta title
            </label>
            <input
              name="metaTitle"
              defaultValue={page.metaTitle ?? ""}
              maxLength={70}
              className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-ink-muted uppercase tracking-wider mb-1.5">
              Meta description
            </label>
            <textarea
              name="metaDesc"
              defaultValue={page.metaDesc ?? ""}
              maxLength={160}
              rows={2}
              className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-ink-muted uppercase tracking-wider mb-1.5">
                Meta keywords
              </label>
              <input
                name="metaKeywords"
                defaultValue={page.metaKeywords ?? ""}
                placeholder="từ khoá 1, từ khoá 2"
                className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-ink-muted uppercase tracking-wider mb-1.5">
                Canonical URL
              </label>
              <input
                name="canonicalUrl"
                defaultValue={page.canonicalUrl ?? ""}
                placeholder="để trống = mặc định"
                className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
              />
            </div>
          </div>
          <div>
            <label className="block text-xs font-medium text-ink-muted uppercase tracking-wider mb-1.5">
              OG image URL
            </label>
            <input
              name="ogImage"
              defaultValue={page.ogImage ?? ""}
              className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
            />
          </div>
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              name="noIndex"
              defaultChecked={page.noIndex}
              className="h-4 w-4 rounded border-stroke-subtle"
            />
            <span>Ẩn khỏi Google (noindex, nofollow)</span>
          </label>
        </div>
      </details>

      {/* Footer / Visibility */}
      <details className="rounded-xl border border-stroke-subtle bg-bg-elevated/40">
        <summary className="px-5 py-3 cursor-pointer font-medium select-none">Hiển thị</summary>
        <div className="px-5 pb-5 space-y-4">
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              name="showInFooter"
              defaultChecked={page.showInFooter}
              className="h-4 w-4 rounded border-stroke-subtle"
            />
            <span>Hiện trong cột &ldquo;Trang&rdquo; của footer</span>
          </label>
          <div>
            <label className="block text-xs font-medium text-ink-muted uppercase tracking-wider mb-1.5">
              Thứ tự footer (số nhỏ lên trước)
            </label>
            <input
              type="number"
              name="footerOrder"
              defaultValue={page.footerOrder}
              min={0}
              max={999}
              className="w-32 px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
            />
          </div>
        </div>
      </details>

      {/* Footer actions */}
      <div className="flex flex-wrap items-center justify-between gap-3 sticky bottom-0 -mx-2 px-2 py-3 bg-bg-base/95 backdrop-blur-sm border-t border-stroke-subtle">
        <div className="flex items-center gap-3">
          <select
            name="status"
            defaultValue={page.status}
            className="px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
          >
            <option value="draft">Nháp</option>
            <option value="published">Đã đăng</option>
          </select>
          <button
            type="submit"
            disabled={pending}
            className="px-5 py-2 rounded-lg bg-accent-primary text-white text-sm font-medium hover:bg-accent-primary/90 transition disabled:opacity-60"
          >
            {pending ? "Đang lưu…" : mode === "create" ? "Tạo trang" : "Lưu thay đổi"}
          </button>
          {savedAt ? (
            <span className="text-xs text-emerald-300">
              Đã lưu lúc {savedAt.toLocaleTimeString("vi-VN")}
            </span>
          ) : null}
        </div>
        {mode === "edit" && !page.isSystem ? (
          <button
            type="button"
            onClick={onDelete}
            disabled={pending}
            className="px-3 py-2 rounded-lg text-rose-300 hover:bg-rose-500/10 text-sm transition disabled:opacity-60"
          >
            Xoá vĩnh viễn
          </button>
        ) : null}
      </div>
    </form>
  );
}
