// import { Link, router, usePage } from "@inertiajs/react"
// import { Key, Trash2 } from "lucide-react"

// import { Button } from "@/components/ui/button"
// import { CheckoutBookingInput, RoomSelected } from "@/types/home/bookings"

// type BookingKeyCartProp = {
//   booking: CheckoutBookingInput,
//   search: SearchRoom
// }

// import {
//   Drawer,
//   DrawerContent,
//   DrawerDescription,
//   DrawerFooter,
//   DrawerHeader,
//   DrawerTitle,
//   DrawerTrigger,
// } from "@/components/ui/drawer"
// import { Separator } from "@/components/ui/separator"
// import Price from "../Price"
// import { SearchRoom } from "@/types/home/client-side"
// import { calBookingTotal, calMealPackageTotal, calRoomOnlyTotal, calRoomTotal } from "@/utils/client/calBooking"
// import UiCardFooter from "../UiCardFooter"

// function RoomCard({ room, nights }: { room: RoomSelected, nights: number }) {

//   const { meal_package, addons, room_daily_prices, adults, children } = room

//   return <div className="space-y-2 "   >
//     <div className="flex gap-4">
//       <img src={room?.image_url ? room.image_url : '/images/placeholders/room-placeholder.jpg'} className="h-20 aspect-video rounded-none object-cover" alt={room.title} />


//       <div>
//         <h3 className="font-semibold font-title text-lg">{room.title}</h3>
//         <p className="text-sm text-gray-500 font-p">
//           {room.adults} Adults · {room.children} Children
//         </p>

//       </div>


//     </div>

//     <div>
//       <div className="flex justify-between border-b-2 border-dashed text-neutral-600  py-1.5 text-sm">
//         <span>Room</span>
//         <span><Price value={calRoomOnlyTotal(room_daily_prices)} /></span>
//       </div>
//       {
//         meal_package && <div className="flex justify-between border-b-2 text-neutral-600 border-dashed py-1.5 text-sm ">
//           <span>{meal_package.title}</span>
//           <span><Price value={calMealPackageTotal(meal_package, nights, adults + children)} /></span>
//         </div>
//       }
//       {
//         addons.map((item) => <div key={item.id} className="flex justify-between border-b-2 text-neutral-600 border-dashed py-1.5 text-sm">
//           <span>{item.title}</span>
//           <span><Price value={0} /></span>
//         </div>)
//       }

//       <div className="flex justify-between font-semibold text-sm py-1.5">
//         <span>Room Total Price</span>
//         <span><Price value={calRoomTotal(room, nights)} /></span>
//       </div>

//     </div>
//     <div className="flex w-full gap-2 justify-end">
//       <Button size='sm' variant='outline' onClick={() => router.get(`/rooms/${room.slug}`, { room: room.room_number })} className="w-fit  text-sm  rounded-sm hover:bg-gray-50 transition"> View Details </Button>
//       <Button onClick={() => router.post('/booking/remove-room', { room_id: room.room_id })} className="text-destructive  rounded-sm" variant='outline' size='icon-sm'><Trash2 /></Button>
//     </div>


//   </div>

// }


// export default function BookingKeyCart() {

//   const { booking, search } = usePage().props as unknown as BookingKeyCartProp
//   const { rooms } = booking
//   const nights = search.nights

//   return (
//     <Drawer direction='right'  >
//       <DrawerTrigger asChild>
//         <button className="relative rounded-full backdrop-blur-xs border-main/40 bg-white/90  border sm:bg-black/80 p-2 hover:scale-102 active:scale-98">

//           <Key size={20} className="text-main" />

//           {rooms.length > 0 && (
//             <span className="absolute -top-1 -left-1 min-w-5 h-5 rounded-full bg-main text-white text-[10px] flex items-center justify-center font-semibold">
//               {rooms.length}
//             </span>
//           )}

//         </button>
//       </DrawerTrigger>
//       <DrawerContent className="data-[vaul-drawer-direction=bottom]:max-h-[50vh] data-[vaul-drawer-direction=top]:max-h-[50vh] ">
//         <DrawerHeader className="pb-2">
//           <DrawerTitle className="flex items-center gap-2 text-xl font-semibold">
//             <Key className="text-main" size={20} />  Room Keys  </DrawerTitle>
//           <DrawerDescription className="text-sm text-muted-foreground">
//             Review your selected rooms before checkout
//           </DrawerDescription>
//         </DrawerHeader>

