"use client"

import React from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { bookReservations, deleteProperties, deleteReservations, getHistory, getProperties, getReservations, updatePrice, updateStatus } from '@/actions/bmv'
import DataTable from '@/components/table/data-table'
import { Button } from '@/components/ui/button'
import { useDebounce } from '@/hooks/useDebounce'
import { ColumnDef } from '@tanstack/react-table'
import { AlertCircle, ChevronLeft, ChevronRight, ConstructionIcon, CopyIcon, Edit3Icon, RefreshCcw, Search, Send, Settings, Trash2Icon, XIcon } from 'lucide-react'
import { toast } from 'sonner'
import { Switch } from '@/components/ui/switch'
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card"
import { Input } from '@/components/ui/input'
import { formatCurrency } from '@/lib/format-currency'
import { useLoading } from '@/lib/useLoading'
import moment from 'moment-timezone'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import { historyStatus } from '@/lib/history'
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import DeleteDialog from '@/components/delete/delete-dialog'
import SendBooking from './send-booking'
import { cn } from '@/lib/utils'
import BookingDetail from './booking-detail'

const ListReservations = () => {
    const [reservations, setReservations] = React.useState<any[]>([]);
    const [offset, setOffset] = React.useState(0);
    const [hasMore, setHasMore] = React.useState(true);
    const [search, setSearch] = React.useState('');
    const [page, setPage] = React.useState<any | null>(null);
    const debouncedSearch = useDebounce(search, 500);
    const [loadHistroy, setLoadHistory] = React.useState(false)
    const [today , setToday] = React.useState(moment().tz("Asia/Makassar").format("YYYY-MM-DD"))
    const [history, setHistory] = React.useState<any[]>([])
    const {loading, setLoading} = useLoading();
    const [showHistory, setShowHistory] = React.useState(true)

    const fetchData = async ({ value = debouncedSearch, skip = offset }: { value?: string, skip?: number }) => {
        if(loading) setLoading(true)
        setLoading(true);
        const response = await getReservations(skip, value);
        if(response.success){
            setReservations(response.data);
            setHasMore(response.hasMore)
            setPage({
                page : response.currentPage,
                allPage: response.totalPages,
                total: response.total
            })
        }else{
            setHasMore(false);
            setPage({
                page : response.currentPage,
                allPage: response.totalPages,
                total: response.total
            })
            if (offset === 0) setReservations([]);
            toast.error(response.message);
        }
        setLoading(false);
    }

    React.useEffect(() => {
        fetchData({});
        const currentDate = moment().tz("Asia/Makassar").format("YYYY-MM-DD")
        fetchHistory(currentDate)
    }, []);
    
    const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setSearch(e.target.value);
        setOffset(0)
    };

    const nextPage = () => {
        if (hasMore) {
            const skip = offset + 10;
            setOffset(skip)
            fetchData({ skip }); 
        }
    }

    const prevPage = () => {
        const skip = Math.max(0, offset - 10)
        setOffset(skip)
        fetchData({ skip })
    }

    const clearSearch = () => {
        setSearch("")
        fetchData({ value: ""})
    }

    const columns: ColumnDef<any>[] = [
        {
            accessorKey: 'rsvId',
            header: () => <span className='font-bold'>RSV ID</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <div className='flex items-center'>
                        <p className='w-fit text-[13px]'>{row.rsvId}</p>
                        <Button size="sm" variant="ghost" onClick={() => copyToClipboard(row.rsvId)}>
                            <CopyIcon />
                        </Button>
                    </div>
                )
            },
        },
        {
            accessorKey: 'invId',
            header: () => <span className='font-bold'>INV ID</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <div className='flex items-center'>
                        <p className='w-fit text-[13px]'>{row.invId}</p>
                        <Button size="sm" variant="ghost" onClick={() => copyToClipboard(row.invId)}>
                            <CopyIcon />
                        </Button>
                    </div>
                )
            },
        },           
        {
            accessorFn: (row: any) => row.property.name,
            id: 'name',
            header: () => <span className='font-bold'>PROPERTY</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return <p className='w-fit text-[13px] font-medium'>{row.property.name}</p>
            },
        },
        {
            accessorFn: (row: any) => row.start || row.end,
            id: 'date',
            header: () => <span className='font-bold'>DATE</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return <p className='w-fit text-[13px]'>{`${moment(row.start).tz("Asia/Makassar").format("MMM DD")} - ${moment(row.end).tz("Asia/Makassar").format("MMM DD, YYYY")}`}</p>
            },
        },
        {
            accessorFn: (row: any) => `${row.firstname} ${row.lastname}`,
            id: 'guest',
            header: () => <span className='font-bold'>GUEST</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return <p className='w-fit font-medium text-clamp-1 text-[13px]'>{row.firstname} {row.lastname}</p>
            },
        },
        {
            accessorKey: 'paid',
            header: () => <span className='font-bold'>STATUS</span>,
            enableSorting: false,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <Badge variant={row.paid ? "green" : "red"} className='h-8'>
                        <span className='text-[13px]'>{row.paid ? "Paid" : "Pending"}</span>
                    </Badge>
                )
            },
        },
        {
            accessorFn: (row: any) => row.usd || row.idr,
            id: 'price',
            header: () => <span className='font-bold'>PRICE</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return <p className="w-fit before:content-['$'] before:mr-1 font-bold ">{formatCurrency(row.usd)}</p>
            },
        },
        {
            accessorKey: 'action',
            header: () => <span className='font-bold'>ACTION</span>,
            enableSorting: false,
            enableColumnFilter: false,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <div className='flex items-center gap-2'>
                        <BookingDetail 
                            data={row}
                        />
                        <SendBooking 
                            variant={row.paid ? "outline" : "blue"} 
                            disabled={row.paid}
                            onAction={() => {
                                handleBooking(row.rsvId)
                            }}
                        />
                        <DeleteDialog 
                            onDelete={() => handleDelete(row._id)}
                        />
                    </div>
                );
            },
        },
    ]

    const fetchHistory = async (date: string) => {
        setLoadHistory(true)
        const response = await getHistory(date)
        if(response.success){
            setHistory(response.data)
            setLoadHistory(false)
        }else{
            toast.error(response.message)
            setLoadHistory(false)
        }
    }

    const handleDelete = async (id: string) => {
        setLoading(true)
        const response = await deleteReservations(id)
        if(response.success){
            fetchData({});
            fetchHistory(today);
            toast.success(response.message)
        }else{
            toast.error(response.message)
        }
        setLoading(false)
    }

    const handleBooking = async (id: string) => {
        setLoading(true)
        const data = {
            type: "test",
            externalId: id
        }
        const response = await bookReservations(data)
        if(response.success){
            fetchData({});
            fetchHistory(today);
            toast.success(response.message)
            toast(<div className='w-fit'><pre>{JSON.stringify(response.data, null, 2)}</pre></div>)
        }else{
            toast.error(response.message)
        }
        setLoading(false)
    }

    const copyToClipboard = (text: string) => {
        navigator.clipboard
        .writeText(text)
        .then(() => {
            toast.success("Copied to clipboard!");
        })
        .catch(() => {
            toast.error("Failed to copy!");
        });
    };
    return (
        <div className='grid lg:grid-cols-12 gap-6'>
            <div className={cn(showHistory ? "lg:col-span-9" : "col-span-11")}>
                <Card>
                    <CardHeader>
                        <CardTitle>Reservations Overview</CardTitle>
                        <CardDescription>Browse and manage all current and past reservations with search and pagination.</CardDescription>
                    </CardHeader>
                    <CardContent className='space-y-6'>
                        <div className='flex items-center justify-between'>
                            <div className='flex items-center gap-3'>
                                <div className="relative max-w-2xs">
                                    <Input
                                        type="text"
                                        value={search}
                                        placeholder="Search reservations..."
                                        className="border px-2 py-1 rounded-lg"
                                        onChange={handleSearchChange}
                                        onKeyDown={(e) => {
                                            if (e.key === 'Enter') {
                                                fetchData({ value: search })
                                            }
                                        }}
                                    />
                                    {search && (
                                        <div className="absolute top-2 right-2 translate translate-y-0">
                                            <Button 
                                                type="button" 
                                                variant="black" 
                                                size="bullet" 
                                                onClick={clearSearch}
                                            >
                                                <XIcon />
                                            </Button>
                                        </div>
                                    )}
                                </div>
                                <Button 
                                    size="rounded"
                                    onClick={() => {
                                        if(!search) return;
                                        fetchData({ value: search })
                                    }}
                                >
                                    <Search />
                                </Button>
                            </div>
                            <div className="flex items-center gap-3">
                                <Button variant="green" onClick={() => fetchData({})}>
                                    Refresh Data
                                </Button>
                            </div>
                        </div>
                        <DataTable 
                            data={reservations}
                            columns={columns}
                            isLoading={loading}
                            next={nextPage}
                            prev={prevPage}
                            canNextpage={!hasMore}
                            canPrevPage={offset === 0}
                            page={page?.page || 0}
                            allPage={page?.allPage || 0}
                            total={page?.total || 0}
                        />
                    </CardContent>
                </Card>
            </div>
            <div className={cn(showHistory ? "lg:col-span-3" : "col-span-1")}>
                {showHistory ? (
                    <Card className='gap-3 relative'>
                        <div className='absolute top-5 right-5'>
                            <Button 
                                variant="outline" 
                                size="sm" 
                                className='cursor-pointer'
                                onClick={() => {setShowHistory(!showHistory)}}
                            >
                                Hide
                            </Button>
                        </div>
                        <CardHeader>
                            <CardTitle>History</CardTitle>
                            <CardDescription>Recent reservations from the webiste.</CardDescription>
                            <div className='flex items-center gap-3'>
                                <p className=''>Date</p>
                                <Badge variant="blue">
                                    {moment(today).tz("Asia/Makassar").format("DD MMMM YYYY")}
                                </Badge>
                            </div>
                        </CardHeader>
                        <CardContent>
                            <div className='space-y-3'>
                                <Separator />
                                <div className='flex items-center justify-center gap-3 w-full'>
                                    <Button 
                                        variant="semi" 
                                        size="sm" 
                                        className='cursor-pointer'
                                        onClick={() => {
                                            const yesterday = moment(today).subtract(1, "day").tz("Asia/Makassar").format("YYYY-MM-DD")
                                            setToday(yesterday)
                                            fetchHistory(yesterday)
                                        }}
                                    >
                                        <ChevronLeft />
                                    </Button>
                                    <Button 
                                        variant="semi" 
                                        className='cursor-pointer'
                                        onClick={() => {
                                            const currentDate = moment().tz("Asia/Makassar").format("YYYY-MM-DD")
                                            setToday(currentDate)
                                            fetchHistory(currentDate)
                                        }}
                                    >
                                        <RefreshCcw />
                                    </Button>
                                    <Button 
                                        variant="semi" 
                                        size="sm" 
                                        className='cursor-pointer'
                                        onClick={() => {
                                            const tomorrow = moment(today).add(1, "day").tz("Asia/Makassar").format("YYYY-MM-DD")
                                            setToday(tomorrow)
                                            fetchHistory(tomorrow)
                                        }}
                                        disabled={moment(today).isSameOrAfter(moment().tz("Asia/Makassar"), 'day')}
                                    >
                                        <ChevronRight />
                                    </Button>
                                </div>
                                <Separator />
                                <ScrollArea className="h-[60vh] w-full rounded-md border py-2 pl-2 pr-4 space-y-3">
                                    {!loadHistroy ?
                                        history.length > 0 ? (
                                            history.map((h) => {
                                                const status = historyStatus.find(s => s.type === h.type);
                                                const Icon = status?.icon;
                                            
                                                return (
                                                    <Alert key={h._id} className="mb-3" variant={h.type?.toLowerCase()}>
                                                        {Icon && <Icon className="w-5 h-5 text-gray-500" />}
                                                        <AlertTitle>{h.type}</AlertTitle>
                                                        <AlertDescription className='text-[13px]'>
                                                            <p>{h.details} , {h.reason}</p>
                                                            <div className='flex items-center justify-end w-full'>
                                                                <small>{moment(h.createdAt).tz("Asia/Makassar").fromNow()}</small>
                                                            </div>
                                                        </AlertDescription>
                                                    </Alert>
                                                
                                                );
                                            })
                                        ) : (
                                            <div className='flex items-center justify-center w-full p-4'>
                                                <p className='font-medium'>
                                                    No activity today
                                                </p>
                                            </div>
                                        )
                                        :
                                            <div className='flex items-center justify-center w-full p-4'>
                                                <p className='font-medium'>
                                                    Loading Data ...
                                                </p>
                                            </div>
                                    }
                                </ScrollArea>

                            </div>
                        </CardContent>
                    </Card>
                ) : (
                    <div className='flex items-center justify-center w-full'>
                        <Button onClick={() => {setShowHistory(!showHistory)}}>
                            <Settings />
                        </Button>
                    </div>
                )}
            </div>
        </div>
    )
}

export default ListReservations