"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";

import { getMyRequests } from "@/services/employee-requests/employee-requests.client";
import type { MyRequestRow } from "@/services/employee-requests/employee-requests.types";

import { MyTripsCard } from "./MyTripsCard";
import { useBusinessSessionReady, useBusinessToken } from "./use-session";

/**
 * LEIS-1022 — My Trips, styled like leisure-ui's own personal-mode My Trips
 * (components/trips/TripTabs.tsx + TripCard.tsx/FlightTripCard.tsx in
 * leisure-ui.com): the same booking-type pill row, the same Bootstrap
 * nav-pills status tabs, the same card chrome — ported to Business-mode's
 * MyRequestRow data and narrowed to Upcoming/Completed/Cancelled, since
 * Pending and Pending Review (leisure-ui's other two tabs) describe requests
 * still in the approval pipeline, which stay on My requests here. Each
 * card's CTA now navigates to app/booking-details/page.tsx, same as
 * leisure-ui's own cards do — see that page's doc comment.
 */

type TripType = "FLIGHT" | "HOTEL";
type TripStatusTab = "upcoming" | "completed" | "cancelled";

const STATUS_TABS: Array<{ key: TripStatusTab; label: string; icon: string }> = [
  { key: "upcoming", label: "Upcoming", icon: "bi-briefcase" },
  { key: "completed", label: "Completed", icon: "bi-calendar-check" },
  { key: "cancelled", label: "Cancelled", icon: "bi-ban" },
];

function todayIso(): string {
  return new Date().toISOString().slice(0, 10);
}

function isTrip(row: MyRequestRow): boolean {
  return row.status === "BOOKED" || row.status === "CANCELLED";
}

function tripStatusTab(row: MyRequestRow, today: string): TripStatusTab {
  if (row.status === "CANCELLED") return "cancelled";
  const end = row.trip.travelEndDate ?? row.trip.travelStartDate;
  return end && end < today ? "completed" : "upcoming";
}

export function MyTripsView() {
  const router = useRouter();

  const [typeTab, setTypeTab] = useState<TripType | null>(null);
  const [statusTab, setStatusTab] = useState<TripStatusTab>("upcoming");

  const token = useBusinessToken();
  const sessionReady = useBusinessSessionReady();
  useEffect(() => {
    if (sessionReady && token === null) {
      router.replace("/employee-login?next=/my-trips");
    }
  }, [sessionReady, token, router]);

  const { data, isPending, isFetching } = 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 trips.");
      return res.data!;
    },
    enabled: Boolean(token),
    refetchOnWindowFocus: false,
    staleTime: 30_000,
  });

  const trips = useMemo(() => (data?.data ?? []).filter(isTrip), [data]);

  const types = useMemo(() => {
    const present = new Set(trips.map((r) => r.type));
    return (["HOTEL", "FLIGHT"] as const).filter((t) => present.has(t));
  }, [trips]);

  useEffect(() => {
    if (typeTab && types.includes(typeTab)) return;
    setTypeTab(types[0] ?? null);
  }, [types, typeTab]);

  const today = todayIso();
  const rows = useMemo(() => {
    if (!typeTab) return [];
    return trips.filter((r) => r.type === typeTab && tripStatusTab(r, today) === statusTab);
  }, [trips, typeTab, statusTab, today]);

  const typeLabel = typeTab === "FLIGHT" ? "flight" : "hotel";
  const loading = isPending || isFetching;

  // Nothing at all: no type row, no status tabs, one honest empty state —
  // leisure-ui's own TripTabs makes the same call for the same reason.
  if (!loading && trips.length === 0) {
    return (
      <PageShell>
        <div className="allTripTab py-3 px-4">
          <EmptyState
            title="You have no trips yet"
            description="Once a request is booked or cancelled, it shows up here. Still waiting on approval? Find it on My requests."
          />
        </div>
      </PageShell>
    );
  }

  return (
    <PageShell>
      <div className="allTripTab">
        {/* Booking type row — leisure-ui's own pill buttons, only the types
            the traveller actually has trips for. */}
        {types.length > 1 && (
          <div
            className="d-flex gap-2 px-md-3 pt-3 pb-2 justify-content-sm-start justify-content-center"
            role="tablist"
            aria-label="Booking type"
          >
            {types.map((type) => (
              <button
                key={type}
                type="button"
                className={`buttons rounded-2 px-4 py-2 text-sm text-uppercase fw-600 ${
                  typeTab === type ? "btnColor-first" : "border bg-transparent color-text-black"
                }`}
                onClick={() => setTypeTab(type)}
                aria-selected={typeTab === type}
                role="tab"
              >
                {type === "HOTEL" ? "Hotels" : "Flights"}
              </button>
            ))}
          </div>
        )}

        {/* Status tabs — Bootstrap nav-pills, same as leisure-ui's own. */}
        <ul className="nav nav-pills px-md-3 pt-2 shadow-sm justify-content-sm-start justify-content-center" role="tablist">
          {STATUS_TABS.map((tab) => (
            <li key={tab.key} className={`nav-item ${tab.key}`} role="presentation">
              <button
                className={`nav-link d-flex align-items-center ${statusTab === tab.key ? "active" : ""}`}
                type="button"
                role="tab"
                onClick={() => setStatusTab(tab.key)}
                aria-selected={statusTab === tab.key}
              >
                <i className={`me-2 bi ${tab.icon} iconSize-20`} aria-hidden="true" />
                {tab.label}
              </button>
            </li>
          ))}
        </ul>

        <div className="tab-content py-3 px-4">
          {loading ? (
            <TripCardSkeleton count={3} />
          ) : rows.length === 0 ? (
            <EmptyState
              title={`Looks empty, you've no ${statusTab} ${typeLabel} trips.`}
              description={`Looks like you don't have any ${statusTab} ${typeLabel} trips.`}
            />
          ) : (
            rows.map((row) => <MyTripsCard key={row.id} row={row} />)
          )}
        </div>
      </div>
    </PageShell>
  );
}