//         <div className="no-scrollbar overflow-y-auto px-4">

//           {rooms.length === 0 && (
//             <div className="flex flex-col items-center justify-center py-6 text-center space-y-2 ">

//               <Key size={28} className="text-muted-foreground opacity-60" />

//               <p className="text-sm font-medium text-muted-foreground">
//                 No rooms selected
//               </p>

//               <p className="text-xs text-muted-foreground">
//                 Choose a room to start your booking
//               </p>

//               <Link
//                 href="/rooms"
//                 className="text-xs text-main font-medium hover:underline"
//               >
//                 Browse Rooms
//               </Link>

//             </div>
//           )}

//           <div className="space-y-4 mb-4">
//             {rooms.map(room => <><Separator /><RoomCard key={room.room_id} room={room} nights={nights} /></>)}
//           </div>

//         </div>
//         <DrawerFooter className="flex gap-4 flex-row pt-0">
//           <UiCardFooter title="Total Price" subTitle="booking" price={calBookingTotal(booking)} buttonTitle="See Details" onClick={() => router.get('/summery')} />
//           {/* <DrawerClose asChild>

//             <Button variant="outline">Cancel</Button>
//           </DrawerClose>
//           <ButtonUi href="/summery" className="flex-1 py-1.5 text-center">See Details</ButtonUi> */}
//         </DrawerFooter>
//       </DrawerContent>
//     </Drawer>
//   )
// }

import { Link, router, usePage } from "@inertiajs/react"
import {
  BedDouble,
  ChevronRight,
  Key,
  Trash2,
  Utensils,
} from "lucide-react"

import { Button } from "@/components/ui/button"

import {
  Drawer,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
  DrawerTrigger,
} from "@/components/ui/drawer"

import { Separator } from "@/components/ui/separator"

import {
  CheckoutBookingInput,
  RoomSelected,
} from "@/types/home/bookings"

import { SearchRoom } from "@/types/home/client-side"

import Price from "../Price"
import UiCardFooter from "../UiCardFooter"

import {
  calBookingSubTotal,
  calBookingTotal,
  calMealPackageTotal,
  calPriceAdjustment,
  calRoomOnlyTotal,
  calRoomTotal,
} from "@/utils/client/calBooking"

type BookingKeyCartProp = {
  booking: CheckoutBookingInput
  search: SearchRoom
}

/* -------------------------------------------------------------------------- */
/*                                PREVIEW CARD                                */
/* -------------------------------------------------------------------------- */

function SelectedRoomPreview({ room, nights }: { room: RoomSelected, nights: number }) {
  return (
    <div className="flex items-center gap-3 rounded-xl border border-gray-200 bg-white p-3 transition hover:border-main/30 hover:shadow-sm  cursor-pointer">

      {/* Image */}
      <img
        src={room?.image_url ? room.image_url : "/images/placeholders/room-placeholder.jpg"}
        alt={room.title}
        className="h-16 w-20 rounded-sm object-cover"
      />

      {/* Content */}
      <div className="min-w-0 flex-1 space-y-1">

        <div className="flex items-start justify-between gap-2">

          <div className="min-w-0">
            <h4 className="truncate text-sm font-semibold text-neutral-900">   {room.title}    </h4>

            <p className="mt-0.5 text-xs text-neutral-500">
              {room.adults} Adults · {room.children} Children
            </p>
          </div>

          <ChevronRight
            size={16}
            className="mt-0.5 shrink-0 text-neutral-400"
          />
        </div>

        {/* Bottom */}
        <div className=" flex items-center justify-between gap-3">
          <div className="flex flex-wrap items-center gap-2">
            {/* <div className="flex items-center gap-1 rounded-full bg-gray-100 px-2 py-1 text-[11px] text-neutral-600">  <BedDouble size={12} />  Room     </div> */}
            {room.meal_package && (
              <div className="flex items-center gap-1 rounded-full bg-main/10 px-2 py-1 text-[11px] text-main"> <Utensils size={12} /> {room.meal_package.title}      </div>
            )}
          </div>

          <div className="text-sm font-semibold text-neutral-900 whitespace-nowrap">
            <Price value={calRoomTotal(room, nights)} />
          </div>

        </div>
      </div>
    </div>
  )
}

/* -------------------------------------------------------------------------- */
/*                                 ROOM CARD                                  */
/* -------------------------------------------------------------------------- */

