"use client";
import { usePermission } from "@/utils/auth/permission";
import getData from "@/utils/fetch";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { FC, useEffect, useState } from "react";
import ActionButton from "../action-button";
import DeleteItem from "../common/delete-item";
import DataTable from "../dataTable/data-table-fb";
import Spinner from "../spinner";
import TjBoxForm from "./tj-box-form";
import CustomPagination from "../common/pagination";

type props = {
    filterValue?: string
}

const TjBoxList: FC<props> = ({ filterValue }) => {
    const [currentPage, setCurrentPage] = useState(1);
    const [pagination, setPagination] = useState<any>();
    const onPageChange = (page: number) => setCurrentPage(page);
    let base_url = `/api/v1/tj-boxes?page=${currentPage}`;
    let url = filterValue ? `${base_url}&${filterValue}` : base_url;

    const getTjBoxes = async () => {
        const {
            data: { data },
            data: { pagination },
        } = await getData(url);
        setPagination(pagination);
        return data;
    };

    const {
        data: tjBoxes,
        refetch,
        isLoading,
        isFetching,
    } = useQuery({
        queryKey: ["tj-boxes"],
        queryFn: () => getTjBoxes(),
        refetchOnWindowFocus: false,
    });

    useEffect(() => {
        if (!filterValue?.includes("#")) {
            setCurrentPage(1);
            refetch();
        }
    }, [filterValue]);
    const columns = [
        {
            header: "SL",
            cell: ({ row }: any) => (
                <div className="font-bold">{row.index + 1}</div>
            ),
        },
        {
            header: "Name",
            accessorKey: "name",
        },
        {
            header: "Device",
            accessorKey: "device.name",
            cell: ({ row }: any) => (
                <div>{row.original.device?.name || '-'}</div>
            ),
        },
        {
            header: "Zone",
            accessorKey: "zone.name",
            cell: ({ row }: any) => (
                <div>{row.original.zone?.name || '-'}</div>
            ),
        },
        {
            header: "Latitude",
            accessorKey: "latitude",
        },
        {
            header: "Longitude",
            accessorKey: "longitude",
        },
        {
            header: "Status",
            accessorKey: "status",
            cell: ({ row }: any) => (
                <div className={`px-2 py-1 rounded-full text-xs font-medium inline-block ${row.original.status === 'active'
                    ? 'bg-green-100 text-green-800'
                    : 'bg-red-100 text-red-800'
                    }`}>
                    {row.original.status}
                </div>
            ),
        },
        {
            header: "Actions",
            id: "actions",
            cell: ({ row }: any) => {
                const tjBox = row.original;
                const tjBox_id: string = String(tjBox.id);
                const [isOpen, setOpen] = useState(false);
                return (
                    <div className="flex">
                        {usePermission("tj-boxes.edit") && (
                            <>
                                <div className="mr-2" onClick={() => setOpen(true)}>
                                    <ActionButton type="edit" />
                                </div>
                                <div>
                                    {isOpen && (
                                        <TjBoxForm isOpen={isOpen} setOpen={setOpen} tjBox_id={tjBox_id} mode="edit" />
                                    )}
                                </div>
                            </>
                        )}
                        {usePermission("tj-boxes.delete") && (
                            <div className="mr-2">
                                <DeleteItem
                                    name="tj-box"
                                    keys={"tj-boxes"}
                                    url={`/api/v1/tj-boxes/${tjBox_id}`}
                                />
                            </div>
                        )}
                    </div>
                );
            },
        },
    ];

    return (
        <>
            {(isLoading || isFetching) && (
                <div className="relative">
                    <div className="grid fixed left-2/4 top-1/2 z-50">
                        <Spinner size="xl" color="purple" />
                    </div>
                </div>
            )}
            {tjBoxes !== undefined && (
                <div className="tj-box-list pb-20 shadow-md min-h-96">
                    <div className="border-b overflow-x-auto">
                        <DataTable data={tjBoxes} columns={columns} />
                    </div>
                    <CustomPagination
                        pagination={pagination}
                        currentPage={currentPage}
                        onPageChange={onPageChange}
                        keys="tj-boxes"
                    />
                </div>
            )}
        </>
    );
};

export default TjBoxList;
