"use client"

import React from 'react'
import { useDebounce } from '@/hooks/useDebounce';
import { useLoading } from '@/lib/useLoading';
import { deleteArea, getAreas } from '@/actions/ttd';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card"
import { toast } from 'sonner';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { CopyIcon, Edit3Icon, Search, XIcon } from 'lucide-react';
import DataTable from '@/components/table/data-table';
import { ColumnDef } from '@tanstack/react-table';
import Image from 'next/image';
import EditForm from './edit-form';
import AddForm from './add-form';
import DeleteDialog from '@/components/delete/delete-dialog';
import moment from 'moment-timezone';

const ListAreas = () => {
    const [areas, setAreas] = 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 [edit, setEdit] = React.useState(false);
    const [selected, setSelected] = React.useState<any | null>(null);

    const fetchData = async ({ value = debouncedSearch, skip = offset }: { value?: string, skip?: number }) => {
        if(loading) setLoading(true)
        setLoading(true);
        const response = await getAreas(skip, value);
        if(response.success){
            setAreas(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) setAreas([]);
            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>[] = [
        {
            accessorKey: 'image',
            header: () => <div className='flex items-center justify-center w-full font-bold'>IMAGE</div>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return (
                    <div className='flex items-center justify-center'>
                        <Image 
                            src={`https://imagedelivery.net/wO6ihUlg1M7aee1mES2PLg/${row.image}/public`}
                            alt={row.name}
                            width={500}
                            height={500}
                            className="object-center h-14 w-28"
                        />
                    </div>
                )
            },
        },
        {
            accessorKey: 'name',
            header: () => <span className='font-bold'>AREA NAME</span>,
            enableSorting: true,
            enableColumnFilter: false,
            enableGlobalFilter: true,
            cell: (info: any) => {
                const row = info.row.original;
                return <p className='w-fit font-medium'>{row.name}</p>
            },
        },
        {
            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 '>{moment(row.updatedAt).tz("Asia/Makassar").fromNow()}</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'>
                        <Button 
                            size="sm"
                            variant="blue"
                            onClick={() => {
                                setSelected(row)
                                setEdit(true)
                            }}
                        >
                            <Edit3Icon />
                        </Button>
                        <DeleteDialog 
                            onDelete={() => handleDelete(row._id)}
                        />
                    </div>
                );
            },
        },
    ]

    const handleDelete = async (id: string) => {
        setLoading(true)
        const response = await deleteArea(id)
        if(response.success){
            toast.success(response.message)
            setSelected(null)
            setEdit(false)
            fetchData({})
        }else{
            toast.error(response.message)
        }
        setLoading(false)
    }
    return (
        <div className="grid grid-cols-3 gap-6">
            <Card className='h-fit'>
                <CardHeader>
                    <CardTitle>
                        {edit ? ("Edit areas") : ("Create new areas")}
                    </CardTitle>
                    <CardDescription>{edit ? ("Update the details for this existing area.") : ("Fill in the details to add a new area to the system.")}</CardDescription>
                </CardHeader>
                <CardContent>
                    {edit ? (
                        <EditForm 
                            data={selected}
                            onAction={() => fetchData({})}
                            onReset={() => {
                                setEdit(false)
                                setSelected(null)
                            }}
                        />
                    ) : (
                        <AddForm 
                            onAction={() => fetchData({})}
                        />
                    )}
                </CardContent>
            </Card>
            <div className='col-span-2'>
                <Card>
                    <CardHeader>
                        <CardTitle>API Access Tokens</CardTitle>
                        <CardDescription>Manage the list of tokens used to access the API.</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 areas..."
                                        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={areas}
                            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>
    )
}

export default ListAreas