"use client";

import { useEffect, useRef, type RefObject } from "react";
import { useForm, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";

import { useRequestTraveller } from "@/components/employee-requests/useRequestTraveller";
import { useBusinessSession } from "@/components/employee-requests/use-session";
import PhoneInput from "@/components/ui/PhoneInput";
import {
  hotelGuestDetailsSchema,
  type HotelGuestDetailsValues,
} from "@/features/employee-requests/schemas/hotel-guest-details.schema";
import type { HotelGuestPayload } from "@/services/employee-requests/employee-requests.types";

export interface GuestDetailsCardHotelHandle {
  /** Validates and returns the current guest, or null if invalid — called by
   *  PaneReviewHotel's "Request approval" button rather than this card
   *  owning its own submit button, since Guest Details is not a separate
   *  step here (see PaneReviewHotel's doc comment). */
  getValidGuest: () => Promise<HotelGuestPayload | null>;
}

/**
 * LEIS-989 — Guest Details, ported from leisure-ui's GuestDetailsForm to
 * match the reference "Review your Booking" page the user pointed to, cut
 * down to what a Business request actually sends:
 *
 *   - No Title: BusinessHotelRequestDetail's guest has no title field, and
 *     a courtesy title has no bearing on an approval request. Email IS
 *     shown, matching the reference layout, but read-only and prefilled
 *     from the traveller's own account — there is no booking voucher to
 *     send it to, and nowhere in BusinessHotelRequestDetail for a typed-in
 *     address to go, so this displays what the request is actually tied to
 *     (the authenticated employee's account) rather than invite editing a
 *     value that would be silently discarded.
 *   - No "My Self / Someone Else" radio: that toggles between the signed-in
 *     user and an ad-hoc second guest on the SAME reservation (leisure-ui
 *     supports multiple guests per room). Business mode's traveller — self,
 *     or the colleague named by "Booking for" on search — is already decided
 *     before hotel-details, via useRequestTraveller below, so there is only
 *     ever one guest to prefill here, not a choice to make on this page.
 *   - No SMS/RCS marketing consent checkbox: that is a Personal-mode opt-in,
 *     not a business request field.
 *
 * Prefilled from the resolved traveller's profile and editable for this stay
 * only — never written back, same snapshot rule PaneTravelerDetails follows
 * for flights.
 */
export function GuestDetailsCardHotel({
  travelerId,
  countryCode,
  formRef,
}: {
  travelerId: string | null;
  /**
   * The property's ISO-2 country (LEIS-1042) — passed through to
   * `useRequestTraveller` so a colleague whose COLLEAGUE_BOOKING_OFF toggle
   * fires on the specific tab this stay falls under is caught here, before
   * the approval overlay, rather than only at submit. Previously hardcoded
   * `airports: []`, which left hotel scope permanently null and so never
   * caught this case at all.
   */
  countryCode: string | null;
  /** Lets PaneReviewHotel trigger validation from its own "Request approval"
   *  button without this card needing a submit button of its own. */
  formRef: RefObject<GuestDetailsCardHotelHandle | null>;
}) {
  const session = useBusinessSession();
  const traveller = useRequestTraveller({
    travelerId,
    countryCode: countryCode ?? "",
    sessionEmail: session?.email ?? "",
    enabled: true,
  });

  const {
    register,
    reset,
    trigger,
    getValues,
    setValue,
    control,
    formState: { errors },
  } = useForm<HotelGuestDetailsValues>({
    resolver: zodResolver(hotelGuestDetailsSchema),
    mode: "onTouched",
    defaultValues: {
      firstName: "",
      middleName: "",
      lastName: "",
      email: "",
      mobileCountryCode: "",
      mobileNumber: "",
    },
  });

  // Prefilled once the traveller's profile resolves — never again, so an
  // employee's own in-progress edits are not clobbered by a slow query or a
  // re-render. The ref makes that "once" explicit rather than relying on the
  // profile object's identity staying stable.
  const prefilledFor = useRef<string | null>(null);
  useEffect(() => {
    if (!traveller.profile) return;
    // workEmail is part of the key because for the signed-in employee it can arrive
    // a render after the profile (it comes from the session, not the profile query).
    const key = `${travelerId ?? "self"}:${traveller.workEmail}`;
    if (prefilledFor.current === key) return;
    prefilledFor.current = key;
    reset({
      firstName: traveller.profile.firstName ?? "",
      middleName: traveller.profile.middleName ?? "",
      lastName: traveller.profile.lastName ?? "",
      email: traveller.workEmail ?? "",
      mobileCountryCode: traveller.profile.mobileCountryCode ?? "",
      mobileNumber: traveller.profile.mobileNumber ?? "",
    });
  }, [traveller.profile, traveller.workEmail, travelerId, reset]);

  // `useWatch` rather than `watch()`: it subscribes to just these two
  // fields instead of the whole form, and — unlike `watch` — does not hand
  // the React Compiler a function it has to bail out of memoising this
  // component on (same reasoning RequestApprovalModal.tsx documents).
  const mobileCountryCode = useWatch({ control, name: "mobileCountryCode" });
  const mobileNumber = useWatch({ control, name: "mobileNumber" });
  // PhoneInput's `value` is digits-only, country code + national number
  // concatenated (its own doc comment: "12133734253" for +1 213 373 4253) —
  // build that from the two separate form fields this component still
  // stores, stripping the "+" the dial code is kept with everywhere else.
  const phoneValue = `${(mobileCountryCode || "").replace(/\D/g, "")}${mobileNumber || ""}`;

  useEffect(() => {
    formRef.current = {
      getValidGuest: async () => {
        const valid = await trigger();
        if (!valid) return null;
        const values = getValues();
        return {
          firstName: values.firstName.trim(),
          middleName: values.middleName?.trim() || null,
          lastName: values.lastName.trim(),
          mobileCountryCode: values.mobileCountryCode?.trim() || null,
          mobileNumber: values.mobileNumber?.trim() || null,
        };
      },
    };
  }, [formRef, trigger, getValues]);

  return (
    <div className="bgColor-white shadow-sm rounded-3 p-3">
      <p className="fw-semibold">Guest Details</p>

      {traveller.reason && (
        <div className="alert alert-danger text-sm" role="alert">
          {traveller.reasonMessage ?? "That colleague can no longer be requested for on this stay."}
        </div>
      )}

      <div className="row mb-3">
        <div className="col-sm-5">
          <label htmlFor="guestFirstName" className="form-label text-sm">
            FIRST NAME <span className="text-danger">*</span>
          </label>
          <input
            type="text"
            className={`form-control border rounded ${errors.firstName ? "is-invalid" : ""}`}
            id="guestFirstName"
            {...register("firstName")}
          />
          {errors.firstName && (
            <div className="invalid-feedback d-block text-sm">{errors.firstName.message}</div>
          )}
        </div>
        <div className="col-sm-5">
          <label htmlFor="guestLastName" className="form-label text-sm">
            LAST NAME <span className="text-danger">*</span>
          </label>
          <input
            type="text"
            className={`form-control border rounded ${errors.lastName ? "is-invalid" : ""}`}
            id="guestLastName"
            {...register("lastName")}
          />
          {errors.lastName && (
            <div className="invalid-feedback d-block text-sm">{errors.lastName.message}</div>
          )}
        </div>
      </div>

      <div className="row mb-3 align-items-end">
        <div className="col-sm-6">
          <label htmlFor="guestEmail" className="form-label text-sm">
            EMAIL ADDRESS
          </label>
          <input
            type="email"
            className="form-control border rounded"
            id="guestEmail"
            readOnly
            // Not `disabled`: a disabled control is skipped by the tab order
            // and announced as unavailable — this field matters (it is what
            // the request is tied to), it simply is not editable here.
            aria-readonly="true"
            tabIndex={-1}
            {...register("email")}
          />
        </div>
        <div className="col-sm-6">
          <PhoneInput
            id="guestMobileNumber"
            label="Mobile Number"
            value={phoneValue}
            // PhoneInput always calls this with the same combined digits
            // `onValuePartsChange` below derives separately — kept as a
            // harmless no-op so the two never fight over which one wins.
            onChange={() => {}}
            onValuePartsChange={({ dialCode, nationalNumber }) => {
              setValue("mobileCountryCode", dialCode, { shouldValidate: true });
              setValue("mobileNumber", nationalNumber, { shouldValidate: true });
            }}
            placeholder="Enter mobile number"
            defaultCountry="us"
            preferredCountries={["us", "in", "gb"]}
            error={errors.mobileNumber?.message}
          />
        </div>
      </div>
    </div>
  );
}