function RoomCard({ room, nights, }: { room: RoomSelected, nights: number }) {

  const { meal_package, addons, room_daily_prices, adults, children } = room

  return (
    <div className="space-y-3 border-t-2 pt-4">

      {/* Top */}
      <div className="flex gap-4">

        <img
          src={
            room?.image_url
              ? room.image_url
              : "/images/placeholders/room-placeholder.jpg"
          }
          className="h-20 aspect-video  object-cover"
          alt={room.title}
        />

        <div className="flex-1">

          <h3 className="font-title text-lg font-semibold">
            {room.title}
          </h3>

          <p className="font-p text-sm text-gray-500">
            {adults} Adults · {children} Children
          </p>

          {meal_package && (
            <div className="mt-2 inline-flex items-center gap-1 rounded-full bg-main/10 px-2 py-1 text-[11px] text-main">
              <Utensils size={12} />
              {meal_package.title}
            </div>
          )}

        </div>

      </div>

      {/* Pricing */}
      <div className="space-y-1">

        <div className="flex justify-between border-b-2 border-dashed py-1.5 text-sm text-neutral-600">
          <span>Room</span>
          <span>
            <Price value={calRoomOnlyTotal(room_daily_prices)} />
          </span>
        </div>

        {meal_package && (
          <div className="flex justify-between border-b-2 border-dashed py-1.5 text-sm text-neutral-600">
            <span>{meal_package.title}</span>

            <span>
              <Price
                value={calMealPackageTotal(
                  meal_package,
                  nights,
                  adults + children
                )}
              />
            </span>
          </div>
        )}

        {addons.map((item) => (
          <div
            key={item.id}
            className="flex justify-between border-b-2 border-dashed py-1.5 text-sm text-neutral-600"
          >
            <span>{item.title}</span>
            <span>
              <Price value={0} />
            </span>
          </div>
        ))}

        <div className="flex justify-between py-1.5 text-sm font-semibold">
          <span>Room Total Price</span>

          <span>
            <Price value={calRoomTotal(room, nights)} />
          </span>
        </div>

      </div>

      {/* Actions */}
      <div className="flex justify-end gap-2">

        <Button
          size="sm"
          variant="outline"
          onClick={() =>
            router.get(`/rooms/${room.slug}`, {
              room: room.room_number,
            })
          }
          className="rounded-sm text-sm"
        >
          View Details
        </Button>

        <Button
          onClick={() =>
            router.post("/booking/remove-room", {
              room_id: room.room_id,
            })
          }
          className="rounded-sm text-destructive"
          variant="outline"
          size="icon-sm"
        >
          <Trash2 />
        </Button>

      </div>
    </div>
  )
}

/* -------------------------------------------------------------------------- */
/*                              BOOKING KEY CART                              */
/* -------------------------------------------------------------------------- */

