import { notFound } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import AdminNav from '@/components/AdminNav';
import { startDesignWithProduct } from './actions';

export default async function StartDesignPage({ params }: { params: { id: string } }) {
  const request = await prisma.customRequest.findUnique({
    where: { id: params.id },
    include: { product: true },
  });
  if (!request) notFound();

  const products = await prisma.product.findMany({
    where: { showOnPersonalised: true },
    orderBy: { name: 'asc' },
  });

  return (
    <div className="mx-auto max-w-2xl px-6 py-12">
      <AdminNav />
      <h1 className="font-display text-3xl">Start design for this photo</h1>
      <p className="mt-2 text-sm text-muted">Select which product to design this photo on</p>

      <div className="mt-6 border border-line bg-surface p-6">
        <img src={request.imageDataUrl} alt="Customer's photo" className="mx-auto max-h-64 object-contain" />
      </div>

      <div className="mt-6 border border-line bg-surface p-6">
        <p className="tag-label mb-2">Photo request details</p>
        <p className="text-sm mb-2"><span className="font-medium">Customer:</span> {request.customerName}</p>
        <p className="text-sm"><span className="font-medium">Originally requested for:</span> {request.product.name}</p>
      </div>

      <form action={async (formData) => {
        'use server';
        await startDesignWithProduct(formData, request.id);
      }} className="mt-6 space-y-4 border border-line bg-surface p-6">
        <div>
          <label htmlFor="productId" className="tag-label mb-2 block">
            Which product to design on?
          </label>
          <select
            id="productId"
            name="productId"
            required
            defaultValue={request.productId}
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
          >
            <option value="">Select a product...</option>
            {products.map((p) => (
              <option key={p.id} value={p.id}>
                {p.name}
              </option>
            ))}
          </select>
        </div>

        <div className="flex gap-3 pt-4">
          <button type="submit" className="bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark">
            Go to design canvas
          </button>
          <a
            href={`/admin/custom-requests/${request.id}`}
            className="border border-line px-6 py-3 text-sm hover:border-clay hover:text-clay"
          >
            Cancel
          </a>
        </div>
      </form>
    </div>
  );
}
