import Link from 'next/link';
import { notFound } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import AdminNav from '@/components/AdminNav';
import ShareButtons from '@/components/ShareButtons';
import DownloadPhotoButton from '@/components/DownloadPhotoButton';
import { deleteRequest, markRequestDone, markRequestNew } from '../actions';

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

  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000';
  const adminLink = `${siteUrl}/admin/custom-requests/${request.id}`;
  const whatsappDigits = request.customerPhone ? request.customerPhone.replace(/\D/g, '') : null;
  const whatsappMessage = `Hi ${request.customerName}, thanks for sending over your photo for a ${request.product.name} — we're working on it!`;

  const newProofParams = new URLSearchParams({
    productId: request.productId,
    customerName: request.customerName,
    customerEmail: request.customerEmail,
  });

  return (
    <div className="mx-auto max-w-2xl px-6 py-12">
      <AdminNav />
      <div className="flex items-baseline justify-between gap-3">
        <h1 className="font-display text-3xl">Photo request</h1>
        <span
          className={`tag-label rounded-full px-3 py-1 ${
            request.status === 'NEW' ? 'bg-splash-orange/10 text-splash-orange' : 'bg-splash-blue/10 text-splash-blue'
          }`}
        >
          {request.status}
        </span>
      </div>

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

      {request.note && (
        <div className="mt-6 border-l-2 border-splash-pink pl-4 text-sm italic">"{request.note}"</div>
      )}

      <div className="mt-6 grid gap-4 sm:grid-cols-2">
        <div>
          <p className="tag-label mb-1">Customer</p>
          <p className="text-sm">{request.customerName}</p>
          <p className="text-sm text-muted">{request.customerEmail}</p>
          {request.customerPhone && <p className="text-sm text-muted">{request.customerPhone}</p>}
        </div>
        <div>
          <p className="tag-label mb-1">For</p>
          <p className="text-sm">{request.product.name}</p>
        </div>
      </div>

      <div className="mt-8 flex flex-wrap gap-3">
        <DownloadPhotoButton photoUrl={request.imageDataUrl} customerName={request.customerName} />

        <Link
          href={`/admin/proofs/new?${newProofParams.toString()}`}
          className="bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark"
        >
          Start a design for this
        </Link>

        {whatsappDigits && (
          <a
            href={`https://wa.me/${whatsappDigits}?text=${encodeURIComponent(whatsappMessage)}`}
            target="_blank"
            rel="noopener noreferrer"
            className="border border-ink px-6 py-3 text-sm hover:border-clay hover:bg-clay hover:text-paper"
          >
            Message {request.customerName} on WhatsApp
          </a>
        )}

        <form action={request.status === 'NEW' ? markRequestDone : markRequestNew}>
          <input type="hidden" name="id" value={request.id} />
          <button
            type="submit"
            className="tag-label border border-line px-4 py-3 hover:border-clay hover:text-clay"
          >
            {request.status === 'NEW' ? 'Mark as done' : 'Reopen'}
          </button>
        </form>

        <form action={deleteRequest}>
          <input type="hidden" name="id" value={request.id} />
          <button
            type="submit"
            className="tag-label border border-line px-4 py-3 text-muted hover:border-splash-pink hover:text-splash-pink"
          >
            Delete
          </button>
        </form>
      </div>

      <div className="mt-10 border-t border-line pt-6">
        <p className="tag-label mb-3">Notify yourself / a colleague</p>
        <ShareButtons
          message={`New photo request from ${request.customerName} for a ${request.product.name}: ${adminLink}`}
          link={adminLink}
          redirectUri={adminLink}
        />
      </div>

      <Link href="/admin/custom-requests" className="mt-8 inline-block tag-label hover:text-ink">
        ← All photo requests
      </Link>
    </div>
  );
}