/** Mirrors leisure-ui's own page.tsx + BreadcrumbsBar shell: a bare section/
 *  container/row/col wrapper plus a "Home / My Trips" breadcrumb, the one
 *  piece of chrome TripTabs itself doesn't own — leisure-ui splits it into
 *  page.tsx, this inlines it since there's no separate page component here. */
function PageShell({ children }: { children: React.ReactNode }) {
  return (
    <section className="pt-0 booking-detail-listing-section travelContent">
      <div className="container webNewContent">
        <nav aria-label="Breadcrumb" className="leisure-breadcrumb mb-3 pt-3">
          <ol className="breadcrumb leisure-breadcrumb__list mb-0">
            <li className="breadcrumb-item">
              <Link href="/" className="leisure-breadcrumb__link">
                <span className="leisure-breadcrumb__label">Home</span>
              </Link>
            </li>
            <li className="breadcrumb-item active" aria-current="page">
              <span className="leisure-breadcrumb__label">My Trips</span>
            </li>
          </ol>
        </nav>
        <div className="row">
          <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-12">{children}</div>
        </div>
      </div>
    </section>
  );
}

/** Mirrors leisure-ui's own EmptyState closely enough without importing a
 *  component that lives in a different app. */
function EmptyState({ title, description }: { title: string; description: string }) {
  return (
    <div className="text-center py-5">
      <h2 className="subHeading fw-bold mb-2">{title}</h2>
      <p className="text-secondary mb-0">{description}</p>
    </div>
  );
}

/** Mirrors leisure-ui's own TripCardSkeleton shape (a pulsing card outline). */
function TripCardSkeleton({ count }: { count: number }) {
  return (
    <>
      {Array.from({ length: count }).map((_, i) => (
        <div key={i} className="card rounded-3 border mb-3" aria-hidden="true">
          <div className="card-header border-bottom py-4 px-4">
            <div className="h-6 w-1/2 animate-pulse rounded bg-[var(--fra-hover)]" />
          </div>
          <div className="card-body py-4 px-4">
            <div className="h-4 w-3/4 animate-pulse rounded bg-[var(--fra-hover)]" />
          </div>
        </div>
      ))}
    </>
  );
}
