"use client";

import { useId, useState, type FormEvent } from "react";
import { useQueryClient } from "@tanstack/react-query";
import {
  BedDouble,
  ChevronDown,
  CircleDollarSign,
  CornerDownLeft,
  Clock,
  Eye,
  MessageSquare,
  Plane,
  Send,
  ShieldCheck,
  Tag,
  Ticket,
  UserRound,
  XCircle,
} from "lucide-react";
import { cn } from "cn";

import type {
  MyRequestRow,
} from "@/services/employee-requests/employee-requests.types";
import { replyToRequest } from "@/services/employee-requests/employee-requests.client";
import { buildActivityTimeline } from "@/services/employee-requests/activity-timeline";
import {
  formatEnumLabel,
  formatDate,
  formatDateTime,
  formatMoney,
  tripDays,
} from "@/services/employee-requests/format";

import { ActivityTimeline } from "./ActivityTimeline";
import { PolicyChecks } from "./PolicyChecks";
import { RequestTracker } from "./RequestTracker";
import { BookedTripActions } from "./BookedTripActions";
import { SupportBadge } from "./SupportBadge";
import { TravellerList } from "./TravellerList";
import { FraBadge } from "./fra-primitives";
import {
  askedByName,
  latestReply,
  STATUS_LABEL,
  STATUS_TONE,
} from "@/services/employee-requests/request-status";

/**
 * One request on My requests.
 *
 * Collapsed it answers the three questions someone opens this page for — which
 * trip, where has it got to, and is anything waiting on me. Everything else is
 * behind View details, because a list of eight requests each showing a full
 * breakdown is a list nobody scans.
 *
 * The "More information needed" panel is NOT behind that toggle. It is the one
 * thing on the card that needs an action, and burying a question from your
 * approver one click down is how requests sit untouched for a week.
 */

