import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/Button";
import {
  getProductForAdmin,
  listCategoriesForAdmin,
  formatPrice,
} from "@/lib/store/queries";
import {
  AdminHeading,
  FormSection,
  InputField,
  TextareaField,
  SelectField,
  StatusBadge,
  ConfirmButton,
  ImageUpload,
  MarkdownEditor,
  RepeaterField,
  type RepeaterFieldDef,
} from "@/components/admin";
import { updateProduct, setProductStatus, deleteProduct } from "../actions";

export const dynamic = "force-dynamic";

const statusOptions = ["draft", "published", "archived"] as const;
const STOCK_OPTIONS = [
  { value: "in_stock", label: "In stock" },
  { value: "out_of_stock", label: "Out of stock" },
  { value: "preorder", label: "Preorder" },
  { value: "coming_soon", label: "Coming soon" },
];

const galleryFields: RepeaterFieldDef[] = [
  { key: "path", label: "Image URL", type: "text", span: 2, maxLength: 500 },
  { key: "alt", label: "Alt text", type: "text", span: 1, maxLength: 500 },
];

export default async function AdminStoreProductEditor({
  params,
}: {
  params: Promise<{ productId: string }>;
}) {
  const { productId } = await params;
  const product = await getProductForAdmin(productId);
  if (!product) notFound();

  const categories = await listCategoriesForAdmin();

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/store"
          className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-blue)]"
        >
          <ArrowLeft className="h-3.5 w-3.5" aria-hidden />
          All products
        </Link>
      </div>

      <AdminHeading
        eyebrow={`Product · ${product.slug}`}
        title={product.title}
        lede={`${formatPrice(product.priceMinor, product.currency)} · ${product.sku ?? "No SKU"}`}
        actions={
          <div className="flex items-center gap-2">
            <StatusBadge label={product.stockStatus.replace("_", "-")} dot />
            <StatusBadge label={product.status} dot />
          </div>
        }
      />

      <div className="grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,1fr)]">
        <div className="flex flex-col gap-6">
          <FormSection title="Details">
            <form action={updateProduct} className="grid gap-4 md:grid-cols-2">
              <input type="hidden" name="id" value={product.id} />
              <InputField
                label="Title"
                name="title"
                defaultValue={product.title}
                required
                wrapClassName="md:col-span-2"
              />
              <SelectField
                label="Category"
                name="categoryId"
                defaultValue={product.categoryId ?? ""}
              >
                <option value="">— none —</option>
                {categories.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name}
                  </option>
                ))}
              </SelectField>
              <InputField label="SKU" name="sku" defaultValue={product.sku ?? ""} />
              <InputField
                label="Price (minor units)"
                name="priceMinor"
                type="number"
                defaultValue={String(product.priceMinor)}
              />
              <InputField label="Currency" name="currency" defaultValue={product.currency} />
              <SelectField
                label="Stock status"
                name="stockStatus"
                defaultValue={product.stockStatus}
                options={STOCK_OPTIONS}
              />
              <label className="flex items-end gap-2.5 text-[13px]">
                <input
                  type="checkbox"
                  name="memberOnly"
                  defaultChecked={product.memberOnly}
                  className="mb-2 h-4 w-4 rounded border-[var(--color-line)] text-[var(--color-blue)]"
                />
                <span className="mb-2 font-semibold text-[var(--color-ink)]">Members only</span>
              </label>
              <TextareaField
                label="Short description"
                name="shortDescription"
                defaultValue={product.shortDescription}
                rows={2}
                maxLength={400}
                wrapClassName="md:col-span-2"
              />
              <div className="md:col-span-2">
                <MarkdownEditor
                  name="description"
                  label="Full description"
                  defaultValue={product.description}
                  rows={10}
                  maxLength={10_000}
                  folder="store"
                  hint="Markdown supported — use headings for sections like Features, Contents, and Specifications"
                />
              </div>
              <div className="md:col-span-2">
                <ImageUpload
                  name="coverImage"
                  altName="coverImageAlt"
                  folder="store"
                  label="Cover image"
                  defaultValue={product.coverImage}
                  defaultAlt={product.coverImageAlt}
                />
              </div>
              <div className="md:col-span-2">
                <RepeaterField
                  name="gallery"
                  label="Additional images"
                  hint="Supplementary gallery shown on the product detail page. Up to 8 images."
                  fields={galleryFields}
                  defaultValue={
                    (product.gallery ?? []) as unknown as Array<Record<string, string>>
                  }
                  addLabel="Add gallery image"
                  emptyRow={{ path: "", alt: "" }}
                  max={8}
                />
              </div>
              <div className="md:col-span-2">
                <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                  Save product
                </Button>
              </div>
            </form>
          </FormSection>

          <FormSection
            title="Danger zone"
            description="Deleting a product removes it from the store permanently."
            tone="danger"
          >
            <form action={deleteProduct}>
              <input type="hidden" name="id" value={product.id} />
              <ConfirmButton
                label="Delete product"
                confirmLabel="Click again to delete permanently"
                tone="danger"
              />
            </form>
          </FormSection>
        </div>

        <aside className="flex flex-col gap-6">
          <FormSection title="Publication status">
            <div className="flex flex-col gap-2">
              {statusOptions.map((s) => (
                <form key={s} action={setProductStatus}>
                  <input type="hidden" name="id" value={product.id} />
                  <input type="hidden" name="status" value={s} />
                  <button
                    type="submit"
                    disabled={product.status === s}
                    className={
                      product.status === s
                        ? "w-full rounded-lg bg-[var(--color-blue)] px-3 py-2 text-[13px] font-semibold text-white"
                        : "w-full rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                    }
                  >
                    {product.status === s ? `Current · ${s}` : `Set to ${s}`}
                  </button>
                </form>
              ))}
            </div>
          </FormSection>
        </aside>
      </div>
    </>
  );
}