export default function BookingKeyCart({ card }: { card?: boolean }) {

  const { booking, search } = usePage().props as unknown as BookingKeyCartProp

  console.log(booking, search);


  const { rooms } = booking
  const nights = search.nights

  return (
    <Drawer direction="right">

      {/* ------------------------------------------------------------------ */}
      {/* TRIGGER */}
      {/* ------------------------------------------------------------------ */}

      <DrawerTrigger asChild>

        {/* ---------------------------------------------------------------- */}
        {/* BUTTON MODE */}
        {/* ---------------------------------------------------------------- */}

        {!card ? (

          <button className="relative rounded-full border border-main/40 bg-white/90 p-2 backdrop-blur-xs transition hover:scale-105 active:scale-95 sm:bg-black/80">
            <Key size={20} className="text-main" />
            {rooms.length > 0 && (
              <span className="absolute -top-1 -left-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-main px-1 text-[10px] font-semibold text-white">  {rooms.length}    </span>
            )}

          </button>

        ) : (

          /* -------------------------------------------------------------- */
          /* ROOMS MODE */
          /* -------------------------------------------------------------- */

          <div className="space-y-3">

            {/* Header */}
            <div className="flex items-center justify-between">
              <h4 className="text-sm font-semibold text-neutral-700">    Your Reservation     </h4>

              {rooms.length > 0 && (
                <Link href="/summery" className="flex items-center gap-1 text-xs font-medium text-main hover:underline"   > View Summary   </Link>
              )}
            </div>

            {/* Empty State */}
            {rooms.length === 0 ? (
              <div className="rounded-xl border border-dashed border-gray-300 bg-white px-4 py-6 text-center ">
                <div className="mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-white shadow-sm">        <Key size={18} className="text-neutral-400" />   </div>
                <p className="text-sm font-medium text-neutral-700">     No rooms selected yet  </p>
                <p className="mt-1 text-xs text-neutral-500">   Choose a room to begin your stay     </p>
                <Link href="/rooms" className=" **: mt-4 inline-flex items-center justify-center **: rounded-full bg-main px-4 py-2 **: text-xs font-medium text-white **: transition hover:opacity-90  "  >         Browse Rooms  </Link>
              </div>
            ) : (

              /* Room previews */
              <div className="space-y-2">
                {rooms.slice(0, 2).map((room) => (
                  <SelectedRoomPreview key={room.room_id} room={room} nights={nights} />
                ))}
                {rooms.length > 2 && (
                  <div className="rounded-lg border border-dashed border-gray-300 bg-gray-50 py-2 text-center text-xs text-neutral-500">      + {rooms.length - 2} more rooms     </div>
                )}
              </div>

            )}

          </div>

        )}

      </DrawerTrigger>

      {/* ------------------------------------------------------------------ */}
      {/* DRAWER */}
      {/* ------------------------------------------------------------------ */}

      <DrawerContent className="data-[vaul-drawer-direction=bottom]:max-h-[50vh] data-[vaul-drawer-direction=top]:max-h-[50vh]">

        <DrawerHeader className="pb-2">

          <DrawerTitle className="flex items-center gap-2 text-xl font-semibold">
            <Key className="text-main" size={20} />
            Room Keys
          </DrawerTitle>

          <DrawerDescription className="text-sm text-muted-foreground">
            Review your selected rooms before checkout
          </DrawerDescription>

        </DrawerHeader>

        {/* Content */}
        <div className="no-scrollbar overflow-y-auto px-4">

          {rooms.length === 0 && (

            <div className="flex flex-col items-center justify-center space-y-2 py-6 text-center">

              <Key
                size={28}
                className="text-muted-foreground opacity-60"
              />

              <p className="text-sm font-medium text-muted-foreground">
                No rooms selected
              </p>

              <p className="text-xs text-muted-foreground">
                Choose a room to start your booking
              </p>

              <Link
                href="/rooms"
                className="text-xs font-medium text-main hover:underline"
              >
                Browse Rooms
              </Link>

            </div>

          )}

          {/* Room list */}
          <div className="mb-4 space-y-4">

            {rooms.map((room) => (
              <div key={room.room_id}>
                <RoomCard
                  room={room}
                  nights={nights}
                />
              </div>
            ))}

          </div>

          {
            (booking.rooms.length > 1 || booking?.price_data.length > 0) && booking.rooms.length > 0 &&
            <div className="border-2 border-dashed px-4 bg-gray-50/50 mt-8 ">
              {/* 📊 Subtotal */}
              {
                booking.rooms.length > 1 && <div className="flex justify-between text-sm py-2   font-semibold text-neutral-800  ">
                  <span>Subtotal</span>
                  <span>
                    <Price value={calBookingSubTotal(booking)} />
                  </span>
                </div>
              }

              {/* 💰 Price Adjustments */}
              {booking?.price_data?.map((item, index) => {

                const isDiscount = item.direction === 'subtract';

                return (
                  <div key={item.id} className={`flex justify-between text-sm py-2 ${(booking.rooms.length > 1 || index !== 0) && 'border-t-2 border-dashed'}    ${isDiscount ? 'text-green-600' : 'text-neutral-600'} `}  >
                    {/* Left side */}
                    <span className="flex items-center gap-1">
                      {item.name}
                      {item.value_type === 'percentage' && <span className="text-xs text-neutral-400">({Number(item.value)}%)</span>}
                      {item.value_type === 'fixed' && <span className="text-xs text-neutral-400">(fixed)</span>}
                    </span>

                    {/* Right side */}
                    <span className="font-medium">
                      {item.direction === 'add' ? '+' : '-'}{" "}
                      {<Price value={Math.abs(calPriceAdjustment(item, calBookingSubTotal(booking)))} />}
                    </span>
                  </div>
                );
              })}
            </div>
          }
        </div>

        {/* Footer */}
        <DrawerFooter className="flex flex-row gap-4 pt-0">

          <UiCardFooter
            title="Total Price"
            subTitle="booking"
            price={calBookingTotal(booking)}
            buttonTitle="See Details"
            onClick={() => router.get("/summary")}
          />

        </DrawerFooter>

      </DrawerContent>

    </Drawer>
  )
}