export function RequestCard({
  row,
  expanded,
  onToggle,
  highlighted,
}: {
  row: MyRequestRow;
  expanded: boolean;
  onToggle: () => void;
  /** Arrived here from the submitted screen — this is the one they came to see. */
  highlighted?: boolean;
}) {
  const panelId = useId();
  const flight = row.trip.flight;
  const hotel = row.trip.hotel;
  const isHotel = row.type === "HOTEL";
  const days = tripDays(row.trip.travelStartDate, row.trip.travelEndDate);

  /**
   * The copy below is written in the second person, which stops being true the
   * moment two people are on a request. Both of them get the emails (PRD §11),
   * so "you" becomes "you both" when the reader is also the traveller, and the
   * sentences that describe an ACTION name the requester — only they can take
   * one.
   */
  const shared = row.viewerRole !== "BOTH";
  const requesterLabel = row.requester.name ?? row.requester.workEmail;

  return (
    <article
      id={`request-${row.reference}`}
      aria-labelledby={`${panelId}-title`}
      className={cn(
        "scroll-mt-24 overflow-hidden rounded-2xl border bg-[var(--fra-surface)] shadow-[var(--fra-shadow)]",
        // A left edge in the status colour, so a page of cards can be skimmed
        // for the one that needs attention without reading any of them.
        row.status === "INFO_REQUESTED"
          ? "border-l-4 border-l-[var(--fra-info-solid)]"
          : row.status === "REJECTED" || row.status === "BOOKING_FAILED" || row.status === "EXPIRED"
            ? "border-l-4 border-l-[var(--fra-rejected-solid)]"
            : row.status === "APPROVED" || row.status === "BOOKED"
              ? "border-l-4 border-l-[var(--fra-approved-solid)]"
              : "border-l-4 border-l-[var(--fra-pending)]",
        highlighted ? "border-[var(--fra-navy-2)]" : "border-[var(--fra-border)]"
      )}
    >
      <div className="p-[20px] sm:p-6">
        <div className="mb-[16px] flex flex-wrap items-center justify-between gap-[12px]">
          <h2
            id={`${panelId}-title`}
            className="flex items-center gap-2.5 text-lg font-bold text-[var(--fra-heading)]"
          >
            {isHotel ? "Hotel request" : "Flight request"} #{row.reference}
            {row.supportStatus !== "WITH_SUPPORT" && <FraBadge tone={STATUS_TONE[row.status]}>{STATUS_LABEL[row.status]}</FraBadge>}
            <SupportBadge status={row.supportStatus} reference={row.supportReference} />
            {row.priority === "URGENT" && <FraBadge tone="pending">Urgent</FraBadge>}
          </h2>
          <button
            type="button"
            onClick={onToggle}
            aria-expanded={expanded}
            aria-controls={panelId}
            className="inline-flex h-11 items-center gap-2 rounded-[var(--fra-radius-sm)] border border-[var(--fra-info-solid)] px-[16px] text-sm font-semibold text-[var(--fra-info-solid)] transition-colors hover:bg-[var(--fra-info-bg)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-info-solid)]"
          >
            {expanded ? "Hide details" : "View details"}
            <ChevronDown
              aria-hidden
              className={cn("size-4 transition-transform", expanded && "rotate-180")}
            />
          </button>
        </div>

        {/* Who this request is about, when that is not simply the reader.
            Nothing is shown on a self-request — the overwhelmingly common case
            — so the line's presence is itself the signal. */}
        {row.viewerRole !== "BOTH" && (
          <p className="mb-[16px] flex flex-wrap items-center gap-x-2 gap-y-1 text-[13px] text-[var(--fra-muted)]">
            <UserRound aria-hidden className="size-3.5 shrink-0" />
            {row.viewerRole === "REQUESTER" ? (
              <>
                <span>
                  For{" "}
                  <strong className="font-semibold text-[var(--fra-heading)]">
                    {row.traveller.name ?? row.traveller.workEmail}
                  </strong>
                </span>
                <span className="text-[var(--fra-border-strong)]">·</span>
                <span>you requested it</span>
              </>
            ) : (
              <>
                <span>
                  Booked by{" "}
                  <strong className="font-semibold text-[var(--fra-heading)]">
                    {row.requester.name ?? row.requester.workEmail}
                  </strong>
                </span>
                <span className="text-[var(--fra-border-strong)]">·</span>
                {/* States the limitation before anyone goes looking for a
                    button that is not there. */}
                <span className="inline-flex items-center gap-1">
                  <Eye aria-hidden className="size-3.5" />
                  view only
                </span>
              </>
            )}
          </p>
        )}

        <RequestTracker steps={row.tracker} />

        {/* Trip strip — the collapsed summary. */}
        <div className="grid grid-cols-1 gap-[16px] rounded-xl bg-[var(--fra-surface-2)] p-[16px] sm:grid-cols-2 lg:grid-cols-4">
          <div className="flex items-start gap-[12px] lg:col-span-1">
            <span
              aria-hidden
              className="inline-flex size-10 shrink-0 items-center justify-center rounded-xl bg-[var(--fra-navy)] text-white"
            >
              {isHotel ? <BedDouble className="size-5 text-white" /> : <Plane className="size-5 text-white" />}
            </span>
            <div className="min-w-0">
              <small className="block text-xs text-[var(--fra-muted)]">Trip details</small>
              <strong className="block text-sm font-semibold text-[var(--fra-heading)]">
                {isHotel
                  ? hotel
                    ? hotel.property
                    : "—"
                  : flight
                    ? `${flight.origin} → ${flight.destination}`
                    : "—"}
              </strong>
              <span className="block text-xs text-[var(--fra-muted)]">
                {isHotel && hotel?.location ? `${hotel.location} · ` : ""}
                {formatDate(row.trip.travelStartDate)}
                {row.trip.travelEndDate && row.trip.travelEndDate !== row.trip.travelStartDate
                  ? ` – ${formatDate(row.trip.travelEndDate)}${days ? ` (${days} day${days === 1 ? "" : "s"})` : ""}`
                  : ""}
              </span>
              {/* Who is going belongs with the trip, not in a column of its own
                  — the strip is already four across on a laptop. */}
              {row.travellers.length > 1 && (
                <span className="block text-xs font-medium text-[var(--fra-navy-2)]">
                  {row.travellers.length} travellers
                </span>
              )}
            </div>
          </div>
          <Cell label="Client" value={row.business.client || "—"} />
          <Cell label="Purpose" value={row.business.meetingType || "—"} />
          <Cell
            label="Est. cost"
            value={formatMoney(row.cost.estTotal, row.cost.currency)}
            emphasis
          />
        </div>

        {/* Anything that needs reading now, outside the details toggle. */}
        {row.infoRequest && <InfoRequestPanel row={row} />}
        {row.status === "PENDING" && latestReply(row) && (
          <Notice
            tone="info"
            icon={CornerDownLeft}
            title="Reply sent · in review"
            body={`Your reply is with ${askedByName(row) ?? "your approver"}. The request is back in their queue for a decision.`}
            quote={latestReply(row)?.message ?? null}
          />
        )}
        {row.isOpen && row.priceCheck?.changed && row.priceCheck.previousFare && (
          <Notice
            tone="info"
            icon={Tag}
            title="Fare updated since you submitted"
            body={`It was ${formatMoney(row.priceCheck.previousFare, row.priceCheck.currency)} and is now ${formatMoney(row.priceCheck.fare, row.priceCheck.currency)}. The estimate above is the current fare.`}
          />
        )}
        {row.isOpen && row.priceCheck?.status === "UNCONFIRMED" && (
          <Notice
            tone="info"
            icon={Clock}
            title="Live fare not confirmed"
            body="We could not re-check this fare with the airline just now. The estimate is from when you submitted and will be checked again when you next open this page."
          />
        )}
        {row.rejection && (
          <Notice
            tone="rejected"
            icon={XCircle}
            // The reason is the headline; the admin's optional message sits under it.
            title={row.rejection.reason ?? "Not approved"}
            body={
              row.rejection.note ??
              "Your approver did not approve this request. You can submit a new request with changes."
            }
          />
        )}
        {!row.infoRequest && !row.rejection && row.status === "BOOKED" && (
          <Notice
            tone="approved"
            icon={Ticket}
            title={isHotel ? "Confirmation issued" : "Ticket issued"}
            body={
              shared
                ? `The ${isHotel ? "hotel confirmation" : "e-ticket"} has been emailed to both of you.`
                : `Your ${isHotel ? "hotel confirmation" : "e-ticket"} has been emailed to you.`
            }
          />
        )}
        {!row.infoRequest && !row.rejection && row.status === "APPROVED" && (
          <Notice
            tone="info"
            icon={Clock}
            title="Booking in progress · Corporate Travel Team"
            body={
              shared
                ? `${row.traveller.name ?? "The traveller"}'s ${isHotel ? "stay" : "flight"} is being booked. You will both get the ${isHotel ? "confirmation" : "e-ticket"} by email.`
                : `Your ${isHotel ? "stay" : "flight"} is being booked. You will get the ${isHotel ? "confirmation" : "e-ticket"} by email.`
            }
          />
        )}
        {row.status === "BOOKING_FAILED" && (
          <Notice
            tone="rejected"
            icon={XCircle}
            title="Booking could not be completed"
            body="The travel team has been notified and will be in touch."
          />
        )}
        {/* What the requester can do about it, from the one shared status
            table — see services/employee-requests/request-actions.ts. Outside
            the details toggle on purpose: an action you have to go looking for
            is an action people do not find. */}
        <BookedTripActions row={row} />
      </div>

      <div
        id={panelId}
        hidden={!expanded}
        className="border-t border-dashed border-[var(--fra-border)] bg-[var(--fra-surface)] p-[20px] sm:p-6"
      >
        <div className="grid grid-cols-1 gap-[20px] lg:grid-cols-2">
          {isHotel ? (
            <Panel icon={BedDouble} title="Hotel">
              <Row label="Property" value={hotel?.property || "—"} />
              <Row label="Location" value={hotel?.location || "—"} />
              <Row label="Check-in" value={formatDate(hotel?.checkIn)} />
              <Row label="Check-out" value={formatDate(hotel?.checkOut)} />
              <Row label="Nights" value={hotel ? String(hotel.nights) : "—"} />
              <Row label="Room type" value={hotel?.roomType || "—"} />
            </Panel>
          ) : (
            <Panel icon={Plane} title="Flight">
              <Row label="Trip type" value={formatEnumLabel(flight?.tripType)} />
              <Row label="Cabin" value={formatEnumLabel(flight?.cabin)} />
              <Row label="Airline" value={flight?.airline || "—"} />
              <Row label="Flight number(s)" value={flight?.flightNumbers || "—"} />
              <Row label="Departs" value={formatDate(flight?.departDate)} />
              {flight?.returnDate && <Row label="Returns" value={formatDate(flight.returnDate)} />}
            </Panel>
          )}

          <Panel icon={CircleDollarSign} title="Estimated cost">
            <Row label={isHotel ? "Hotel" : "Flight"} value={formatMoney(row.cost.fare, row.cost.currency)} />
            <Row
              label="Additional"
              value={formatMoney(row.cost.additionalCost, row.cost.currency)}
            />
            <Row
              label="Total (est.)"
              value={formatMoney(row.cost.estTotal, row.cost.currency)}
              emphasis
            />
            <p className="mt-2 text-xs text-[var(--fra-muted)]">Currency: {row.cost.currency}</p>
          </Panel>

          <Panel icon={ShieldCheck} title="Business information">
            <Row label="Client" value={row.business.client || "—"} />
            <Row label="Opportunity" value={row.business.opportunity || "—"} />
            <Row label="Meeting type" value={row.business.meetingType || "—"} />
            <Row label="Submitted" value={formatDateTime(row.submittedAt)} />
          </Panel>

          <Panel icon={ShieldCheck} title="Policy check">
            {/* The list endpoint carries only the headline figures, not the
                per-rule verdicts, so this renders what it has rather than
                inventing rows. */}
            <PolicyChecks
              policy={{
                scope: "",
                inPolicy: row.policy.inPolicy,
                flagCount: row.policy.flagCount,
                checks: [],
              }}
            />
          </Panel>
        </div>

        {row.travellers.length > 0 && (
          <div className="mt-[20px] border-t border-dashed border-[var(--fra-border)] pt-[20px]">
            <TravellerList travellers={row.travellers} travellerIsViewer={row.traveller.isViewer} />
          </div>
        )}

        <div className="mt-[20px] border-t border-dashed border-[var(--fra-border)] pt-[20px]">
          <h3 className="mb-[16px] flex items-center gap-2 text-[15px] font-bold text-[var(--fra-heading)]">
            <Clock aria-hidden className="size-4 text-[var(--fra-navy-2)]" />
            Activity
          </h3>
          <ActivityTimeline
            items={buildActivityTimeline({
              viewer: "employee",
              status: row.status,
              submittedAt: row.submittedAt,
              activity: row.activity,
              askedBy: row.infoRequest?.askedBy ?? null,
            })}
          />
        </div>

        {row.relatedRequests.length > 0 && (
          <div className="mt-[20px] border-t border-dashed border-[var(--fra-border)] pt-[16px]">
            <h3 className="mb-2 text-[13px] font-bold text-[var(--fra-heading)]">
              Related requests
            </h3>
            <ul className="m-0 list-none space-y-1 p-0">
              {row.relatedRequests.map((rel) => (
                <li key={rel.id} className="text-[13px] text-[var(--fra-muted)]">
                  <strong className="text-[var(--fra-text)]">#{rel.reference}</strong> ·{" "}
                  {rel.kind.toLowerCase()} · {STATUS_LABEL[rel.status] ?? rel.status}
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </article>
  );
}

const REPLY_MAX = 5000;

/**
 * The approver's question, with the reply box.
 *
 * Sending the reply resubmits the request: the server returns it to PENDING,
 * so this panel goes away on the next refetch and the card shows "Awaiting
 * approval" again. The query is invalidated on success rather than patched
 * locally, so the card always reflects what the server stored.
 */
function InfoRequestPanel({ row }: { row: MyRequestRow }) {
  const info = row.infoRequest!;
  const queryClient = useQueryClient();
  const [reply, setReply] = useState("");
  const [sending, setSending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const trimmed = reply.trim();

  const send = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!trimmed || sending) return;
    setSending(true);
    setError(null);
    const res = await replyToRequest(row.id, trimmed);
    setSending(false);
    if (!res.success) {
      setError(res.message ?? "Your reply could not be sent. Please try again.");
      return;
    }
    setReply("");
    await queryClient.invalidateQueries({ queryKey: ["employee-requests", "mine"] });
  };

  const viewerCanReply = row.canAct;

  return (
    <section className="mt-[16px] flex gap-3.5 rounded-xl bg-[var(--fra-info-bg)] p-[16px]">
      <span
        aria-hidden
        className="inline-flex size-10 shrink-0 items-center justify-center rounded-full bg-[var(--fra-info-solid)] text-white"
      >
        <MessageSquare className="size-5" />
      </span>
      <div className="min-w-0 flex-1">
        <h3 className="m-0 mb-0.5 text-[17px] font-bold text-[var(--fra-heading)]">
          More information needed
        </h3>
        <p className="m-0 text-sm text-[var(--fra-text)]">
          {info.askedBy ?? "Your approver"} asked a question before approving
          {viewerCanReply ? "." : ` ${row.requester.name ?? "the requester"}'s request.`}
        </p>
        <blockquote className="mt-2.5 rounded-[10px] border-l-[3px] border-[var(--fra-info-solid)] bg-[var(--fra-surface)] px-[12px] py-2.5 text-sm text-[var(--fra-text)]">
          {info.message}
          <small className="mt-1 block text-xs text-[var(--fra-muted)]">
            {formatDateTime(info.askedAt)}
          </small>
        </blockquote>
        {/*
         * Only the requester may answer. `canAct` is the server's word for it
         * (`isRequester`), and `POST /requests/:id/reply` refuses anyone else —
         * so a traveller shown this form could type a reply, press the button
         * and be told nothing happened. It used to render for them, with
         * `viewerCanReply` switching only the sentence above; LEIS-1013 made it
         * gate the form itself and say who CAN answer instead.
         */}
        {!viewerCanReply ? (
          <p className="mt-3 mb-0 text-[13px] text-[var(--fra-muted)]">
            Only{" "}
            <strong className="font-semibold text-[var(--fra-heading)]">
              {row.requester.name ?? row.requester.workEmail}
            </strong>{" "}
            can answer this — they raised the request.
          </p>
        ) : (
          <form onSubmit={send} className="mt-3 space-y-2.5">
            <label
              htmlFor={`reply-${row.id}`}
              className="block text-[13px] font-semibold text-[var(--fra-heading)]"
            >
              Your reply
            </label>
            <textarea
              id={`reply-${row.id}`}
              value={reply}
              onChange={(e) => setReply(e.target.value)}
              maxLength={REPLY_MAX}
              rows={3}
              disabled={sending}
              placeholder="Answer the question so your approver can decide."
              className="w-full resize-y rounded-[10px] border border-[var(--fra-border-strong)] bg-[var(--fra-surface)] px-3 py-2.5 text-sm text-[var(--fra-text)] placeholder:text-[var(--fra-muted)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-info-solid)]"
            />
            {error && (
              <p role="alert" className="m-0 text-[13px] text-[var(--fra-rejected-solid)]">
                {error}
              </p>
            )}
            <div className="flex flex-wrap items-center justify-between gap-3">
              <span className="text-xs text-[var(--fra-muted)]">
                Sending resubmits the request to {info.askedBy ?? "your approver"}.
              </span>
              <button
                type="submit"
                disabled={!trimmed || sending}
                className="inline-flex h-11 items-center gap-2 rounded-[var(--fra-radius-sm)] bg-[var(--fra-info-solid)] px-[16px] text-sm font-semibold text-white transition-colors hover:bg-[var(--fra-info-hover)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-info-solid)] disabled:cursor-not-allowed disabled:opacity-50"
              >
                <Send aria-hidden className="size-4" />
                {sending ? "Sending…" : "Send reply & resubmit"}
              </button>
            </div>
          </form>
        )}
      </div>
    </section>
  );
}

/** Who asked the question most recently, from the thread. */

function Notice({
  tone,
  icon: Icon,
  title,
  body,
  quote,
}: {
  tone: "approved" | "rejected" | "info";
  icon: typeof Ticket;
  title: string;
  body: string;
  quote?: string | null;
}) {
  const bg = {
    approved: "bg-[var(--fra-approved-bg)]",
    rejected: "bg-[var(--fra-rejected-bg)]",
    info: "bg-[var(--fra-info-bg)]",
  }[tone];
  const dot = {
    approved: "bg-[var(--fra-approved-solid)]",
    rejected: "bg-[var(--fra-rejected-solid)]",
    info: "bg-[var(--fra-info-solid)]",
  }[tone];
  return (
    <section className={cn("mt-[16px] flex gap-3.5 rounded-xl p-[16px]", bg)}>
      <span
        aria-hidden
        className={cn(
          "inline-flex size-10 shrink-0 items-center justify-center rounded-full text-white",
          dot
        )}
      >
        <Icon className="size-5" />
      </span>
      <div className="min-w-0">
        <h3 className="m-0 mb-0.5 text-[15px] font-bold text-[var(--fra-heading)]">{title}</h3>
        <p className="m-0 text-sm text-[var(--fra-text)]">{body}</p>
        {quote && (
          <blockquote className="mt-2 rounded-[10px] border-l-[3px] border-current bg-[var(--fra-surface)] px-[12px] py-2 text-sm text-[var(--fra-text)]">
            {quote}
          </blockquote>
        )}
      </div>
    </section>
  );
}

function Cell({ label, value, emphasis }: { label: string; value: string; emphasis?: boolean }) {
  return (
    <div className="min-w-0">
      <small className="block text-xs text-[var(--fra-muted)]">{label}</small>
      <strong
        className={cn(
          "block truncate font-semibold text-[var(--fra-heading)]",
          emphasis ? "text-lg" : "text-sm"
        )}
      >
        {value}
      </strong>
    </div>
  );
}

function Panel({
  icon: Icon,
  title,
  children,
}: {
  icon: typeof Plane;
  title: string;
  children: React.ReactNode;
}) {
  return (
    <section className="rounded-xl border border-[var(--fra-border)] p-[16px]">
      <h3 className="mb-[12px] flex items-center gap-2 text-[15px] font-bold text-[var(--fra-heading)]">
        <Icon aria-hidden className="size-4 text-[var(--fra-navy-2)]" />
        {title}
      </h3>
      <dl className="m-0">{children}</dl>
    </section>
  );
}

function Row({ label, value, emphasis }: { label: string; value: string; emphasis?: boolean }) {
  return (
    <div className="flex items-baseline justify-between gap-[16px] py-1.5">
      <dt className="text-[13px] text-[var(--fra-muted)]">{label}</dt>
      <dd
        className={cn(
          "text-right font-semibold text-[var(--fra-heading)]",
          emphasis ? "text-base" : "text-[13px]"
        )}
      >
        {value}
      </dd>
    </div>
  );
}
