"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";

import type { FlightSearchFormV3Props } from "@/components/flights/v3/FlightSearchFormV3";
import { useBusinessSession, useBusinessToken } from "@/components/employee-requests/use-session";
import { getBusinessProfile } from "@/services/employee-login/employee-login.client";
import { nameFromEmail } from "@/lib/business-session";
import { HomeHero } from "./HomeHero";
import { HomeSearchPanel, type HomeSearchTab } from "./HomeSearchPanel";
import { useHomePolicy } from "./useHomePolicy";
import { PassportCard } from "./panels/PassportCard";
import { RecentRequests } from "./panels/RecentRequests";
import { TravelPolicyPanel } from "./panels/TravelPolicyPanel";

/**
 * Employee home — E0 (LEIS-1013).
 *
 * The PRD's §6.1 search landing, which the repo README listed as unbuilt: the
 * flight and hotel search, with the employee's own requests, travel policy and
 * passport underneath. Everything below the search card arrives in LEIS-1016 /
 * 1017 / 1018; this is the hero, the search and the approval chips.
 *
 * Signed-out and admin visitors never reach this component — `HomeRouter`
 * resolves the role first.
 */
export function EmployeeHome({ flightFormProps }: { flightFormProps?: FlightSearchFormV3Props }) {
  const session = useBusinessSession();
  const token = useBusinessToken();
  const [tab, setTab] = useState<HomeSearchTab>("flights");
  const policy = useHomePolicy({ tab, isAdmin: false });

  // The same query key the header and the Profile page use, so the three share
  // one cache entry rather than making three identical calls on one page load.
  const profile = useQuery({
    queryKey: ["business-profile", "me"],
    queryFn: async () => {
      const res = await getBusinessProfile(token!);
      if (!res.success) throw new Error(res.message ?? "Could not load your profile.");
      return res.data ?? null;
    },
    enabled: Boolean(token),
    staleTime: 5 * 60_000,
  });

  // `nameFromEmail` rather than a blank while the profile loads: the greeting
  // is the first thing on the page, and "Where's your next business trip, ?"
  // is worse than a name derived from the address they signed in with.
  const firstName =
    profile.data?.firstName?.trim() || (session ? nameFromEmail(session.email).split(" ")[0] : "");

  return (
    <>
      <HomeHero
        title={firstName ? `Where's your next business trip, ${firstName}?` : "Where's your next business trip?"}
        subtitle={<EmployeeSubtitle groupName={policy.groupName} />}
      >
        <HomeSearchPanel
          tab={tab}
          onTabChange={setTab}
          approvalRequired={policy.approvalRequired}
          policyKnown={policy.known}
          flightFormProps={flightFormProps}
        />
      </HomeHero>

      {/*
       * Requests take the wide column and the two reference panels stack beside
       * them, as in the design. The order is deliberate on a phone, where the
       * grid collapses: requests first, because they are the only thing here
       * that can need acting on, then the policy, then the passport.
       */}
      <div
        data-corp-home
        className="mx-auto w-full max-w-[1200px] px-[16px] pt-[32px] pb-[48px]"
      >
        <div className="grid gap-[24px] lg:grid-cols-[minmax(0,1fr)_340px]">
          <RecentRequests />
          <div className="grid content-start gap-[24px]">
            <TravelPolicyPanel
              tab={tab}
              flight={policy.flight}
              hotel={policy.hotel}
              groupName={policy.groupName}
            />
            <PassportCard profile={profile.data} isLoading={profile.isPending} />
          </div>
        </div>
      </div>
    </>
  );
}

/**
 * "[Company] · Travel policy group: [name]".
 *
 * The company name is not on the session — the JWT carries `companyId`, an
 * opaque number — and no endpoint on this page returns it yet, so the line
 * leads with the policy group, which `GET /policy/me` does return. Rendering
 * "undefined ·" would be worse than leading with the half that is known.
 */
function EmployeeSubtitle({ groupName }: { groupName: string | null }) {
  if (!groupName) return <>Business travel, booked against your company&rsquo;s policy.</>;
  return (
    <>
      Travel policy group: <strong>{groupName}</strong>
    </>
  );
}
