import { notFound } from "next/navigation";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { canDownloadOriginals, canViewProperty } from "@/lib/access";
import { env } from "@/lib/env";
import { formatDate, formatMoney } from "@/lib/format";

export default async function PropertyPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const user = await requireUser();
  const property = await db.property.findUnique({
    where: { id },
    include: {
      photos: { orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }] },
      orders: { orderBy: { createdAt: "desc" } },
    },
  });
  // 404 (not 403) so clients can't discover other clients' property ids.
  if (!property || !canViewProperty(user, property)) notFound();

  const download = canDownloadOriginals(user, property, property.orders);
  const openOrders = property.orders.filter((o) => o.status === "PENDING");

  return (
    <>
      <h1>{property.address}</h1>
      <p className="muted">Shot {formatDate(property.shootDate)} · {property.photos.length} photos</p>

      {download.allowed ? (
        <div className="notice ok">Payment received. Full-resolution downloads are unlocked.</div>
      ) : openOrders.length > 0 ? (
        <div className="notice warn">
          <strong>Awaiting payment.</strong> Send an Interac e-Transfer to <strong>{env().INTERAC_EMAIL}</strong> and put
          the reference code in the message. Downloads unlock once the studio confirms your payment.
          <table style={{ marginTop: 12 }}>
            <thead>
              <tr><th>Reference code</th><th>Amount</th><th>Status</th></tr>
            </thead>
            <tbody>
              {openOrders.map((o) => (
                <tr key={o.id}>
                  <td><code className="ref">{o.referenceCode}</code></td>
                  <td>{formatMoney(o.amountCents, o.currency)}</td>
                  <td><span className={`badge ${o.status}`}>{o.status}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="notice">Previews are watermarked. The studio will send your invoice shortly.</div>
      )}

      {property.orders.length > 0 && (
        <>
          <h2>Orders</h2>
          <table>
            <thead>
              <tr><th>Reference</th><th>Amount</th><th>Status</th><th>Paid</th></tr>
            </thead>
            <tbody>
              {property.orders.map((o) => (
                <tr key={o.id}>
                  <td><code>{o.referenceCode}</code></td>
                  <td>{formatMoney(o.amountCents, o.currency)}</td>
                  <td><span className={`badge ${o.status}`}>{o.status}</span></td>
                  <td>{formatDate(o.paidAt)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </>
      )}

      <h2>Photos</h2>
      <div className="grid">
        {property.photos.map((photo) => (
          <div className="photo" key={photo.id}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={`/api/photos/${photo.id}/preview`} alt={photo.filename} loading="lazy" />
            <div className="meta">
              <span className="muted" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                {photo.filename}
              </span>
              {download.allowed ? (
                <a className="btn" href={`/api/photos/${photo.id}/download`}>Download</a>
              ) : (
                <span className="muted">Locked</span>
              )}
            </div>
          </div>
        ))}
      </div>
    </>
  );
}
