import { notFound } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import { toProductDTO } from '@/lib/product';
import { fetchActivePromotions } from '@/lib/promotions';
import { updateProduct } from '../../actions';
import AdminNav from '@/components/AdminNav';
import ColorPicker from '@/components/ColorPicker';
import SizePicker from '@/components/SizePicker';
import PhotoPrintAreaField from '@/components/PhotoPrintAreaField';
import { MOCKUP_OPTIONS } from '@/lib/mockupDefaults';

export default async function EditProductPage({ params }: { params: { id: string } }) {
  const activePromotions = await fetchActivePromotions();
  const row = await prisma.product.findUnique({ where: { id: params.id }, include: { collections: true } });
  if (!row) notFound();
  const product = toProductDTO(row, activePromotions);

  const categories = await prisma.category.findMany({ orderBy: { name: 'asc' } });
  const collections = await prisma.collection.findMany({ orderBy: { name: 'asc' } });
  const occasions = collections.filter((c) => c.group === 'OCCASION');
  const recipients = collections.filter((c) => c.group === 'RECIPIENT');
  const selectedCollectionIds = new Set(row.collections.map((c) => c.id));

  return (
    <div className="mx-auto max-w-2xl px-6 py-12">
      <AdminNav />
      <h1 className="font-display text-3xl">Edit {product.name}</h1>
      <p className="mt-2 text-sm text-muted">
        Changes apply immediately to the live product at /made-to-order/{product.slug}.
      </p>

      <form action={updateProduct} className="mt-10 space-y-6" encType="multipart/form-data">
        <input type="hidden" name="id" value={product.id} />

        <div>
          <label className="tag-label mb-2 block">Show on</label>
          <div className="space-y-2">
            <label className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                name="showOnPersonalised"
                value="1"
                defaultChecked={product.showOnPersonalised}
                className="h-4 w-4 accent-clay"
              />
              Personalised catalog (/made-to-order) — customers design their own
            </label>
            <label className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                name="showOnProducts"
                value="1"
                defaultChecked={product.showOnProducts}
                className="h-4 w-4 accent-clay"
              />
              Products catalog (/products) — same photos, browse and buy as-is
            </label>
          </div>
          <p className="mt-1 text-xs text-muted">Check both to list the same product on both pages.</p>
        </div>

        <div>
          <label htmlFor="name" className="tag-label mb-2 block">
            Product name
          </label>
          <input
            id="name"
            name="name"
            required
            defaultValue={product.name}
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label htmlFor="category" className="tag-label mb-2 block">
              Category
            </label>
            <select
              id="category"
              name="category"
              required
              defaultValue={product.category}
              className="w-full border border-line bg-paper px-3 py-2 text-sm"
            >
              {categories.map((c) => (
                <option key={c.id} value={c.slug}>
                  {c.name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label htmlFor="mockup" className="tag-label mb-2 block">
              Shape (used if no photo)
            </label>
            <select
              id="mockup"
              name="mockup"
              required
              defaultValue={product.mockup}
              className="w-full border border-line bg-paper px-3 py-2 text-sm"
            >
              {MOCKUP_OPTIONS.map((m) => (
                <option key={m.value} value={m.value}>
                  {m.label}
                </option>
              ))}
            </select>
          </div>
        </div>

        {(occasions.length > 0 || recipients.length > 0) && (
          <div>
            <label className="tag-label mb-2 block">Collections (optional)</label>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="mb-2 text-xs text-muted">Occasions</p>
                <div className="space-y-1.5">
                  {occasions.map((c) => (
                    <label key={c.id} className="flex items-center gap-2 text-sm">
                      <input
                        type="checkbox"
                        name="collections"
                        value={c.id}
                        defaultChecked={selectedCollectionIds.has(c.id)}
                        className="h-4 w-4 accent-clay"
                      />
                      {c.name}
                    </label>
                  ))}
                  {occasions.length === 0 && <p className="text-xs text-muted">None yet.</p>}
                </div>
              </div>
              <div>
                <p className="mb-2 text-xs text-muted">Gifts for</p>
                <div className="space-y-1.5">
                  {recipients.map((c) => (
                    <label key={c.id} className="flex items-center gap-2 text-sm">
                      <input
                        type="checkbox"
                        name="collections"
                        value={c.id}
                        defaultChecked={selectedCollectionIds.has(c.id)}
                        className="h-4 w-4 accent-clay"
                      />
                      {c.name}
                    </label>
                  ))}
                  {recipients.length === 0 && <p className="text-xs text-muted">None yet.</p>}
                </div>
              </div>
            </div>
            <a href="/admin/collections/new" className="mt-1 inline-block text-xs text-clay hover:text-clay-dark">
              + Add a new collection
            </a>
          </div>
        )}

        <div>
          <label htmlFor="price" className="tag-label mb-2 block">
            Price (£)
          </label>
          <input
            id="price"
            name="price"
            type="number"
            step="0.01"
            min={0}
            required
            defaultValue={(product.basePrice / 100).toFixed(2)}
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
          />
        </div>

        <div>
          <label htmlFor="salePrice" className="tag-label mb-2 block">
            Sale price (£, optional)
          </label>
          <input
            id="salePrice"
            name="salePrice"
            type="number"
            step="0.01"
            min={0}
            defaultValue={row.salePrice != null ? (row.salePrice / 100).toFixed(2) : ''}
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
            placeholder="Leave blank for no sale"
          />
          <p className="mt-1 text-xs text-muted">
            Set a start/end date below too — outside that window the normal price shows instead.
          </p>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label htmlFor="saleStartsAt" className="tag-label mb-2 block">
              Sale starts (optional)
            </label>
            <input
              id="saleStartsAt"
              name="saleStartsAt"
              type="date"
              defaultValue={row.saleStartsAt ? row.saleStartsAt.toISOString().slice(0, 10) : ''}
              className="w-full border border-line bg-paper px-3 py-2 text-sm"
            />
          </div>
          <div>
            <label htmlFor="saleEndsAt" className="tag-label mb-2 block">
              Sale ends (optional)
            </label>
            <input
              id="saleEndsAt"
              name="saleEndsAt"
              type="date"
              defaultValue={row.saleEndsAt ? row.saleEndsAt.toISOString().slice(0, 10) : ''}
              className="w-full border border-line bg-paper px-3 py-2 text-sm"
            />
          </div>
        </div>

        <div>
          <label htmlFor="personalisedPrice" className="tag-label mb-2 block">
            Personalised price (£, optional)
          </label>
          <input
            id="personalisedPrice"
            name="personalisedPrice"
            type="number"
            step="0.01"
            min={0}
            defaultValue={row.personalisedPrice != null ? (row.personalisedPrice / 100).toFixed(2) : ''}
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
            placeholder="Leave blank to use the regular price"
          />
          <p className="mt-1 text-xs text-muted">
            Higher price for made-to-order items. Leave blank to use the same price as ready-made.
          </p>
        </div>

        <div>
          <label className="tag-label mb-2 block">Front photo</label>
          {product.imageUrl && (
            <div className="mb-3 flex items-center gap-3">
              <img src={product.imageUrl} alt={product.name} className="h-20 w-20 border border-line object-contain" />
              <p className="text-xs text-muted">Current photo. Upload a new one below to replace it.</p>
            </div>
          )}
          <PhotoPrintAreaField />
        </div>

        <div>
          <label className="tag-label mb-2 block">Back photo</label>
          {product.imageUrlBack && (
            <div className="mb-3 flex items-center gap-3">
              <img
                src={product.imageUrlBack}
                alt={`${product.name} back`}
                className="h-20 w-20 border border-line object-contain"
              />
              <p className="text-xs text-muted">Current back photo and print area. Upload a new one below to replace both.</p>
            </div>
          )}
          <PhotoPrintAreaField variant="back" />
        </div>

        <div>
          <label className="flex items-start gap-2 text-sm">
            <input
              type="checkbox"
              name="photoRecolorable"
              value="1"
              defaultChecked={product.photoRecolorable}
              className="mt-1 h-4 w-4 accent-clay"
            />
            <span>
              Tint this photo per color (fallback)
              <span className="mt-1 block text-xs text-muted">
                Only works well for black, white, or gray photos — the color is applied as a live
                tint. If you have real photos for specific colors, add them below instead — this
                only kicks in for colors that don&apos;t have their own photo.
              </span>
            </span>
          </label>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label htmlFor="referenceWidthCm" className="tag-label mb-2 block">
              Reference width (cm)
            </label>
            <input
              id="referenceWidthCm"
              name="referenceWidthCm"
              type="number"
              step="0.1"
              min="0"
              placeholder="e.g. 40"
              defaultValue={product.referenceWidthCm ?? ''}
              className="w-full border border-line bg-paper px-3 py-2 text-sm"
            />
            <p className="mt-1 text-xs text-muted">Width of garment/object for ruler reference (optional)</p>
          </div>
          <div>
            <label htmlFor="referenceHeightCm" className="tag-label mb-2 block">
              Reference height (cm)
            </label>
            <input
              id="referenceHeightCm"
              name="referenceHeightCm"
              type="number"
              step="0.1"
              min="0"
              placeholder="e.g. 60"
              defaultValue={product.referenceHeightCm ?? ''}
              className="w-full border border-line bg-paper px-3 py-2 text-sm"
            />
            <p className="mt-1 text-xs text-muted">Height of garment/object for ruler reference (optional)</p>
          </div>
        </div>

        <div>
          <label className="tag-label mb-2 block">Colors</label>
          <ColorPicker
            name="colors"
            defaultColors={product.colors}
            defaultColorPhotos={product.colorPhotos}
            defaultColorPhotosBack={product.colorPhotosBack}
          />
        </div>

        <div>
          <label className="tag-label mb-2 block">Sizes (optional)</label>
          <SizePicker name="sizes" defaultSizes={product.sizes} />
        </div>

        <div>
          <label htmlFor="description" className="tag-label mb-2 block">
            Description
          </label>
          <textarea
            id="description"
            name="description"
            rows={3}
            defaultValue={product.description}
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
          />
        </div>

        <button type="submit" className="bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark">
          Save changes
        </button>
      </form>
    </div>
  );
}
