import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { transporterApi, type TransporterBid } from "@/lib/api/transporter";
import { requireRole, requireServerToken } from "@/lib/auth/server";
import type { ApiTransporterEnquiryDetail } from "@/lib/api/types";
import SafeImage from "@/components/ui/SafeImage";
import { respondToEnquiry } from "./actions";
import QuoteFieldset from "./QuoteFieldset";
import SubmitQuoteButton from "./SubmitQuoteButton";
import { formatDateTime } from "@/lib/utils";

type PageProps = {
  params: Promise<{ id: string }>;
};

async function loadEnquiry(token: string, id: number): Promise<ApiTransporterEnquiryDetail | null> {
  try {
    return await transporterApi.enquiry(token, id);
  } catch {
    return null;
  }
}

async function loadBids(token: string, id: number): Promise<TransporterBid[]> {
  try {
    return (await transporterApi.enquiryBidding(token, id)).data;
  } catch {
    return [];
  }
}

/**
 * Server-rendered detail view with a Server Action for the quote.
 *
 * The enquiry and the competing bids do not depend on each other, so they are
 * requested together — the same `Promise.all` the effect used, minus the wait
 * for hydration that had to happen before the effect could even run.
 *
 * `params` is a promise in Next 15 and is awaited rather than unwrapped with
 * `use()`; there is no Suspense boundary to fall back to on the server.
 */
export default async function TransporterEnquiryDetailPage({ params }: PageProps) {
  const { id } = await params;
  const token = await requireServerToken(`/transporter/enquiries/${id}`);
  await requireRole(["transporter"]);

  const enquiryId = Number(id);
  const [data, bids] = await Promise.all([loadEnquiry(token, enquiryId), loadBids(token, enquiryId)]);

  if (!data) {
    return <div className="rounded-xl bg-white p-10 text-center text-gray-500 shadow-sm">Enquiry not found.</div>;
  }

  const locked = !!(
    data.is_marked ||
    (data.parent_enquiry &&
      data.parent_enquiry.status &&
      data.parent_enquiry.status !== "pending" &&
      data.parent_enquiry.status !== "Transporter Replied")
  );

  return (
    <div className="space-y-4">
      <Link href="/transporter/enquiries" className="inline-flex items-center gap-1 text-sm text-gray-600 hover:text-[#CC1414]">
        <ArrowLeft className="h-4 w-4" /> Back to enquiries
      </Link>

      <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
        <h1 className="text-xl font-bold text-gray-900">
          Enquiry {data.unique_id ?? data.parent_enquiry?.unique_id ?? `#${data.id}`}
        </h1>
        <p className="mt-1 text-sm text-gray-500">
          Status: <span className="font-medium capitalize text-gray-900">{data.status}</span>
          {data.is_marked && <span className="ml-2 rounded bg-emerald-50 px-2 py-0.5 text-xs text-emerald-700">awarded to you</span>}
        </p>
      </div>

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
        <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-2">
          <h2 className="mb-3 text-sm font-semibold text-gray-900">Product</h2>
          <div className="flex items-start gap-4">
            {data.product?.thumbnail && (
              <SafeImage
                src={data.product.thumbnail}
                alt=""
                width={80}
                height={80}
                className="h-20 w-20 rounded-lg object-cover ring-1 ring-gray-100"
              />
            )}
            <div className="text-sm">
              <div className="font-semibold text-gray-900">{data.product?.name ?? "—"}</div>
              <div className="text-gray-500">{data.brand?.name ?? "—"}</div>
              {data.origin_city && <div className="mt-1 text-gray-500">Origin: {data.origin_city}</div>}
              {(data.min_price != null || data.max_price != null) && (
                <div className="mt-1 text-gray-500">
                  Range: ₹{data.min_price ?? "—"} – ₹{data.max_price ?? "—"}
                </div>
              )}
              {data.description && <p className="mt-2 text-gray-600">{data.description}</p>}
            </div>
          </div>
        </div>

        <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
          <h2 className="mb-3 text-sm font-semibold text-gray-900">
            {data.status === "pending" ? "Submit Quote" : "Your Quote"}
          </h2>
          {/* A real form post, so quoting survives a failed/blocked bundle. */}
          <form action={respondToEnquiry}>
            <input type="hidden" name="id" value={data.id} />
            <QuoteFieldset locked={locked}>
              <div>
                <label className="mb-1 block text-xs font-medium text-gray-600">Price (INR)</label>
                <input
                  type="number"
                  name="price"
                  min={0}
                  step="0.01"
                  required
                  defaultValue={data.price != null ? String(data.price) : ""}
                  placeholder="Enter quote price"
                  className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:border-[#CC1414] focus:outline-none disabled:bg-gray-50"
                />
              </div>
              <div>
                <label className="mb-1 block text-xs font-medium text-gray-600">Note (optional)</label>
                <textarea
                  rows={3}
                  name="note"
                  placeholder="Add optional note for this quote"
                  className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:border-[#CC1414] focus:outline-none disabled:bg-gray-50"
                />
              </div>
              {!locked && <SubmitQuoteButton label={data.status === "pending" ? "Submit quote" : "Update quote"} />}
              {locked && (
                <p className="rounded-md bg-amber-50 px-3 py-2 text-xs text-amber-700 ring-1 ring-amber-200">
                  {data.is_marked ? "This enquiry has been awarded; further changes are locked." : "This enquiry is no longer accepting changes."}
                </p>
              )}
            </QuoteFieldset>
          </form>
        </div>

        {bids.length > 0 && (
          <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-3">
            <h2 className="mb-3 text-sm font-semibold text-gray-900">Competing Bids ({bids.length})</h2>
            <ul className="divide-y divide-gray-100 text-sm">
              {bids.map((b) => (
                <li key={b.id} className="flex items-center justify-between py-2">
                  <span className="text-gray-700">Bid #{b.id}</span>
                  <span className="font-semibold text-gray-900">₹ {b.price ?? "—"}</span>
                </li>
              ))}
            </ul>
          </div>
        )}

        {Array.isArray(data.history) && data.history.length > 0 && (
          <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 lg:col-span-3">
            <h2 className="mb-3 text-sm font-semibold text-gray-900">History</h2>
            <ol className="space-y-2 text-sm">
              {data.history.map((h, i) => (
                <li key={i} className="flex items-center justify-between border-b border-gray-100 pb-2 last:border-b-0">
                  <span className="capitalize text-gray-900">
                    {String(h.status ?? "")}
                    {h.note ? ` — ${String(h.note)}` : ""}
                  </span>
                  <span className="text-xs text-gray-500">
                    {h.created_at ? formatDateTime(String(h.created_at)) : ""}
                  </span>
                </li>
              ))}
            </ol>
          </div>
        )}
      </div>
    </div>
  );
}
