"use client";
import { usePermission } from "@/utils/auth/permission";
import { cellIndex } from "@/utils/lib/helpers";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { Alert, Badge, Pagination, Spinner } from "flowbite-react";
import { FC, useEffect, useState } from "react";
import ActionButton from "../action-button";
import DataTable from "../dataTable/data-table-fb";
import DeviceTypeForm from "./device-type-form";
import getData from "@/utils/fetch";
import DeleteItem from "../common/delete-item";

type props = {
    filterValue?: string
}

const DeviceTypeList: FC<props> = ({ filterValue }) => {
    const [currentPage, setCurrentPage] = useState(1);
    const [pagination, setPagination] = useState<any>({});
    const [isOpen, setOpen] = useState(false);

    let base_url = `${'/api/v1/device-types'}?page=${currentPage}`;
    let url = filterValue ? `${base_url}&${filterValue}` : base_url;
    const onPageChange = (page: number) => setCurrentPage(page);

    const getDeviceTypes = async () => {
        const {
            data: { data },
            data: { pagination },
        } = await getData(url);
        setPagination(pagination);
        return data;
    };

    const {
        data: deviceTypes,
        isLoading,
        refetch,
    } = useQuery({
        queryKey: ["device-types", { currentPage }],
        placeholderData: keepPreviousData,
        queryFn: () => getDeviceTypes(),
        retry: 0,
    });

    useEffect(() => {
        if (!filterValue?.includes("#")) {
            setCurrentPage(1);
            refetch();
        }
    }, [filterValue]);

    const columns = [
        {
            header: "SL",
            cell: ({ row }: any) => (
                <div className="font-bold">{cellIndex(row.index, pagination)}</div>
            ),
        },
        {
            header: "Name",
            accessorKey: "name",
            cell: ({ row }: any) => {
                const deviceType = row.original;
                return <div>{deviceType.name}</div>;
            },
        },
        {
            header: "Note",
            accessorKey: "note",
            cell: ({ row }: any) => {
                const deviceType = row.original;
                return (
                    <div className="max-w-xs truncate" title={deviceType.note}>
                        {deviceType.note || "N/A"}
                    </div>
                );
            },
        },
        {
            header: "Actions",
            id: "actions",
            cell: ({ row }: any) => {
                const deviceType = row.original;
                const deviceType_id: string = String(deviceType.id);
                const [isEdit, setEdit] = useState(false);

                return (
                    <>
                        <div className="flex">
                            <div className="mr-2">
                                {usePermission("device-types.edit") && (
                                    <>
                                        <ActionButton
                                            type="edit"
                                            onClick={() => setEdit(true)}
                                        />
                                        {isEdit && (
                                            <DeviceTypeForm
                                                deviceType={deviceType}
                                                key={deviceType_id}
                                                setOpen={setEdit}
                                                isOpen={isEdit}
                                                mode="edit"
                                            />
                                        )}
                                    </>
                                )}
                            </div>
                            {usePermission("device-types.delete") && (
                                <DeleteItem
                                    keys="device-types"
                                    url={`/api/v1/device-types/${deviceType_id}`}
                                    name="device type"
                                />
                            )}
                        </div>
                    </>
                );
            },
        },
    ];

    return (
        <>
            {isLoading && (
                <div className="text-center">
                    <Spinner
                        aria-label="Center-aligned spinner example"
                        className="mt-20"
                        size="xl"
                    />
                </div>
            )}

            {deviceTypes !== undefined && (
                <div className="user-list pb-20 shadow-md">
                    <div className="border-b overflow-x-auto">
                        <DataTable data={deviceTypes} columns={columns} loading={isOpen} />
                    </div>

                    <div className="flex justify-between overflow-x-auto">
                        <div className="flex">
                            <Pagination
                                className="ml-2 mt-2"
                                layout="navigation"
                                currentPage={currentPage}
                                totalPages={pagination.total_pages || 0}
                                onPageChange={onPageChange}
                                showIcons
                                nextLabel=""
                                previousLabel=""
                            />
                            <div className="ml-2 mt-5">
                                <p className="text-gray-500">
                                    Showing
                                    <span className="ml-2 mr-1 mt-1 text-gray-900">
                                        {(pagination.current_page - 1) * 10 < 1
                                            ? 1
                                            : (pagination.current_page - 1) * 10}{" "}
                                        - {pagination.current_page * 10}
                                    </span>{" "}
                                    of <span className="text-gray-900"> {pagination.total}</span>{" "}
                                </p>
                            </div>
                        </div>
                        <Pagination
                            currentPage={currentPage}
                            totalPages={pagination.total_pages || 0}
                            onPageChange={onPageChange}
                            className="mr-2 mt-2 text-blue-900 sm:justify-end"
                            showIcons
                            color="blue"
                        />
                    </div>
                </div>
            )}
        </>
    );
};

export default DeviceTypeList; 