"use client";
import { usePermission } from "@/utils/auth/permission";
import { cellIndex, useParseFloat } from "@/utils/lib/helpers";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import axios from "axios";
import { Alert, Badge, Kbd, Pagination, Spinner } from "flowbite-react";
import { FC, useEffect, useState } from "react";
import { HiInformationCircle } from "react-icons/hi";
import ActionButton from "../action-button";
import DeleteRecord from "../common/delete-record";
import DataTable from "../dataTable/data-table-fb";
import getData from "@/utils/fetch";
import MoneyFormat from "../common/money";
import DeleteItem from "../common/delete-item";

type props = {
    filterValue?: string
    api?: string
}

const FundTransactionList: FC<props> = ({ filterValue, api = `/api/v1/fund-transactions` }) => {
    const [currentPage, setCurrentPage] = useState(1);
    const [pagination, setPagination] = useState<any>({});
    const transactionColor = {
        deposit: "text-green-600",
        withdraw: "text-red-600",
        expense: "text-red-600",
        salary: "text-red-600",
        transfer: "text-yellow-600",
        badge: {
            deposit: "success",
            withdraw: "failure",
            expense: "failure",
            salary: "failure",
            transfer: "warning",
        }
    }

    const onPageChange = (page: number) => setCurrentPage(page);
    let base_url = `${api}?page=${currentPage}`;
    let url = filterValue ? `${base_url}&${filterValue}` : base_url;

    const getTransactions = async () => {
        const {
            data: { data },
            data: { pagination },
        } = await getData(url);
        setPagination(pagination);
        return data;
    };

    const {
        data: transactions,
        isLoading,
        isFetching,
        refetch,
    } = useQuery({
        queryKey: ["fund-transactions", { currentPage }],
        placeholderData: keepPreviousData,
        queryFn: () => getTransactions(),
        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: "Date",
            accessorKey: "created_at",
            cell: ({ row }: any) => {
                const transaction = row.original;
                return <div>{transaction.created_at}</div>;
            },
        },
        {
            header: "Fund",
            accessorKey: "fund.name",
            cell: ({ row }: any) => {
                const transaction = row.original;
                return <div>{transaction.fund?.name}</div>;
            },
        },
        {
            header: "Type",
            accessorKey: "type",
            cell: ({ row }: any) => {
                const transaction = row.original;
                return (
                    <Badge color={`${transactionColor.badge[transaction.transaction_type]}`} className="inline-block">
                        {transaction.transaction_type}
                    </Badge>
                );
            },
        },
        {
            header: "Amount",
            accessorKey: "amount",
            cell: ({ row }: any) => {
                const transaction = row.original;
                return (
                    <div className={`${transactionColor[transaction.transaction_type]}`}>
                        <MoneyFormat amount={useParseFloat(transaction?.amount)} />
                    </div>
                );
            },
        },
        {
            header: "Note",
            accessorKey: "note",
        },
        {
            header: "Actions",
            cell: ({ row }: any) => {
                const transaction = row.original;
                const transaction_id: string = String(transaction.id);
                return (
                    <div className="flex">
                        {usePermission("funds.delete") && (
                            <DeleteItem
                                keys="fund-transactions"
                                url={`/api/v1/fund-transactions/${transaction_id}`}
                                name="transaction"
                            />
                        )}
                    </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>
            )}
            {transactions !== undefined && (
                <div className="user-list pb-20 shadow-md">
                    <div className="border-b overflow-x-auto">
                        <DataTable data={transactions} columns={columns} loading={isLoading} />
                    </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 FundTransactionList; 