"use client";

import { useState } from "react";
import { Camera, ExternalLink } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useT } from "@/i18n";
import type { Order } from "@/types/order";

/**
 * The photograph the captain took on handing the parcel over.
 *
 * It is the evidence behind a delivery anyone later disputes, and the API has been returning it
 * all along while no screen asked for it — so the one artefact that settles "it never arrived"
 * was reachable only by reading JSON.
 *
 * Deliberately not `next/image`: the file is served from our own media disk, which may be an
 * S3-compatible host that the image loader is not configured for, and a misconfigured loader
 * fails the whole page rather than one picture. A plain tag with a fallback degrades to a link.
 */
export function OrderProof({ order }: { order: Order }) {
  const t = useT();
  const [broken, setBroken] = useState(false);

  const url = order.proof_of_delivery ?? null;

  if (!url) {
    return null;
  }

  return (
    <Card className="mt-6">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Camera className="h-4 w-4 text-primary" aria-hidden />
          {t("orders.proof.title")}
        </CardTitle>
      </CardHeader>
      <CardContent>
        {broken ? (
          // The picture would not load, which is not the same as there being none: say so, and
          // keep the link, because the file may well open in a tab that the page cannot embed.
          <p className="text-sm text-muted-foreground">{t("orders.proof.unavailable")}</p>
        ) : (
          <a href={url} target="_blank" rel="noreferrer" className="inline-block">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={url}
              alt={t("orders.proof.alt", { order: order.order_number })}
              onError={() => setBroken(true)}
              className="max-h-80 rounded-lg border object-contain"
            />
          </a>
        )}
        <a
          href={url}
          target="_blank"
          rel="noreferrer"
          className="mt-3 inline-flex items-center gap-1.5 text-xs text-primary hover:underline"
        >
          <ExternalLink className="h-3.5 w-3.5" aria-hidden />
          {t("orders.proof.open")}
        </a>
      </CardContent>
    </Card>
  );
}
