"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";

import DatePicker from "@/components/ui/DatePicker";
import { MinusIcon, PlusIcon } from "@/components/home/v3/icons";
import { VALIDATION_RULES } from "@/constants/booking";
import { checkInTimeOrDefault, checkOutTimeOrDefault } from "@/components/hotel-review/types";
import type { ResponseHotelData } from "@/types/hotel";

interface BookingUpdateFormBusinessProps {
  propertyRules: ResponseHotelData["propertyRules"];
}

function formatYYYYMMDD(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}


/**
 * LEIS-987 — "Change Dates and Guest(s)," ported from leisure-ui's
 * BookingUpdateForm.
 *
 * Rooms + adults use the same `+`/`-` stepper markup and VALIDATION_RULES
 * limits HotelSearchFormV3's own traveller panel already uses on /srp/hotels,
 * rather than importing leisure-ui's GuestRoomSelector, which corp does not
 * have. Children are left out — corp has never needed them in a Business
 * itinerary, and adding the stepper plus per-child age inputs for a feature
 * no Business traveller has asked for would be scope the ticket does not
 * call for.
 *
 * Submitting re-runs the server component with the new query string
 * (`router.push`, no full reload) — same mechanism leisure-ui's own form
 * uses — so hotel-details/page.tsx re-fetches live availability for the new
 * dates/occupancy rather than this form trying to recompute rates itself.
 */
