"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { AlertTriangle, Plus, RefreshCw } from "lucide-react";
import { cn } from "cn";

import type { MyRequestsTab } from "@/services/employee-requests/employee-requests.types";

import { RequestCard } from "./RequestCard";
import { useBusinessSessionReady, useBusinessToken } from "./use-session";
import { RequestStepper, requestSteps } from "./RequestStepper";
import { fraButton } from "./fra-primitives";
import { useMyRequests } from "@/services/employee-requests/useMyRequests";

/**
 * Step 3 — My requests.
 *
 * One fetch of `tab=all` drives all three tabs. The contract supports this
 * explicitly: every row carries `isOpen`, and `meta.counts` is computed
 * *ignoring* `tab`, so the numbers beside All / Open / Closed hold still while
 * the user moves between them. Filtering in the browser also makes switching
 * instant rather than a round trip each time, and means the counts and the rows
 * can never be one response out of step with each other.
 *
 * Note which side of the line "approved" falls on: from the employee's point of
 * view an approved request is **Closed** — there is nothing left for them to do
 * — and the server's `isOpen` says so. This renders that flag rather than
 * re-deciding it.
 */

const TABS: Array<{ key: MyRequestsTab; label: string }> = [
  { key: "all", label: "All" },
  { key: "open", label: "Open" },
  { key: "closed", label: "Closed" },
];

