"use client"

import React from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { deleteVilla, getVillas, updateStatus, updatePrice } from '@/actions/ttd'
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 { BathIcon, BedIcon, ConstructionIcon, CopyIcon, Edit3Icon, Search, User2, 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 { Badge } from '@/components/ui/badge'
import DeleteDialog from '@/components/delete/delete-dialog'
import { cn } from '@/lib/utils'
import moment from 'moment-timezone'
import UpdatePriceDialog from './update-price-dialog'

const ListVillas = () => {
    const [villas, setVillas] = 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 {loading, setLoading} = useLoading();

    const fetchData = async ({ value = debouncedSearch, skip = offset }: { value?: string, skip?: number }) => {
        if(loading) setLoading(true)
        setLoading(true);
        const response = await getVillas(skip, value);
        if(response.success){
            setVillas(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) setVillas([]);
            toast.error(response.message);
        }
        setLoading(false);
    }

    React.useEffect(() => {
        fetchData({});
    }, []);

    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>[] = [
        {
            accessorFn: (row: any) => row._id,
            id: 'id',
            header: () => <div className='flex items-center justify-center w-full font-bold'>ID</div>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <div className='flex items-center justify-center'>
                        <Button size="sm" variant="ghost" onClick={() => copyToClipboard(row._id)}>
                            <CopyIcon />
                        </Button>
                    </div>
                )
            },
        },
        {
            accessorKey: 'propertyId',
            header: () => <span className='font-bold'>PROPERTY 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.propertyId}</p>
                        <Button size="sm" variant="ghost" onClick={() => copyToClipboard(row.propertyId)}>
                            <CopyIcon />
                        </Button>
                    </div>
                )
            },
        },
        {
            accessorKey: 'roomId',
            header: () => <span className='font-bold'>ROOM 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.roomId}</p>
                        <Button size="sm" variant="ghost" onClick={() => copyToClipboard(row.roomId)}>
                            <CopyIcon />
                        </Button>
                    </div>
                )
            },
        },       
        {
            accessorFn: (row: any) => row.image,
            id: 'image',
            header: () => <span className='font-bold'>IMAGE</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                const imageUrl = row?.image ? `https://imagedelivery.net/wO6ihUlg1M7aee1mES2PLg/${row.image}/public` : "/images/no-picture.png"
                return <Image src={imageUrl} alt={row.name} width={200} height={200} className={cn("object-cover w-16 h-11 rounded-lg", row?.image ? "" : " grayscale")}/>
            },
        },    
        {
            accessorFn: (row: any) => row.name,
            id: 'name',
            header: () => <span className='font-bold'>NAME</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return <p className='w-fit'>{row.name}</p>
            },
        },
        {
            accessorKey: 'address',
            id: 'address',
            header: () => <span className='font-bold'>AREA</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <Badge className='py-1.5' variant="outline">
                        <span className='capitalize'>{row?.area?.name}</span>
                    </Badge>
                )
            },
        },
        {
            accessorFn: (row: any) => row.maxGuests || row.bedroom || row.bathroom,
            accessorKey: 'additional',
            header: () => <div className='flex items-center justify-center w-full font-bold'>FACILITIES</div>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <div className='flex items-center justify-center gap-3'>
                        <Badge className='w-14' variant="blue">
                            <User2 />
                            <span>{row.maxGuests}</span>
                        </Badge>
                        <Badge className='w-14' variant="blue">
                            <BedIcon />
                            <span>{row.bedrooms}</span>
                        </Badge>
                        <Badge className='w-14' variant="blue">
                            <BathIcon />
                            <span>{row.bedrooms}</span>
                        </Badge>
                    </div>
                )
            },
        },
        {
            accessorKey: 'construction',
            header: () => <div className='flex text-yellow-500 items-center justify-center w-full'><ConstructionIcon /></div>,
            enableSorting: false,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <div className='flex items-center justify-center'>
                        <Switch 
                            checked={row?.construction || false} 
                            onCheckedChange={(value) => handleStatus(row._id, "construction", value)}
                            className='data-[state=checked]:bg-gundam-green data-[state=unchecked]:bg-gundam-red'
                        />
                    </div>
                )
            },
        },
        {
            accessorKey: '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.price)}</p>
            },
        },
        {
            accessorKey: 'status',
            header: () => <div className='flex items-center justify-center w-full'>MANAGED</div>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <div className='flex items-center justify-center'>
                        <Switch 
                            checked={row.status} 
                            onCheckedChange={(value) => handleStatus(row._id, "status", value)}
                            className='data-[state=checked]:bg-gundam-green data-[state=unchecked]:bg-gundam-red'
                        />
                    </div>
                )
            },
        },
        {
            accessorKey: 'updatedAt',
            header: () => <span className='font-bold'>LAST UPDATE</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return <p className='w-fit text-sm'>{moment(row.updatedAt).tz("Asia/Makassar").fromNow()}</p>
            },
        },
        {
            accessorKey: 'action',
            header: () => <div className='flex items-center justify-center w-full font-bold'>ACTIONS</div>,
            enableSorting: false,
            enableColumnFilter: false,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <div className='flex items-center justify-center gap-2'>
                        <UpdatePriceDialog 
                            onAction={() => handlePrice(row._id)}
                        />
                        <Button size="sm" variant="blue" asChild>
                            <Link href={`/dashboard/ttd/villas/${row._id}`} onNavigate={() => setLoading(true)}>
                                <Edit3Icon className="h-4 w-4" />
                            </Link>
                        </Button>
                        <DeleteDialog 
                            onDelete={() => handleDelete(row._id)}
                        />
                    </div>
                );
            },
        },
    ]

    const handleDelete = async (id: string) => {
        setLoading(true);
        const response = await deleteVilla(id)
        if(response.success){
            toast.success(response.message);
            fetchData({});
            setLoading(false)
        }else{
            setLoading(false)
            toast.error(response.message);
        }
    }
    const handleStatus = async (id: string, key:string, value: any) => {
        setLoading(true)
        
        const body = {
            key,
            value
        }
        const response = await updateStatus(id, body)
        if(response.success){
            toast.success(response.message);
            fetchData({});
            setLoading(false)
        }else{
            setLoading(false)
            toast.error(response.message);
        }
    }

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

    const copyToClipboard = (text: string) => {
        navigator.clipboard
        .writeText(text)
        .then(() => {
            toast.success("Copied to clipboard!");
        })
        .catch(() => {
            toast.error("Failed to copy!");
        });
    };
    return (
        <div>
            <Card>
                <CardHeader>
                    <CardTitle>Explore All Villas</CardTitle>
                    <CardDescription>Browse through our curated collection of villas available for booking in Bali, managed by The Tropical Door.</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 villas..."
                                    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="semi" asChild>
                                <Link href="/dashboard/ttd/villas/add" onNavigate={() => setLoading(true)}>
                                    Add Data
                                </Link>
                            </Button>
                            <Button variant="green" onClick={() => fetchData({})}>
                                Refresh Data
                            </Button>
                        </div>
                    </div>
                    <DataTable 
                        data={villas}
                        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>
    )
}

export default ListVillas