import Image from "next/image";
import { redirect } from "next/navigation";
import { getCurrentCustomerId } from "@/lib/customer-auth";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";
import { TYPE_LABELS, stageInfo } from "@/lib/custom-orders";
import { submitCustomOrderRequest, respondToDesignProof } from "@/lib/actions/customer-account";

export const metadata = { title: "My Custom Orders — Iniyaval Return Gifts" };

export default async function CustomOrdersPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const customerId = await getCurrentCustomerId();
  if (!customerId) redirect("/account/login");
  const { error } = await searchParams;

  const [customer, requests] = await Promise.all([
    prisma.customer.findUniqueOrThrow({ where: { id: customerId } }),
    prisma.customOrderRequest.findMany({ where: { customerId }, orderBy: { createdAt: "desc" } }),
  ]);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-rose-800">Custom Orders</h1>
      <p className="mt-1 text-sm text-stone-500">Personalization requests — name engraving, laser engraving, or 3D printing.</p>

      {error && <p className="mt-4 mb-4 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <div className="mt-4 space-y-3">
        {requests.length === 0 ? (
          <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">No custom order requests yet.</p>
        ) : (
          requests.map((r) => {
            const stage = stageInfo(r.status);
            return (
              <div key={r.id} className="rounded-lg border border-rose-100 bg-white p-4 text-sm">
                <div className="flex items-start justify-between">
                  <div>
                    <p className="font-medium text-stone-800">{TYPE_LABELS[r.type] ?? r.type}</p>
                    <p className="text-xs text-stone-400">Requested {formatDate(r.createdAt)}</p>
                  </div>
                  <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${stage.color}`}>{stage.label}</span>
                </div>
                <p className="mt-2 text-stone-600">{r.details}</p>

                {r.status === "design_approval" && r.designProofImage && !r.customerFeedback && (
                  <div className="mt-3 rounded-md border border-sky-100 bg-sky-50/60 p-3">
                    <p className="text-xs font-semibold text-stone-700">We&apos;ve uploaded a design for your approval:</p>
                    <a href={r.designProofImage} target="_blank" rel="noopener noreferrer" className="mt-2 block">
                      <Image src={r.designProofImage} alt="Design proof" width={160} height={160} className="rounded-md border border-stone-200 object-cover" />
                    </a>
                    <div className="mt-3 flex flex-wrap items-center gap-2">
                      <form action={respondToDesignProof.bind(null, r.id)}>
                        <input type="hidden" name="decision" value="approve" />
                        <button type="submit" className="rounded-md bg-emerald-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-emerald-800">
                          Approve — start production
                        </button>
                      </form>
                      <details className="w-full sm:w-auto">
                        <summary className="cursor-pointer text-xs font-medium text-stone-500 hover:text-rose-700">Request changes</summary>
                        <form action={respondToDesignProof.bind(null, r.id)} className="mt-2 flex gap-2">
                          <input type="hidden" name="decision" value="reject" />
                          <input name="feedback" required maxLength={2000} placeholder="What would you like changed?" className="flex-1 rounded-md border border-stone-300 px-2 py-1.5 text-xs" />
                          <button type="submit" className="whitespace-nowrap rounded-md bg-stone-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-stone-800">
                            Send
                          </button>
                        </form>
                      </details>
                    </div>
                  </div>
                )}
                {r.status === "design_approval" && r.designProofImage && r.customerFeedback && (
                  <p className="mt-3 rounded-md border border-amber-100 bg-amber-50 p-2 text-xs text-amber-800">
                    You asked for changes — we&apos;ll upload a revised design soon.
                  </p>
                )}
              </div>
            );
          })
        )}
      </div>

      <div className="mt-6 rounded-lg border border-rose-100 bg-white p-4">
        <h2 className="text-sm font-semibold text-stone-700">Submit a new request</h2>
        <form action={submitCustomOrderRequest} className="mt-3 grid grid-cols-1 gap-2 sm:grid-cols-2">
          <select name="type" required className="rounded-md border border-stone-300 px-2 py-1.5 text-sm">
            <option value="">Type…</option>
            <option value="name_engraving">Name Engraving</option>
            <option value="laser_engraving">Laser Engraving</option>
            <option value="3d_printing">3D Printing</option>
          </select>
          <input name="quantity" type="number" min={1} placeholder="Quantity" className="rounded-md border border-stone-300 px-2 py-1.5 text-sm" />
          <input
            name="phone"
            type="tel"
            required
            inputMode="numeric"
            pattern="\d{10}"
            maxLength={10}
            title="Enter a 10-digit mobile number"
            defaultValue={customer.phone ?? ""}
            placeholder="Phone"
            className="rounded-md border border-stone-300 px-2 py-1.5 text-sm sm:col-span-2"
          />
          <textarea name="details" required maxLength={2000} placeholder="Describe what you'd like personalized" rows={3} className="rounded-md border border-stone-300 px-2 py-1.5 text-sm sm:col-span-2" />
          <div className="sm:col-span-2">
            <label className="text-xs text-stone-500">Reference image (optional)</label>
            <input
              type="file"
              name="image"
              accept="image/jpeg,image/png,image/webp,image/gif"
              className="mt-1 block w-full text-sm text-stone-600 file:mr-3 file:rounded-md file:border-0 file:bg-rose-100 file:px-3 file:py-1.5 file:text-sm file:font-medium file:text-rose-800 hover:file:bg-rose-200"
            />
          </div>
          <button type="submit" className="rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800 sm:col-span-2">
            Submit request
          </button>
        </form>
      </div>
    </div>
  );
}
