"use client";

import { useEffect, useMemo } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { Check, Clock, Eye, Hash, HelpCircle, Plus, User } from "lucide-react";

import { getMyRequests } from "@/services/employee-requests/employee-requests.client";
import type { SubmittedRequest } from "@/services/employee-requests/employee-requests.types";
import { formatDateTime, formatMoney } from "@/services/employee-requests/format";
import { parseReceipt } from "@/services/employee-requests/submitted-handoff";

import { PolicyChecks } from "./PolicyChecks";
import { RequestStepper, requestSteps } from "./RequestStepper";
import { TravellerList } from "./TravellerList";
import { useBusinessSessionReady, useBusinessToken, useReceiptJson } from "./use-session";
import { FraBadge, fraButton } from "./fra-primitives";

/**
 * Step 2 — the receipt.
 *
 * Rendered from the submit response, which the overlay put in sessionStorage.
 * That is not a shortcut: **there is no `GET /business/requests/:id`**, and the
 * submit deliberately returns everything this screen shows precisely so it
 * needs no follow-up call. The justification and the per-rule policy verdict
 * exist nowhere else the employee can reach.
 *
 * On a cold load — a reload, a pasted link, a tab restored past the receipt's
 * lifetime — it falls back to the list endpoint and matches on reference. That
 * recovers everything except the justification, which the list card does not
 * carry, so the summary drops that row rather than showing it empty.
 *
 * Storage is read through useSyncExternalStore rather than an effect, so the
 * receipt is there on the first client render instead of after a flash of
 * "loading", and the fallback fetch is a query rather than hand-rolled state.
 */

