"use client";

import { FC, useEffect, useState } from "react";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { Spinner, Tooltip } from "flowbite-react";

import getData from "@/utils/fetch";
import { cellIndex } from "@/utils/lib/helpers";
import CustomPagination from "../common/pagination";
import DataTable from "../dataTable/data-table-fb";


type Props = {
    clientId?: string | null;
};

type History = {
    id: string;
    description: string;
    staff?: string;
    old_data?: Record<string, unknown> | null;
    new_data?: Record<string, unknown> | null;
    updated_at?: string;
};

const formatKey = (key: string) =>
    key
        .split("_")
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join(" ");

const renderRecord = (record?: Record<string, unknown> | null) => {
    if (!record || Object.keys(record).length === 0) {
        return <p className="text-sm text-gray-500">N/A</p>;
    }

    return (
        <div className="space-y-1">
            {Object.entries(record).map(([key, value]) => (
                <p key={key} className="text-xs capitalize leading-snug">
                    <span className="font-semibold">{formatKey(key)}:</span>{" "}
                    {typeof value === "object"
                        ? JSON.stringify(value)
                        : String(value ?? "")}
                </p>
            ))}
        </div>
    );
};

const ClientHistory: FC<Props> = ({ clientId }) => {
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [pagination, setPagination] = useState<any>({});

    const onPageChange = (page: number) => setCurrentPage(page);

    const baseUrl = `/api/v1/clients-history/${clientId}?page=${currentPage}`;

    const getHistories = async () => {
        const {
            data: { data, pagination },
        } = await getData(baseUrl);
        setPagination(pagination);
        return data as History[];
    };

    const {
        data: histories,
        isLoading,
        isFetching,
        refetch,
    } = useQuery({
        queryKey: ["histories", { currentPage }],
        placeholderData: keepPreviousData,
        queryFn: () => getHistories(),
        refetchOnWindowFocus: false,
    });

    const columns = [
        {
            header: "SL",
            cell: ({ row }: any) => (
                <div className="font-bold">{cellIndex(row.index, pagination)}</div>
            ),
        },
        {
            header: "Staff",
            accessorKey: "staff",
            cell: ({ row }: any) => (
                <p className="capitalize text-sm">
                    {row.original?.staff ?? "N/A"}
                </p>
            ),
        },
        {
            header: "Old Data",
            accessorKey: "old_data",
            cell: ({ row }: any) => renderRecord(row.original?.old_data),
        },
        {
            header: "New Data",
            accessorKey: "new_data",
            cell: ({ row }: any) => renderRecord(row.original?.new_data),
        },
        {
            header: "Description",
            accessorKey: "description",
            cell: ({ row }: any) => (
                <div className="capitalize text-sm line-clamp-1">
                    <Tooltip content={row.original?.description}>
                        {row.original?.description}
                    </Tooltip>
                </div>
            ),
        },
        {
            header: "Date",
            accessorKey: "created_at",
        },
    ];

    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>
            )}
            {histories !== undefined && (
                <div className="user-list pb-20 shadow-md">
                    <div className="border-b dark:border-t dark:border-gray-500">
                        <DataTable data={histories} columns={columns} />
                    </div>
                    <CustomPagination
                        pagination={pagination}
                        currentPage={currentPage}
                        onPageChange={onPageChange}
                        keys="histories"
                    />
                </div>
            )}
        </>
    );
};

export default ClientHistory