export function MyRequestsView() {
  const router = useRouter();
  const params = useSearchParams();
  const focusRef = params.get("id");

  const [tab, setTab] = useState<MyRequestsTab>("all");
  /*
   * Every card starts closed, except one named by `?id=`.
   *
   * That parameter used to only scroll. It is now also how the home page's
   * short cards hand over (LEIS-1016) — "open this request to reply" has to
   * actually open it, or the reader lands on a collapsed card and has to find
   * the question themselves.
   *
   * Seeded in the initial state rather than set from an effect: `focusRef` is
   * known on the first render, and a `setExpanded` inside a `useEffect` is the
   * shape `react-hooks/set-state-in-effect` exists to catch.
   */
  const [expanded, setExpanded] = useState<Set<string>>(() => new Set(focusRef ? [focusRef] : []));
  const scrolledTo = useRef<string | null>(null);

  // Read as an external store, so there is no "checking…" render and no
  // setState inside an effect. The redirect below is a real side effect and
  // stays in one; it sets nothing.
  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();
  useEffect(() => {
    if (sessionReady && token === null) {
      router.replace("/employee-login?next=/employee-requests");
    }
  }, [sessionReady, token, router]);

  // Shared with the home page's "Your recent requests" (LEIS-1016), which has
  // to sit on the same cache entry — `RequestCard`'s reply invalidates this
  // key by name. See the hook's own comment.
  const { data, isPending, isError, refetch, isFetching } = useMyRequests();

  const rows = useMemo(() => {
    const all = data?.data ?? [];
    if (tab === "open") return all.filter((r) => r.isOpen);
    if (tab === "closed") return all.filter((r) => !r.isOpen);
    return all;
  }, [data, tab]);

  const counts = data?.meta.counts ?? { all: 0, open: 0, closed: 0 };

  // Arriving from the submitted screen: bring that card into view, once. The
  // card is already expanded (seeded above); this only scrolls. Guarded by a
  // ref so a tab change or a refetch does not yank the page back to it while
  // someone is reading something else.
  useEffect(() => {
    if (!focusRef || !data || scrolledTo.current === focusRef) return;
    if (!data.data.some((r) => r.reference === focusRef)) return;
    scrolledTo.current = focusRef;
    requestAnimationFrame(() => {
      const el = document.getElementById(`request-${focusRef}`);
      if (!el) return;
      const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
      el.scrollIntoView({ behavior: reduced ? "auto" : "smooth", block: "start" });
    });
  }, [focusRef, data]);

  const toggle = useCallback((reference: string) => {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(reference)) next.delete(reference);
      else next.add(reference);
      return next;
    });
  }, []);

  return (
    <div className="mx-auto max-w-5xl px-[16px] py-8 sm:py-10">
      <header className="mb-6 rounded-2xl bg-[linear-gradient(120deg,var(--fra-navy)_0%,var(--fra-navy-2)_100%)] p-6 text-white sm:p-8">
        <p className="text-xs tracking-wide text-white/70 uppercase">Corporate travel</p>
        <div className="mt-2 flex flex-wrap items-start justify-between gap-[16px]">
          <div className="min-w-0">
            {/* `text-white` restated here, not just inherited from <header>
                (LEIS-1046): leisure-new-style.css has an unscoped
                `* { color: var(--color-content) }` (#474646), and React's
                `precedence` keeps that sheet in <head> for the rest of the
                session once any /srp route has mounted it. A rule that matches
                the h1 directly beats a colour inherited from its parent, so the
                title rendered mid-grey on the navy band. Every other line in
                this hero already carries its own `text-white/NN`. */}
            <h1 className="text-[26px] font-bold text-white sm:text-3xl">My requests</h1>
            <p className="mt-1 max-w-xl text-sm text-white/80">
              Track the flights you have requested and the ones booked for you, read your
              approver&rsquo;s notes, and see where each trip has got to.
            </p>
          </div>
          <Link href="/srp/flights" className={`${fraButton.primary} shrink-0`}>
            <Plus aria-hidden className="size-4" />
            Request travel booking
          </Link>
        </div>
      </header>

      <RequestStepper steps={requestSteps("/employee-requests")} current={3} className="mb-6" />

      <div className="mb-[20px] flex flex-wrap items-center justify-between gap-[12px]">
        <div
          role="tablist"
          aria-label="Filter requests"
          className="inline-flex gap-1 rounded-xl border border-[var(--fra-border)] bg-[var(--fra-surface)] p-1"
        >
          {TABS.map(({ key, label }) => (
            <button
              key={key}
              role="tab"
              type="button"
              aria-selected={tab === key}
              onClick={() => setTab(key)}
              className={cn(
                "inline-flex h-10 items-center gap-2 rounded-lg px-[16px] text-sm font-semibold transition-colors",
                "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-coral)]",
                tab === key
                  ? "bg-[var(--fra-navy-2)] text-white"
                  : "text-[var(--fra-muted)] hover:bg-[var(--fra-hover)]"
              )}
            >
              {label}
              <span
                className={cn(
                  // `text-inherit`: the vendor sheet's `* { color }` (when it is loaded)
                  // sets a dark grey on this span directly, so without this the count
                  // on the active tab is dark-on-navy instead of white.
                  "rounded-full px-1.5 text-xs text-inherit",
                  tab === key ? "bg-white/20" : "bg-[var(--fra-surface-2)]"
                )}
              >
                {counts[key]}
              </span>
            </button>
          ))}
        </div>

        <button
          type="button"
          onClick={() => void refetch()}
          disabled={isFetching}
          className="inline-flex h-10 items-center gap-2 rounded-lg px-[12px] text-sm font-medium text-[var(--fra-muted)] transition-colors hover:text-[var(--fra-text)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-coral)] disabled:opacity-50"
        >
          <RefreshCw
            aria-hidden
            className={cn("size-4", isFetching && "animate-spin motion-reduce:animate-none")}
          />
          {isFetching ? "Refreshing…" : "Refresh"}
        </button>
      </div>

      <div aria-live="polite" aria-busy={isPending}>
        {isPending && (
          <>
            <span className="sr-only">Loading your requests…</span>
            <div className="grid gap-[16px]">
              {[0, 1, 2].map((i) => (
                <div
                  key={i}
                  aria-hidden
                  className="h-64 animate-pulse rounded-2xl border border-[var(--fra-border)] bg-[var(--fra-surface-2)] motion-reduce:animate-none"
                />
              ))}
            </div>
          </>
        )}

        {isError && (
          <div className="rounded-2xl border border-[var(--fra-border)] bg-[var(--fra-surface)] p-8 text-center">
            <AlertTriangle
              aria-hidden
              className="mx-auto mb-[12px] size-8 text-[var(--fra-rejected)]"
            />
            <h2 className="text-lg font-bold text-[var(--fra-heading)]">
              We could not load your requests
            </h2>
            <p className="mx-auto mt-1 max-w-sm text-sm text-[var(--fra-muted)]">
              Nothing has been lost — this is a problem reaching the server.
            </p>
            <button
              type="button"
              onClick={() => void refetch()}
              className={`${fraButton.ghost} mt-[20px]`}
            >
              <RefreshCw aria-hidden className="size-4" />
              Try again
            </button>
          </div>
        )}

        {!isPending && !isError && rows.length === 0 && (
          <div className="rounded-2xl border border-dashed border-[var(--fra-border-strong)] bg-[var(--fra-surface)] p-10 text-center">
            <h2 className="text-lg font-bold text-[var(--fra-heading)]">
              {counts.all === 0
                ? "No requests yet"
                : tab === "open"
                  ? "Nothing is waiting on anyone"
                  : "Nothing closed yet"}
            </h2>
            <p className="mx-auto mt-1 max-w-sm text-sm text-[var(--fra-muted)]">
              {counts.all === 0
                ? "Find a flight and send it to your approver — it will show up here with its status."
                : tab === "open"
                  ? // "you have made" is no longer the whole list: a trip a
                    // colleague arranged for you sits here too (LEIS-934).
                    "Every request here has been decided. They are under Closed."
                  : "These requests are all still in progress. They are under Open."}
            </p>
            {counts.all === 0 && (
              <Link href="/srp/flights" className={`${fraButton.primary} mt-[20px]`}>
                <Plus aria-hidden className="size-4" />
                Request travel booking
              </Link>
            )}
          </div>
        )}

        {!isPending && !isError && rows.length > 0 && (
          <div className="grid gap-[16px]">
            {rows.map((row) => (
              <RequestCard
                key={row.id}
                row={row}
                expanded={expanded.has(row.reference)}
                onToggle={() => toggle(row.reference)}
                highlighted={row.reference === focusRef}
              />
            ))}
          </div>
        )}

        {/* The fetch asks for 100; say so rather than silently truncating. */}
        {data && data.meta.total > data.data.length && (
          <p className="mt-[20px] text-center text-[13px] text-[var(--fra-muted)]">
            Showing the {data.data.length} most recent of {data.meta.total} requests.
          </p>
        )}
      </div>
    </div>
  );
}