export function BookingUpdateFormBusiness({ propertyRules }: BookingUpdateFormBusinessProps) {
  const searchParams = useSearchParams();
  const router = useRouter();

  const getInitialCheckInDate = () => {
    const checkinDate = searchParams.get("checkinDate");
    return checkinDate ? new Date(checkinDate) : new Date();
  };
  const getInitialCheckOutDate = () => {
    const checkoutDate = searchParams.get("checkoutDate");
    if (checkoutDate) return new Date(checkoutDate);
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 2);
    return tomorrow;
  };

  const [checkInDate, setCheckInDate] = useState<Date | null>(getInitialCheckInDate());
  const [checkOutDate, setCheckOutDate] = useState<Date | null>(getInitialCheckOutDate());
  const [isCheckInOpen, setIsCheckInOpen] = useState(false);
  const [isCheckOutOpen, setIsCheckOutOpen] = useState(false);
  const [travOpen, setTravOpen] = useState(false);
  const [rooms, setRooms] = useState(() => Number(searchParams.get("rooms") ?? 1) || 1);
  const [adults, setAdults] = useState(() => Number(searchParams.get("adults") ?? 1) || 1);
  const [isSearching, setIsSearching] = useState(false);
  const isSubmittedRef = useRef(false);
  const panelRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setCheckInDate(getInitialCheckInDate());
    setCheckOutDate(getInitialCheckOutDate());
    setRooms(Number(searchParams.get("rooms") ?? 1) || 1);
    setAdults(Number(searchParams.get("adults") ?? 1) || 1);
    if (isSubmittedRef.current) {
      setIsSearching(false);
      isSubmittedRef.current = false;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams]);

  useEffect(() => {
    if (!travOpen) return;
    const onClickOutside = (e: MouseEvent) => {
      if (!panelRef.current?.contains(e.target as Node)) setTravOpen(false);
    };
    document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, [travOpen]);

  const handleCheckInChange = useCallback((date: Date | null) => {
    setCheckInDate(date);
    if (date) {
      const dayAfter = new Date(date);
      dayAfter.setDate(dayAfter.getDate() + 2);
      setCheckOutDate(dayAfter);
      setTimeout(() => {
        setIsCheckInOpen(false);
        setIsCheckOutOpen(true);
      }, 0);
    }
  }, []);

  const handleCheckOutChange = useCallback((date: Date | null) => {
    setCheckOutDate(date);
    if (date) setTimeout(() => setIsCheckOutOpen(false), 0);
  }, []);

  const stepRooms = (delta: number) => () => {
    const next = Math.min(VALIDATION_RULES.maxRooms, Math.max(VALIDATION_RULES.minRooms, rooms + delta));
    setRooms(next);
    setAdults((a) => Math.max(a, next));
  };
  const stepAdults = (delta: number) => () => {
    const next = Math.min(VALIDATION_RULES.maxAdults, Math.max(rooms, adults + delta));
    setAdults(next);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!checkInDate || !checkOutDate) return;
    setIsSearching(true);
    const params = new URLSearchParams(searchParams.toString());
    params.set("checkinDate", formatYYYYMMDD(checkInDate));
    params.set("checkoutDate", formatYYYYMMDD(checkOutDate));
    params.set("rooms", String(rooms));
    params.set("adults", String(adults));
    isSubmittedRef.current = true;
    router.push(`?${params.toString()}`, { scroll: false });
  };

  const checkInOutPolicy = propertyRules?.checkInOutPolicies?.[0];
  const checkInTime = checkInTimeOrDefault(checkInOutPolicy?.checkIn);
  const checkOutTime = checkOutTimeOrDefault(checkInOutPolicy?.checkOut);

  return (
    <section className="bookingUpdate search-result-page my-4" id="booking-update-form">
      <div className="container webNewContent">
        <div className="row">
          <div className="col-12">
            <div className="bgColor-white shadow-sm rounded-4 p-3 p-md-4 mb-0 updatePanel">
              <div className="row g-1 align-items-center">
                <div className="col-12 col-md-4 col-lg-3 mb-3 mb-md-0">
                  <h4 className="subHeading fw-bold mb-2">Change Dates and Guest(s)</h4>
                  <p className="text-md m-0">
                    Check-in: {checkInTime} | Check-out: {checkOutTime}
                  </p>
                </div>
                <div className="col-12 col-md-8 col-lg-9">
                  <form onSubmit={handleSubmit} className="booking-validation" noValidate>
                    <div className="row g-1">
                      <div className="col-6 col-md-6 col-xl-3 position-relative d-flex">
                        <div className="w-100 bg-body-secondary rounded-3 mb-md-0 mb-1">
                          <div
                            className="collapse-fields py-1 px-2 cursor-pointer"
                            onClick={() => {
                              setIsCheckOutOpen(false);
                              setIsCheckInOpen(true);
                            }}
                          >
                            <DatePicker
                              id="hotel-business-from-date"
                              selected={checkInDate}
                              onChange={handleCheckInChange}
                              placeholderText="From Date"
                              minDate={new Date()}
                              className="text-lg form-control shadow-none bg-body-secondary rounded-0 px-0 text-black"
                              open={isCheckInOpen}
                              onClickOutside={() => setIsCheckInOpen(false)}
                              onCalendarClose={() => setIsCheckInOpen(false)}
                              dateFormat="yyyy-MM-dd"
                            />
                          </div>
                        </div>
                      </div>
                      <div className="col-6 col-md-6 col-xl-3 position-relative d-flex">
                        <div className="w-100 bg-body-secondary rounded-3 mb-md-0 mb-1">
                          <div
                            className="collapse-fields py-1 px-2 cursor-pointer"
                            onClick={() => {
                              setIsCheckInOpen(false);
                              setIsCheckOutOpen(true);
                            }}
                          >
                            <DatePicker
                              id="hotel-business-to-date"
                              key={checkInDate?.toISOString()}
                              selected={checkOutDate}
                              onChange={handleCheckOutChange}
                              placeholderText="To Date"
                              minDate={
                                checkInDate
                                  ? (() => {
                                      const dayAfter = new Date(checkInDate);
                                      dayAfter.setDate(dayAfter.getDate() + 1);
                                      return dayAfter;
                                    })()
                                  : new Date()
                              }
                              className="text-lg form-control shadow-none bg-body-secondary rounded-0 px-0"
                              open={isCheckOutOpen}
                              onClickOutside={() => setIsCheckOutOpen(false)}
                              onCalendarClose={() => setIsCheckOutOpen(false)}
                              dateFormat="yyyy-MM-dd"
                            />
                          </div>
                        </div>
                      </div>

                      <div
                        className="col-12 col-md-7 col-xl-3 position-relative guestPanel"
                        ref={panelRef}
                      >
                        <div
                          className="collapse-fields cursor-pointer w-100 bg-body-secondary rounded-3 py-1 px-2 mb-md-0 mb-1"
                          onClick={() => setTravOpen((v) => !v)}
                        >
                          <p className="m-0 text-lg color-text-black fw-500">
                            {rooms} Room{rooms === 1 ? "" : "s"}
                          </p>
                          <span className="text-md color-text-content">
                            {adults} {adults === 1 ? "adult" : "adults"}
                          </span>
                        </div>

                        <div
                          className="submenu-web bgColor-white rounded-3 shadow-sm mt-2"
                          style={{
                            display: travOpen ? "block" : "none",
                            position: "absolute",
                            right: 0,
                            zIndex: 1000,
                            minWidth: 260,
                          }}
                        >
                          <div className="card border-0 rounded-2">
                            <div className="card-body p-3">
                              <div className="row align-items-center mb-3">
                                <div className="col-6">
                                  <p className="mb-0 fw-500 text-lg color-text-content">Rooms</p>
                                  <small className="text-muted">
                                    Max {VALIDATION_RULES.maxRooms}
                                  </small>
                                </div>
                                <div className="col-6">
                                  <div className="qty-container d-flex justify-content-between align-items-center rounded p-1">
                                    <button
                                      type="button"
                                      className="qty-btn-minus btn btn-sm btn-white shadow-none border border-light1"
                                      onClick={stepRooms(-1)}
                                    >
                                      <MinusIcon />
                                    </button>
                                    <input
                                      type="text"
                                      value={rooms}
                                      readOnly
                                      className="input-qty passenger-qty border-0 bg-transparent text-center fw-500"
                                      style={{ width: 30 }}
                                    />
                                    <button
                                      type="button"
                                      className="qty-btn-plus btn btn-sm btn-white shadow-none border border-light1"
                                      onClick={stepRooms(1)}
                                    >
                                      <PlusIcon />
                                    </button>
                                  </div>
                                </div>
                              </div>
                              <div className="row align-items-center">
                                <div className="col-6">
                                  <p className="mb-0 fw-500 text-lg color-text-content">Adults</p>
                                  <small className="text-muted">Age +17</small>
                                </div>
                                <div className="col-6">
                                  <div className="qty-container d-flex justify-content-between align-items-center rounded p-1">
                                    <button
                                      type="button"
                                      className="qty-btn-minus btn btn-sm btn-white shadow-none border border-light1"
                                      onClick={stepAdults(-1)}
                                    >
                                      <MinusIcon />
                                    </button>
                                    <input
                                      type="text"
                                      value={adults}
                                      readOnly
                                      className="input-qty passenger-qty border-0 bg-transparent text-center fw-500"
                                      style={{ width: 30 }}
                                    />
                                    <button
                                      type="button"
                                      className="qty-btn-plus btn btn-sm btn-white shadow-none border border-light1"
                                      onClick={stepAdults(1)}
                                    >
                                      <PlusIcon />
                                    </button>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div className="col-12 col-md-5 col-xl-3 d-flex">
                        <button
                          className="buttons btnColor-first-outline rounded-3 w-100 h-auto px-3 py-2 text-lg fw-600 ls-0"
                          type="submit"
                        >
                          {isSearching ? "Updating…" : "Update Search"}
                        </button>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
