"use client";

import { useState } from "react";
import { useFormStatus } from "react-dom";
import { createProduct, updateProduct } from "@/app/admin/actions";
import { CONDITIONS, CONDITION_META, PRODUCT_STATUSES } from "@/lib/constants";
import type { SpecField } from "@/lib/serialize";

type CategoryOption = {
  id: string;
  name: string;
  specFields: SpecField[];
};

type Initial = {
  id: string;
  title: string;
  description: string;
  brand: string | null;
  price: number;
  mrp: number | null;
  condition: string;
  warrantyMonths: number;
  quantity: number;
  featured: boolean;
  status: string;
  categoryId: string;
  specs: Record<string, string>;
  images: { id: string; url: string }[];
};

function SubmitButton({ label }: { label: string }) {
  const { pending } = useFormStatus();
  return (
    <button
      type="submit"
      disabled={pending}
      className="rounded-lg bg-brand-600 px-6 py-2.5 text-sm font-semibold text-white hover:bg-brand-700 disabled:opacity-60"
    >
      {pending ? "Saving…" : label}
    </button>
  );
}

const inputClass =
  "mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm";
const labelClass = "text-sm font-medium text-slate-600";

export function ProductForm({
  categories,
  initial,
}: {
  categories: CategoryOption[];
  initial?: Initial;
}) {
  const [categoryId, setCategoryId] = useState(
    initial?.categoryId ?? categories[0]?.id ?? "",
  );
  const activeCategory = categories.find((c) => c.id === categoryId);
  const action = initial ? updateProduct : createProduct;

  return (
    <form action={action} className="space-y-6">
      {initial ? <input type="hidden" name="id" value={initial.id} /> : null}

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Left: main details */}
        <div className="space-y-5 lg:col-span-2">
          <div className="rounded-xl border border-slate-200 bg-white p-5">
            <label className="block">
              <span className={labelClass}>Title *</span>
              <input
                name="title"
                required
                defaultValue={initial?.title}
                placeholder="e.g. Dell Latitude 7490 — Core i7, 16GB, 512GB SSD"
                className={inputClass}
              />
            </label>

            <label className="mt-4 block">
              <span className={labelClass}>Description</span>
              <textarea
                name="description"
                rows={5}
                defaultValue={initial?.description}
                placeholder="Condition details, what's included, testing notes…"
                className={inputClass}
              />
            </label>

            <div className="mt-4 grid gap-4 sm:grid-cols-2">
              <label className="block">
                <span className={labelClass}>Category *</span>
                <select
                  name="categoryId"
                  required
                  value={categoryId}
                  onChange={(e) => setCategoryId(e.target.value)}
                  className={inputClass}
                >
                  {categories.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name}
                    </option>
                  ))}
                </select>
              </label>
              <label className="block">
                <span className={labelClass}>Brand</span>
                <input name="brand" defaultValue={initial?.brand ?? ""} className={inputClass} />
              </label>
            </div>
          </div>

          {/* Specs */}
          {activeCategory && activeCategory.specFields.length > 0 ? (
            <div className="rounded-xl border border-slate-200 bg-white p-5">
              <h3 className="text-sm font-bold text-slate-700">
                Specifications — {activeCategory.name}
              </h3>
              <div className="mt-3 grid gap-4 sm:grid-cols-2">
                {activeCategory.specFields.map((f) => (
                  <label key={f.key} className="block">
                    <span className={labelClass}>{f.label}</span>
                    <input
                      name={`spec_${f.key}`}
                      defaultValue={initial?.specs?.[f.key] ?? ""}
                      className={inputClass}
                    />
                  </label>
                ))}
              </div>
            </div>
          ) : null}

          {/* Images */}
          <div className="rounded-xl border border-slate-200 bg-white p-5">
            <h3 className="text-sm font-bold text-slate-700">Images</h3>
            {initial && initial.images.length > 0 ? (
              <div className="mt-3 flex flex-wrap gap-3">
                {initial.images.map((img) => (
                  <label
                    key={img.id}
                    className="relative block h-24 w-24 cursor-pointer overflow-hidden rounded-lg border border-slate-200"
                  >
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img src={img.url} alt="" className="h-full w-full object-cover" />
                    <span className="absolute inset-x-0 bottom-0 flex items-center gap-1 bg-black/60 px-1 py-0.5 text-[10px] text-white">
                      <input type="checkbox" name="removeImage" value={img.id} />
                      Remove
                    </span>
                  </label>
                ))}
              </div>
            ) : null}
            <label className="mt-3 block">
              <span className={labelClass}>
                {initial ? "Add more images" : "Upload images"}
              </span>
              <input
                type="file"
                name="images"
                accept="image/*"
                multiple
                className="mt-1 block w-full text-sm text-slate-500 file:mr-3 file:rounded-lg file:border-0 file:bg-brand-50 file:px-4 file:py-2 file:text-sm file:font-semibold file:text-brand-700 hover:file:bg-brand-100"
              />
            </label>
            <p className="mt-1 text-xs text-slate-400">
              JPG, PNG, WEBP or GIF. First image is used as the thumbnail.
            </p>
          </div>
        </div>

        {/* Right: pricing & status */}
        <div className="space-y-5">
          <div className="rounded-xl border border-slate-200 bg-white p-5">
            <h3 className="text-sm font-bold text-slate-700">Pricing & stock</h3>
            <label className="mt-3 block">
              <span className={labelClass}>Selling price (₹) *</span>
              <input
                type="number"
                name="price"
                required
                min={0}
                defaultValue={initial?.price ?? ""}
                className={inputClass}
              />
            </label>
            <label className="mt-3 block">
              <span className={labelClass}>Original / MRP (₹)</span>
              <input
                type="number"
                name="mrp"
                min={0}
                defaultValue={initial?.mrp ?? ""}
                className={inputClass}
              />
            </label>
            <label className="mt-3 block">
              <span className={labelClass}>Quantity in stock</span>
              <input
                type="number"
                name="quantity"
                min={0}
                defaultValue={initial?.quantity ?? 1}
                className={inputClass}
              />
            </label>
            <label className="mt-3 block">
              <span className={labelClass}>Warranty (months)</span>
              <input
                type="number"
                name="warrantyMonths"
                min={0}
                defaultValue={initial?.warrantyMonths ?? 0}
                className={inputClass}
              />
            </label>
          </div>

          <div className="rounded-xl border border-slate-200 bg-white p-5">
            <h3 className="text-sm font-bold text-slate-700">Condition & status</h3>
            <label className="mt-3 block">
              <span className={labelClass}>Condition</span>
              <select
                name="condition"
                defaultValue={initial?.condition ?? "GOOD"}
                className={inputClass}
              >
                {CONDITIONS.map((c) => (
                  <option key={c} value={c}>
                    {CONDITION_META[c].label}
                  </option>
                ))}
              </select>
            </label>
            <label className="mt-3 block">
              <span className={labelClass}>Status</span>
              <select
                name="status"
                defaultValue={initial?.status ?? "ACTIVE"}
                className={inputClass}
              >
                {PRODUCT_STATUSES.map((s) => (
                  <option key={s} value={s}>
                    {s}
                  </option>
                ))}
              </select>
            </label>
            <label className="mt-4 flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                name="featured"
                defaultChecked={initial?.featured ?? false}
              />
              <span className="font-medium text-slate-700">
                Feature on homepage
              </span>
            </label>
          </div>
        </div>
      </div>

      <div className="flex items-center gap-3">
        <SubmitButton label={initial ? "Save changes" : "Create product"} />
        <a
          href="/admin/products"
          className="rounded-lg border border-slate-300 px-5 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-100"
        >
          Cancel
        </a>
      </div>
    </form>
  );
}