export function SubmittedView() {
  const router = useRouter();
  const reference = useSearchParams().get("ref");

  const token = useBusinessToken();
  // See useBusinessSessionReady: without this gate a cold load redirects a
  // signed-in employee to sign-in, because the token cannot be read until
  // hydration has handed over.
  const sessionReady = useBusinessSessionReady();
  const receiptJson = useReceiptJson(reference);
  const receipt = useMemo(() => parseReceipt(receiptJson), [receiptJson]);

  // A redirect is a genuine side effect, so it stays in an effect — but it no
  // longer sets any state, which is what made the old version cascade.
  useEffect(() => {
    if (sessionReady && token === null) {
      router.replace("/employee-login?next=/employee-requests");
    }
  }, [sessionReady, token, router]);

  // Only runs when the receipt is gone. React Query owns the loading and error
  // states so this component holds none of its own.
  const fallback = useQuery({
    queryKey: ["employee-requests", "mine"],
    queryFn: async () => {
      const res = await getMyRequests({ tab: "all", limit: 100 });
      if (!res.success) throw new Error(res.message ?? "Could not load your requests.");
      return res.data!;
    },
    enabled: Boolean(token) && Boolean(reference) && !receipt,
    refetchOnWindowFocus: false,
  });

  const rebuilt = useMemo<SubmittedRequest | null>(() => {
    const row = fallback.data?.data.find((r) => r.reference === reference);
    if (!row) return null;
    // `justification` is genuinely absent from a list card, so it is left empty
    // and the summary omits that row — better than an em dash, which reads as
    // "they did not write one".
    return {
      id: row.id,
      reference: row.reference,
      type: row.type,
      kind: row.kind,
      status: row.status,
      priority: row.priority,
      submittedAt: row.submittedAt,
      employee: { name: row.traveller.name, workEmail: row.traveller.workEmail },
      // Carried through the cold-load path too: without these the rebuilt
      // screen would call a colleague's trip the viewer's own.
      traveller: { name: row.traveller.name, workEmail: row.traveller.workEmail },
      requester: { name: row.requester.name, workEmail: row.requester.workEmail },
      isColleagueRequest: row.viewerRole !== "BOTH",
      trip: row.trip.flight,
      business: {
        meetingType: row.business.meetingType ?? "",
        client: row.business.client,
        opportunity: row.business.opportunity,
        justification: "",
      },
      cost: row.cost,
      travellers: row.travellers ?? [],
      policy: {
        scope: "",
        inPolicy: row.policy.inPolicy,
        flagCount: row.policy.flagCount,
        checks: [],
      },
      warnings: [],
    };
  }, [fallback.data, reference]);

  const request = receipt ?? rebuilt;
  const partial = !receipt && Boolean(rebuilt);
  const loading = Boolean(reference) && !request && (fallback.isPending || fallback.isFetching);

  const reviewHref = reference
    ? `/employee-requests?id=${encodeURIComponent(reference)}`
    : "/employee-requests";

  if (loading) {
    return (
      <div className="mx-auto max-w-4xl px-[16px] py-10" aria-live="polite" aria-busy="true">
        <span className="sr-only">Loading your request…</span>
        <div className="h-20 animate-pulse rounded-2xl bg-[var(--fra-surface-2)] motion-reduce:animate-none" />
        <div className="mt-[16px] h-96 animate-pulse rounded-2xl bg-[var(--fra-surface-2)] motion-reduce:animate-none" />
      </div>
    );
  }

  if (!request) {
    return (
      <div className="mx-auto max-w-4xl px-[16px] py-10">
        <RequestStepper steps={requestSteps(reviewHref)} current={2} className="mb-6" />
        <div className="rounded-2xl border border-[var(--fra-border)] bg-[var(--fra-surface)] p-8 text-center shadow-[var(--fra-shadow)]">
          <span
            aria-hidden
            className="mx-auto mb-[16px] flex size-16 items-center justify-center rounded-full bg-[var(--fra-surface-2)] text-[var(--fra-muted)]"
          >
            <HelpCircle className="size-8" />
          </span>
          <h1 className="text-2xl font-bold text-[var(--fra-heading)]">
            We could not find that request
          </h1>
          <p className="mx-auto mt-2 max-w-md text-sm text-[var(--fra-muted)]">
            It may have been submitted in another browser or a while ago. All of your requests are
            listed under My requests.
          </p>
          <div className="mt-6 flex flex-wrap justify-center gap-[12px]">
            <Link href="/employee-requests" className={fraButton.primary}>
              <Eye aria-hidden className="size-4 text-white" />
              See my requests
            </Link>
            <Link href="/srp/flights" className={fraButton.ghost}>
              <Plus aria-hidden className="size-4" />
              Request another flight
            </Link>
          </div>
        </div>
      </div>
    );
  }

  const summary: Array<[string, string]> = [
    ["Meeting type", request.business.meetingType || "—"],
    ["Client", request.business.client || "—"],
    ...(request.business.opportunity
      ? ([["Opportunity", request.business.opportunity]] as Array<[string, string]>)
      : []),
    ...(partial
      ? []
      : ([["Justification", request.business.justification || "—"]] as Array<[string, string]>)),
    ...(request.travellers.length > 1
      ? ([["Travellers", `${request.travellers.length} people`]] as Array<[string, string]>)
      : []),
    ["Total (est.)", formatMoney(request.cost.estTotal, request.cost.currency)],
  ];

  return (
    <div className="mx-auto max-w-4xl px-[16px] py-8 sm:py-10">
      <RequestStepper steps={requestSteps(reviewHref)} current={2} className="mb-6" />

      <div className="rounded-2xl border border-[var(--fra-border)] bg-[var(--fra-surface)] p-6 shadow-[var(--fra-shadow)] sm:p-8">
        <div className="text-center">
          <span
            aria-hidden
            className="mx-auto mb-[20px] flex size-16 items-center justify-center rounded-full bg-[var(--fra-approved-solid)] text-white"
          >
            <Check className="size-9" strokeWidth={3} />
          </span>
          {/* The one h1 on the page, and it names the thing that just happened —
              the reference is what the employee quotes to their approver. */}
          <h1 className="text-[26px] font-bold text-[var(--fra-heading)] sm:text-3xl">
            Request {request.reference} submitted
          </h1>
          <p className="mx-auto mt-2 max-w-lg text-sm text-[var(--fra-muted)]">
            {request.status === "BOOKED"
              ? request.type === "HOTEL"
                ? "This stay has been booked and the confirmation is issued. A confirmation email is on its way."
                : "This flight has been booked and the ticket is issued. A confirmation email is on its way."
              : request.isColleagueRequest && request.traveller?.name
                ? `${request.traveller.name}'s ${request.type === "HOTEL" ? "hotel" : "flight"} request has been sent for manager approval. You will both get an email when there is a decision.`
                : `Your ${request.type === "HOTEL" ? "hotel" : "flight"} request has been sent for manager approval. You will get an email when there is a decision.`}
          </p>

          <div className="mt-[20px] flex flex-wrap items-center justify-center gap-2">
            <Pill icon={Hash} label="Reference">
              {request.reference}
            </Pill>
            {/* The traveller first — it is their trip. "Requested by" only
                appears when that is somebody else, so a self-request's chips
                are unchanged. */}
            {(request.traveller?.name ?? request.employee.name) && (
              <Pill icon={User} label={request.isColleagueRequest ? "Traveller" : "Requested by"}>
                {request.traveller?.name ?? request.employee.name}
              </Pill>
            )}
            {request.isColleagueRequest && request.requester?.name && (
              <Pill icon={User} label="Requested by">
                {request.requester.name}
              </Pill>
            )}
            <Pill icon={Clock} label="Submitted">
              {formatDateTime(request.submittedAt)}
            </Pill>
            <FraBadge tone={request.status === "PENDING" ? "pending" : "approved"}>
              {request.status === "PENDING"
                ? "Awaiting approval"
                : request.status === "BOOKED"
                  ? "Booked"
                  : request.status}
            </FraBadge>
          </div>
        </div>

        <dl className="mt-7 rounded-xl border border-[var(--fra-border)] bg-[var(--fra-surface-2)] px-[16px] py-2 sm:px-5">
          {summary.map(([label, value], i) => (
            <div
              key={label}
              className={`flex flex-col gap-1 py-[12px] sm:flex-row sm:items-start sm:justify-between sm:gap-6 ${
                i > 0 ? "border-t border-[var(--fra-border)]" : ""
              }`}
            >
              <dt className="shrink-0 text-[13px] text-[var(--fra-muted)]">{label}</dt>
              <dd className="text-sm font-semibold text-[var(--fra-heading)] sm:max-w-[32rem] sm:text-right">
                {value}
              </dd>
            </div>
          ))}
        </dl>

        {request.travellers.length > 0 && (
          <div className="mt-7 border-t border-dashed border-[var(--fra-border)] pt-6">
            <TravellerList
              travellers={request.travellers}
              travellerIsViewer={!request.isColleagueRequest}
            />
          </div>
        )}

        {request.policy.checks.length > 0 && (
          <div className="mt-7 border-t border-dashed border-[var(--fra-border)] pt-6">
            <h2 className="mb-[12px] text-[15px] font-bold text-[var(--fra-heading)]">
              Policy check
            </h2>
            <PolicyChecks policy={request.policy} warnings={request.warnings} />
          </div>
        )}

        <div className="mt-7 flex flex-wrap justify-center gap-[12px]">
          <Link href={reviewHref} className={fraButton.primary}>
            <Eye aria-hidden className="size-4 text-white" />
            View request status
          </Link>
          <Link href={request.type === "HOTEL" ? "/srp/hotels" : "/srp/flights"} className={fraButton.ghost}>
            <Plus aria-hidden className="size-4" />
            Request another {request.type === "HOTEL" ? "hotel" : "flight"}
          </Link>
        </div>
      </div>
    </div>
  );
}

function Pill({
  icon: Icon,
  label,
  children,
}: {
  icon: typeof Hash;
  label: string;
  children: React.ReactNode;
}) {
  return (
    <span className="inline-flex items-center gap-1.5 rounded-full bg-[var(--fra-surface-2)] px-[12px] py-1.5 text-[13px] text-[var(--fra-text)]">
      <Icon aria-hidden className="size-3.5 text-[var(--fra-muted)]" />
      <span className="sr-only">{label}: </span>
      {children}
    </span>
  );
}
