import { useEffect, useState } from "react";
import { router, usePage } from "@inertiajs/react";
import { Card, CardContent, } from "@/components/ui/card";
import { Tabs, TabsList, TabsTrigger, TabsContent, } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { CalendarX, SquarePen } from "lucide-react";
import { DeleteAlertButton } from "@/components/core/DeleteAlertButton";
import { TablePagination } from "@/components/core/TablePagination";
import RoomAvailabilityMaker from "./RoomAvailabilityMaker";
import { Button } from "@/components/ui/button";

type Room = { id: number; room_number: string };


export default function RoomAvailability() {

    const { rooms, availability, activeRoomId, } = usePage().props as any
    const [activeTab, setActiveTab] = useState(String(activeRoomId));
    const [openMaker, setOpenMaker] = useState(false)
    const [selectedAvailability, setSelectedAvailability] = useState<any | null>(null);
    const [editAvailability, setEditAvailability] = useState<any | null>(null);



    /**
     * SWITCH ROOM (TAB CHANGE)
     */
    const changeRoom = (roomId: string) => {
        setActiveTab(roomId);

        router.get(
            "/dashboard/booking-calendar",
            {
                room_id: roomId,
            },
            {
                preserveState: true,
                replace: true,
            }
        );
    };

    const getDateBlocks = (start: string, end: string) => {
        const dates = [];

        const current = new Date(start);
        const last = new Date(end);

        while (current <= last) {
            dates.push(new Date(current));
            current.setDate(current.getDate() + 1);
        }

        return dates;
    };

    useEffect(() => {
        if (availability.data.length > 0) {
            setSelectedAvailability(availability.data[0]);
        }
    }, [availability]);

    return (
        <Card className="border rounded-sm p-0 bg-background/40">
            <CardContent className="p-4 space-y-4">
                {/* TABS */}
                <Tabs value={activeTab} onValueChange={changeRoom}>
                    <div className="flex justify-between">
                        <TabsList>{rooms.map((room: Room) => (<TabsTrigger key={room.id} value={String(room.id)}>{room.room_number}</TabsTrigger>))} </TabsList>
                        <RoomAvailabilityMaker open={openMaker} setOpen={setOpenMaker} rooms={rooms} availability={editAvailability} setAvailability={setEditAvailability} />
                    </div>

                    {/* CONTENT */}
                    {rooms.map((room: Room) => (
                        <TabsContent key={room.id} value={String(room.id)}      >

                            {availability.data.length === 0 ?
                                <div className="flex flex-col items-center justify-center py-6 text-center space-y-4">
                                    <div className="p-4 rounded-full bg-muted">  <CalendarX className="w-10 h-10 text-primary" />      </div>
                                    <div className="space-y-1">
                                        <h3 className="text-lg font-semibold">No Availability Records Found </h3>
                                        <p className="text-sm text-muted-foreground max-w-sm"> There are no bookings, blocks, or availability changes for this room in the selected date range. Start by adding a booking or blocking dates manually. </p>
                                    </div>
                                </div>
                                :
                                <>

                                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 ">

                                        {/* LEFT SIDE */}
                                        <div className="lg:col-span-2 overflow-hidden">

                                            <div className="px-4 py-3 border-b">
                                                <p className="text-xs uppercase tracking-widest text-gray-500">  Availability Activity Log </p>
                                            </div>

                                            <Table>
                                                <TableHeader>
                                                    <TableRow>
                                                        <TableHead>#</TableHead>
                                                        <TableHead>Date Range</TableHead>
                                                        <TableHead>Status</TableHead>
                                                        <TableHead>Source</TableHead>
                                                        <TableHead>Message</TableHead>
                                                        <TableHead className="text-end">Action</TableHead>
                                                    </TableRow>
                                                </TableHeader>

                                                <TableBody>
                                                    {availability.data.map((item: any) => (
                                                        <TableRow key={item.id} onClick={() => setSelectedAvailability(item)} className={`cursor-pointer transition hover:bg-muted/50 ${selectedAvailability?.id === item.id ? "bg-muted/50" : ""}`}  >
                                                            <TableCell className="text-muted-foreground">   {item.id}   </TableCell>
                                                            <TableCell className="font-medium">{new Date(item.start_date).toLocaleDateString()} →{" "}   {new Date(item.end_date).toLocaleDateString()} </TableCell>
                                                            {/* <TableCell> <Badge className={item.status === "booked" ? "bg-red-500/10 text-red-600" : item.status === "blocked" ? "bg-slate-500/10 text-slate-700" : "bg-amber-500/10 text-amber-600"}   >  {item.status}  </Badge> </TableCell> */}
                                                            <TableCell>  <Badge variant={item.status === "booked" ? "default" : item.status === "blocked" ? "destructive" : "outline"}  >{item.status}  </Badge>      </TableCell>
                                                            <TableCell className="capitalize text-muted-foreground">{item.source}</TableCell>
                                                            <TableCell className="text-muted-foreground max-w-50 truncate">{item.message ?? "-"}</TableCell>
                                                            <TableCell className="text-right flex gap-2 justify-end">

                                                                <Button variant='outline' size='icon-sm' onClick={() => { setEditAvailability(item), setOpenMaker(true) }}><SquarePen /></Button>
                                                                <DeleteAlertButton deleteId={item.id} model="room-availability" title="Availability Record" />
                                                            </TableCell>
                                                        </TableRow>
                                                    ))}
                                                </TableBody>


                                            </Table>
                                            <TablePagination links={availability.links} meta={availability} />
                                        </div>

                                        {/* RIGHT SIDE DETAILS */}
                                        <div className="border rounded-sm overflow-hidden bg-background">

                                            {selectedAvailability ? (
                                                <div className="space-y-5 p-4">

                                                    <div>
                                                        <p className="text-xs uppercase tracking-widest text-muted-foreground">    Availability Details  </p>
                                                        <div className="flex justify-between">
                                                            <h2 className=" font-semibold mt-1">   Record #{selectedAvailability.id}     </h2>

                                                            <div className="flex items-center gap-2">
                                                                <span className="text-sm text-muted-foreground capitalize"> {selectedAvailability.status} via {selectedAvailability.source} </span>
                                                            </div>
                                                        </div>
                                                    </div>


                                                    {/* DATE RANGE */}
                                                    <div className="space-y-2">
                                                        <p className="text-sm font-medium">Date Range</p>
                                                        <div className="text-sm text-muted-foreground">   {new Date(selectedAvailability.start_date).toDateString()}  {" → "}  {new Date(selectedAvailability.end_date).toDateString()}  </div>
                                                    </div>

                                                    {/* DATE BLOCKS */}
                                                    <div className="space-y-2">
                                                        <p className="text-sm font-medium">Reserved / Blocked Days   </p>
                                                        <div className="flex flex-wrap gap-2">  {getDateBlocks(selectedAvailability.start_date, selectedAvailability.end_date).map((date, index) =>
                                                            <div key={index} className="px-2 py-1.5 rounded-sm border border-primary/20 bg-primary/10 text-primary text-xs  dark:border-primary/60 dark:bg-primary/20 dark:text-primary-foreground">
                                                                <div >  {date.toLocaleDateString("en-US", { day: "2-digit", month: "short", })}</div>
                                                            </div>)}
                                                        </div>
                                                    </div>

                                                    {/* MESSAGE */}
                                                    <div className="space-y-1">
                                                        <p className="text-sm font-medium">  Message   </p>
                                                        <p className="text-sm text-muted-foreground"> {selectedAvailability.message || "No message"}   </p>
                                                    </div>

                                                    {/* META */}
                                                    <div className="space-y-3 border-t pt-4">

                                                        <div className="flex justify-between text-sm">
                                                            <span className="text-muted-foreground">  Created By</span>
                                                            <span>  {selectedAvailability.created_by || "System"}</span>
                                                        </div>

                                                        <div className="flex justify-between text-sm">
                                                            <span className="text-muted-foreground">Updated </span>
                                                            <span>{new Date(selectedAvailability.updated_at).toLocaleString()}   </span>
                                                        </div>

                                                    </div>
                                                </div>
                                            ) : (
                                                <div className="p-10 text-center text-muted-foreground">
                                                    Select a record
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </>
                            }
                        </TabsContent>
                    ))}
                </Tabs>
            </CardContent>
        </Card>
    );
}

// in the system are are many rooms i show thsoe are as tabls and each one have table for show each rooms availitliy recored and need to ad pagination. when change tab or pagniaction it need to be get and show i wil,l give you the section compoent write a full working code and controller code i use react ts and larevel inersia


// import React, { useState } from "react";
// import { Card, CardContent } from "@/components/ui/card";
// import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
// import { Badge } from "@/components/ui/badge";
// import { ScrollArea } from "@/components/ui/scroll-area";
// import { cn } from "@/lib/utils";
// import {
//     Table,
//     TableBody,
//     TableCell,
//     TableHead,
//     TableHeader,
//     TableRow,
// } from "@/components/ui/table";
// import { Button } from "@/components/ui/button";
// import { Plus } from "lucide-react";
// import RoomAvailabilityMaker from "./RoomAvailabilityMaker";
// /**
//  * Dummy room data
//  */
// const rooms = [
//     {
//         id: 1,
//         name: "Deluxe Room",
//         number: "101",
//         data: {
//             booked: 3,
//             pending: 2,
//             blocked: 1,
//             free: 10,
//         },
//         logs: [
//             { date: "2026-05-14", status: "booked", note: "John Doe" },
//             { date: "2026-05-15", status: "blocked", note: "Maintenance" },
//             { date: "2026-05-16", status: "pending", note: "Awaiting payment" },
//         ],
//     },
//     {
//         id: 2,
//         name: "Luxury Suite",
//         number: "201",
//         data: {
//             booked: 5,
//             pending: 1,
//             blocked: 0,
//             free: 8,
//         },
//         logs: [
//             { date: "2026-05-14", status: "booked", note: "Booking #A21" },
//             { date: "2026-05-18", status: "pending", note: "Hold request" },
//         ],
//     },
//     {
//         id: 3,
//         name: "Luxury Suite",
//         number: "202",
//         data: {
//             booked: 5,
//             pending: 1,
//             blocked: 0,
//             free: 8,
//         },
//         logs: [
//             { date: "2026-05-14", status: "booked", note: "Booking #A21" },
//             { date: "2026-05-18", status: "pending", note: "Hold request" },
//         ],
//     },
// ];

// /**
//  * STATUS STYLE MAP
//  */
// const statusStyle: Record<string, string> = {
//     booked: "bg-red-500/10 text-red-700 border-red-200",
//     pending: "bg-amber-500/10 text-amber-700 border-amber-200",
//     blocked: "bg-slate-900 text-white",
//     free: "bg-emerald-500/10 text-emerald-700 border-emerald-200",
// };

// /**
//  * STATUS BADGE
//  */
// function StatusBadge({ status }: { status: string }) {
//     return (
//         <Badge className={cn("text-[11px] border", statusStyle[status])}>
//             {status}
//         </Badge>
//     );
// }

// /**
//  * ROOM CARD CONTENT
//  */
// function RoomContent({ room }: any) {


//     const logs = [
//         {
//             start: "2026-05-10",
//             end: "2026-05-12",
//             status: "booked",
//             source: "booking.com",
//             message: "Auto synced reservation",
//             user: "System",
//             created: "2026-05-09 10:22",
//         },
//         {
//             start: "2026-05-13",
//             end: "2026-05-15",
//             status: "blocked",
//             source: "admin",
//             message: "Maintenance work",
//             user: "Admin",
//             created: "2026-05-11 09:10",
//         },
//         {
//             start: "2026-05-16",
//             end: "2026-05-18",
//             status: "pending",
//             source: "website",
//             message: "Pending guest confirmation",
//             user: "System",
//             created: "2026-05-12 14:40",
//         },
//     ];

//     return (
//         <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">

//             {/* LEFT: TABLE (unchanged) */}
//             <div className="lg:col-span-2   overflow-hidden h-fit">

// <div className="px-2 py-3 border-b ">
//     <p className="text-[11px] uppercase tracking-widest text-gray-500">
//         Availability Activity Log
//     </p>
// </div>
// {/* <div>
//     <h2 className="text-sm font-semibold">Availability List</h2>
//     <p className="text-xs text-gray-500">All rooms are currently free (demo state)</p>
// </div> */}



//                 <Table>
//                     <TableHeader>
//                         <TableRow>
//                             <TableHead>Date Range</TableHead>
//                             <TableHead>Status</TableHead>
//                             <TableHead>Source</TableHead>
//                             {/* <TableHead>Message</TableHead> */}
//                             <TableHead>User</TableHead>
//                             <TableHead>Created</TableHead>
//                         </TableRow>
//                     </TableHeader>

//                     <TableBody>
//                         {logs.map((log, i) => (
//                             <TableRow key={i} className="hover:bg-muted/20 transition">

//                                 <TableCell className="font-medium text-gray-900">
//                                     {log.start} → {log.end}
//                                 </TableCell>

//                                 <TableCell>
//                                     <Badge className={`
//                                 text-[11px]
//                                 ${log.status === "booked" && "bg-red-50 text-red-600"}
//                                 ${log.status === "blocked" && "bg-gray-100 text-gray-700"}
//                                 ${log.status === "pending" && "bg-amber-50 text-amber-600"}
//                             `}>
//                                         {log.status}
//                                     </Badge>
//                                 </TableCell>

//                                 <TableCell className="text-gray-600 capitalize">
//                                     {log.source}
//                                 </TableCell>

//                                 {/* <TableCell className="text-gray-700">
//                                     {log.message}
//                                 </TableCell> */}

//                                 <TableCell className="text-gray-600">
//                                     {log.user}
//                                 </TableCell>

//                                 <TableCell className="text-gray-500">
//                                     {log.created}
//                                 </TableCell>

//                             </TableRow>
//                         ))}
//                     </TableBody>
//                 </Table>
//             </div>

//             {/* RIGHT: SUMMARY PANEL */}
//             <div className="space-y-3">

//                 <div className="rounded-sm border bg-white p-4">
//                     <p className="text-[11px] uppercase tracking-widest text-gray-500 mb-3">
//                         Status Overview
//                     </p>

//                     <div className="space-y-3 text-sm">

//                         <div className="flex justify-between">
//                             <span className="text-gray-600">Booked</span>
//                             <span className="font-semibold text-red-600">{2}</span>
//                         </div>

//                         <div className="flex justify-between">
//                             <span className="text-gray-600">Pending</span>
//                             <span className="font-semibold text-amber-600">{4}</span>
//                         </div>

//                         <div className="flex justify-between">
//                             <span className="text-gray-600">Blocked</span>
//                             <span className="font-semibold text-gray-700">{2}</span>
//                         </div>
//                     </div>
//                 </div>

//                 {/* Optional extra insights */}
//                 <div className="rounded-sm border bg-white p-4">
//                     <p className="text-[11px] uppercase tracking-widest text-gray-500 mb-3">
//                         Quick Insight
//                     </p>

//                     <div className="text-sm text-gray-600 space-y-2">
//                         <p>• Most activity: <span className="font-medium text-gray-900">Booked</span></p>
//                         <p>• Source: <span className="font-medium text-gray-900">Booking.com sync</span></p>
//                         <p>• Peak range: <span className="font-medium text-gray-900">Next 7 days</span></p>
//                     </div>
//                 </div>

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

// /**
//  * MAIN COMPONENT
//  */
// export default function RoomAvailability() {

//     const [activeTab, setActiveTab] = useState("1");

//     const [openMaker, setOpenMaker] = useState(false)

//     return (

//         <Card className="shadow-none border-border/60  p-0 rounded-sm ">

//             <CardContent className="p-4 space-y-4">

//                 <Tabs value={activeTab} onValueChange={setActiveTab} className="h-fit">

//                     <div className="flex justify-between itmes-center">
//                         {/* Tabs Header */}
//                         <TabsList  >{rooms.map((room) => <TabsTrigger key={room.id} value={String(room.id)}>{room.number}</TabsTrigger>)}</TabsList>
//                         <RoomAvailabilityMaker open={openMaker} setOpen={setOpenMaker} rooms={rooms} availability={null} setAvailability={() => { }} />
//                     </div>

//                     {/* Tabs Content */}
//                     {rooms.map((room) => (
//                         <TabsContent key={room.id} value={String(room.id)} >

//                             <RoomContent room={room} />

//                         </TabsContent>
//                     ))}

//                 </Tabs>

//             </CardContent>

//         </Card>
//     );
// }