"use client";

import { useEffect, useRef, useState } from "react";
import { ChevronDown, ChevronLeft, ChevronRight, Check } from "lucide-react";
import { NAV } from "@/lib/navigation";

const formatDate = (date?: Date) => {
  if (!date) return "";

  return date.toLocaleDateString("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
};

const isSameDay = (a?: Date, b?: Date) => {
  if (!a || !b) return false;

  return (
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate()
  );
};

const isBeforeDay = (date: Date, compare: Date) => {
  const a = new Date(
    date.getFullYear(),
    date.getMonth(),
    date.getDate()
  );

  const b = new Date(
    compare.getFullYear(),
    compare.getMonth(),
    compare.getDate()
  );

  return a < b;
};

const getCalendarDays = (year: number, month: number) => {
  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();

  const previousMonthDays = new Date(year, month, 0).getDate();

  const days = [];

  // Previous month's visible days
  for (let i = firstDay - 1; i >= 0; i--) {
    days.push({
      date: new Date(year, month - 1, previousMonthDays - i),
      currentMonth: false,
    });
  }

  // Current month's days
  for (let day = 1; day <= daysInMonth; day++) {
    days.push({
      date: new Date(year, month, day),
      currentMonth: true,
    });
  }

  // Next month's visible days
  const remaining = 42 - days.length;

  for (let day = 1; day <= remaining; day++) {
    days.push({
      date: new Date(year, month + 1, day),
      currentMonth: false,
    });
  }

  return days;
};

export function DestinationSelector() {
  const rooms =
  NAV.find((item) => item.label === "Stay & Rooms")?.children || [];

  const [selectedRoom, setSelectedRoom] = useState(
    rooms[0]?.to || ""
  );

  const [checkIn, setCheckIn] = useState<Date | undefined>();
  const [checkOut, setCheckOut] = useState<Date | undefined>();
  const [guests, setGuests] = useState("1");
  const [dateError, setDateError] = useState("");

  const [roomOpen, setRoomOpen] = useState(false);
  const [dateOpen, setDateOpen] = useState(false);

  const [calendarMonth, setCalendarMonth] = useState(
    new Date(new Date().getFullYear(), new Date().getMonth(), 1)
  );

  const selectorRef = useRef<HTMLDivElement>(null);

  const selectedRoomData = rooms.find(
    (room) => room.to === selectedRoom
  );

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  /*
   * Close dropdowns when clicking outside
   */
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        selectorRef.current &&
        !selectorRef.current.contains(event.target as Node)
      ) {
        setRoomOpen(false);
        setDateOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  /*
   * Select palace
   */
  const handleRoomSelect = (room: string) => {
    setSelectedRoom(room);
    setRoomOpen(false);
  };

  /*
   * Date selection
   */
  const handleDateSelect = (date: Date) => {
  const selectedDate = new Date(date);
  selectedDate.setHours(0, 0, 0, 0);

  const todayDate = new Date();
  todayDate.setHours(0, 0, 0, 0);

  // Prevent selecting past dates
  if (selectedDate < todayDate) {
    return;
  }

  // First selection = Check-in
  if (!checkIn || checkOut) {
    setCheckIn(selectedDate);
    setCheckOut(undefined);
    setDateError("");

    return;
  }

  // Check-out cannot be same as or before check-in
  if (selectedDate < checkIn) {
    setDateError("Check-out must be after check-in.");
    return;
  }

  // Valid checkout
  setCheckOut(selectedDate);
  setDateError("");
};

  /*
   * Calendar navigation
   */
  const previousMonth = () => {
    const currentMonth = new Date(
      today.getFullYear(),
      today.getMonth(),
      1
    );

    if (calendarMonth <= currentMonth) {
      return;
    }

    setCalendarMonth(
      new Date(
        calendarMonth.getFullYear(),
        calendarMonth.getMonth() - 1,
        1
      )
    );
  };

  const nextMonth = () => {
    setCalendarMonth(
      new Date(
        calendarMonth.getFullYear(),
        calendarMonth.getMonth() + 1,
        1
      )
    );
  };

  const calendarDays = getCalendarDays(
    calendarMonth.getFullYear(),
    calendarMonth.getMonth()
  );

  const monthName = calendarMonth.toLocaleDateString("en-US", {
    month: "long",
    year: "numeric",
  });

  const handleAvailability = () => {
  // Check-in missing
  if (!checkIn) {
    setDateError("Please select your check-in date.");
    setDateOpen(true);
    return;
  }

  // Check-out missing
  if (!checkOut) {
    setDateError("Please select your check-out date.");
    setDateOpen(true);
    return;
  }

  // Checkout must be after check-in
  if (checkOut <= checkIn) {
    setDateError("Check-out must be after check-in.");
    setDateOpen(true);
    return;
  }

  setDateError("");

  const message = `Hi! I would like to enquire about booking at The Grand Heritage Resorts.

Place: ${selectedRoomData?.label || "Not selected"}
Check-in: ${formatDate(checkIn)}
Check-out: ${formatDate(checkOut)}
Guests: ${guests}

Please let me know about availability and booking details.`;

  const whatsappUrl = `https://wa.me/7447274472?text=${encodeURIComponent(
    message
  )}`;

  window.open(whatsappUrl, "_blank", "noopener,noreferrer");
};

  return (
    <div
      ref={selectorRef}
      className="
        grid
        grid-cols-1
        sm:grid-cols-2
        lg:grid-cols-4
        gap-x-5
        gap-y-4
        lg:gap-y-0
        items-end
        w-full
        max-w-full
      "
    >
      {/* =========================================================
          SELECT PALACE
      ========================================================= */}
      <div className="relative w-full min-w-0">
        <label
          className="
            block
            mb-1.5
            lg:mb-2
            font-sans
            text-[9px]
            lg:text-[11px]
            uppercase
            tracking-[0.12em]
            text-gold-deep
          "
        >
          Select Place
        </label>

        <button
          type="button"
          onClick={() => {
            setRoomOpen((prev) => !prev);
            setDateOpen(false);
          }}
          className="
            flex
            items-center
            justify-between
            gap-2
            w-full
            min-w-0
            h-9
            lg:h-10
            px-0
            bg-transparent
            border-b
            border-espresso/20
            text-left
            focus:outline-none
            focus:border-gold-deep
          "
        >
          <span
            className="
              min-w-0
              truncate
              font-sans
              text-[10px]
              lg:text-xs
              text-espresso
            "
          >
            {selectedRoomData?.selectorLabel ||
              selectedRoomData?.label ||
              "Select Place"}
          </span>

          <ChevronDown
            className={`
              shrink-0
              w-3.5
              h-3.5
              text-espresso/60
              transition-transform
              duration-200
              ${roomOpen ? "rotate-180" : ""}
            `}
          />
        </button>

        {roomOpen && (
          <div
            className="
              absolute
              left-0
              right-0
              bottom-[calc(60%+2px)]
              z-[100]
              w-full
              max-h-[200px]
              overflow-hidden
              bg-ivory
              border
              border-espresso/10
              shadow-2xl
            "
          >
            <div className="max-h-52 overflow-y-auto py-1">
              {rooms.map((room) => {
                const active = selectedRoom === room.to;

                return (
                  <button
                    key={room.to}
                    type="button"
                    onClick={() => handleRoomSelect(room.to)}
                    className="
                      flex
                      items-center
                      justify-between
                      gap-3
                      w-full
                      px-3
                      lg:px-4
                      py-2.5
                      lg:py-3
                      text-left
                      font-sans
                      text-[10px]
                      lg:text-xs
                      text-espresso
                      hover:bg-gold/10
                      transition-colors
                    "
                  >
                    <span className="truncate">
                      {room.selectorLabel || room.label}
                    </span>

                    {active && (
                      <Check
                        className="
                          shrink-0
                          w-3.5
                          h-3.5
                          text-gold-deep
                        "
                      />
                    )}
                  </button>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* =========================================================
          TRAVEL DATES
      ========================================================= */}
      <div className="relative w-full min-w-0">
        <label
          className="
            block
            mb-1.5
            lg:mb-2
            font-sans
            text-[9px]
            lg:text-[11px]
            uppercase
            tracking-[0.12em]
            text-gold-deep
          "
        >
          Travel Dates
        </label>

        <button
          type="button"
          onClick={() => {
            setDateOpen((prev) => !prev);
            setRoomOpen(false);
            setDateError("");
          }}
          className="
            flex
            items-center
            justify-between
            gap-2
            w-full
            min-w-0
            h-9
            lg:h-10
            px-0
            bg-transparent
            border-b
            border-espresso/20
            text-left
            focus:outline-none
            focus:border-gold-deep
          "
        >
          <span
            className="
              min-w-0
              truncate
              font-sans
              text-[10px]
              lg:text-xs
              text-espresso
            "
          >
            {checkIn && checkOut
              ? `${formatDate(checkIn)} – ${formatDate(checkOut)}`
              : checkIn
                ? `${formatDate(checkIn)} – Select check-out`
                : "Select travel dates"}
          </span>

          <ChevronDown
            className={`
              shrink-0
              w-3.5
              h-3.5
              text-espresso/60
              transition-transform
              duration-200
              ${dateOpen ? "rotate-180" : ""}
            `}
          />
        </button>
        {dateError && (
          <p className="mt-1.5 text-[9px] sm:text-[10px] text-red-600 leading-tight">
            {dateError}
          </p>
        )}

        {/* CUSTOM CALENDAR */}
        {dateOpen && (
          <div
            className="
              absolute
              left-1/2
              -translate-x-1/2
              bottom-[calc(60%+2px)]
              z-[110]
              w-[min(90vw,290px)]
              sm:w-[290px]
              bg-ivory
              border
              border-espresso/10
              shadow-2xl
              p-2.5
              sm:p-3
            "
          >
            {/* Calendar Header */}
            <div className="flex items-center justify-between mb-1.5">
              <button
                type="button"
                onClick={previousMonth}
                disabled={
                  calendarMonth.getFullYear() ===
                    today.getFullYear() &&
                  calendarMonth.getMonth() === today.getMonth()
                }
                className="
                  flex
                  items-center
                  justify-center
                  w-6
                  h-6
                  text-espresso
                  hover:bg-gold/10
                  disabled:opacity-30
                  disabled:cursor-not-allowed
                "
                aria-label="Previous month"
              >
                <ChevronLeft className="w-3.5 h-3.5" />
              </button>

              <span
                className="
                  font-serif
                  text-sm
                  lg:text-base
                  text-espresso
                "
              >
                {monthName}
              </span>

              <button
                type="button"
                onClick={nextMonth}
                className="
                  flex
                  items-center
                  justify-center
                  w-6
                  h-6
                  text-espresso
                  hover:bg-gold/10
                "
                aria-label="Next month"
              >
                <ChevronRight className="w-3.5 h-3.5" />
              </button>
            </div>

            {/* Selection Info */}
            <div
              className="
                grid
                grid-cols-2
                gap-1.5
                mb-2
              "
            >
              <div
                className={`
                  px-2
                  py-1
                  border
                  ${
                    !checkIn
                      ? "border-gold-deep"
                      : "border-espresso/10"
                  }
                `}
              >
                <p className="text-[9px] uppercase tracking-widest text-gold-deep">
                  Check-in
                </p>

                <p className="mt-0.5 text-[10px] text-espresso truncate">
                  {checkIn ? formatDate(checkIn) : "Select"}
                </p>
              </div>

              <div
                className={`
                  px-2
                  py-1
                  border
                  ${
                    checkIn && !checkOut
                      ? "border-gold-deep"
                      : "border-espresso/10"
                  }
                `}
              >
                <p className="text-[9px] uppercase tracking-widest text-gold-deep">
                  Check-out
                </p>

                <p className="mt-0.5 text-[10px] text-espresso truncate">
                  {checkOut ? formatDate(checkOut) : "Select"}
                </p>
              </div>
            </div>

            {/* Week Days */}
            <div className="grid grid-cols-7">
              {["S", "M", "T", "W", "T", "F", "S"].map(
                (day, index) => (
                  <div
                    key={`${day}-${index}`}
                    className="
                      flex
                      items-center
                      justify-center
                      h-5
                      font-sans
                      text-[10px]
                      font-medium
                      text-gold-deep
                    "
                  >
                    {day}
                  </div>
                )
              )}
            </div>

            {/* Calendar Days */}
            <div className="grid grid-cols-7">
              {calendarDays.map(({ date, currentMonth }, index) => {
                const disabled =
                isBeforeDay(date, today) ||
                (!!checkIn && date < checkIn);

                const selectedCheckIn = isSameDay(
                  date,
                  checkIn
                );

                const selectedCheckOut = isSameDay(
                  date,
                  checkOut
                );

                const selected =
                  selectedCheckIn || selectedCheckOut;

                const inRange =
                  checkIn &&
                  checkOut &&
                  date >= checkIn &&
                  date <= checkOut;

                return (
                  <button
                    key={`${date.toISOString()}-${index}`}
                    type="button"
                    disabled={disabled}
                    onClick={() => handleDateSelect(date)}
                    className={`
                      relative
                      flex
                      items-center
                      justify-center
                      h-6
                      sm:h-7
                      font-sans
                      text-[8px]
                      sm:text-[9px]
                      transition-all

                      ${
                        !currentMonth
                          ? "text-espresso/20"
                          : disabled
                            ? "text-espresso/20 cursor-not-allowed"
                            : "text-espresso hover:bg-gold/15"
                      }

                      ${
                        inRange
                          ? "bg-gold/10"
                          : ""
                      }

                      ${
                        selected
                          ? "bg-gold text-midnight font-medium"
                          : ""
                      }
                    `}
                  >
                    {date.getDate()}
                  </button>
                );
              })}
            </div>

            {/* Calendar Footer */}
            <div className="flex items-center justify-between mt-1.5 pt-1.5 border-t border-espresso/10">
              <button
                type="button"
                onClick={() => {
                  setCheckIn(undefined);
                  setCheckOut(undefined);
                }}
                className="
                  font-sans
                  text-[9px]
                  uppercase
                  tracking-widest
                  text-espresso/60
                  hover:text-espresso
                "
              >
                Clear
              </button>

              {checkIn && checkOut && (
                <button
                  type="button"
                  onClick={() => setDateOpen(false)}
                  className="
                    font-sans
                    text-[9px]
                    uppercase
                    tracking-widest
                    text-gold-deep
                    hover:text-espresso
                  "
                >
                  Done
                </button>
              )}
            </div>
          </div>
        )}
      </div>

      {/* GUESTS */}
      <div className="w-full min-w-0">
        <label
          className="
            block
            mb-1.5
            lg:mb-2
            font-sans
            text-[9px]
            lg:text-[11px]
            uppercase
            tracking-[0.12em]
            text-gold-deep
          "
        >
          Guests
        </label>

        <input
          type="number"
          min={1}
          value={guests}
          onChange={(e) => {
            setGuests(e.target.value);
          }}
          onBlur={() => {
            if (guests === "" || Number(guests) < 1) {
              setGuests("1");
            }
          }}
          className="
            block
            w-full
            min-w-0
            h-9
            lg:h-10
            px-0
            bg-transparent
            border-0
            border-b
            border-espresso/20
            font-sans
            text-[10px]
            lg:text-xs
            text-espresso
            focus:outline-none
            focus:border-gold-deep
          "
        />
      </div>

      {/* CHECK AVAILABILITY */}
      <div className="w-full min-w-0">
        <button
          type="button"
          onClick={handleAvailability}
          className="
            flex
            items-center
            justify-center
            w-full
            min-w-0
            h-9
            lg:h-10
            px-2
            lg:px-3
            bg-gold
            text-midnight
            uppercase
            tracking-[0.1em]
            text-[8px]
            lg:text-[10px]
            font-medium
            font-sans
            border
            border-gold
            hover:bg-gold-deep
            hover:border-gold-deep
            hover:text-ivory
            transition-all
            duration-300
            whitespace-nowrap
          "
        >
          Check Availability
        </button>
      </div>
    </div>
  );
}

export default DestinationSelector;