'use client';
import React, { useState, useEffect } from "react";
import ComponentTable from "@/components/mutual/tableView/mutual/TablePlain";
import PaginationComponent from "@/components/mutual/tableView/mutual/UpperPagination";
import LowerPagination from "@/components/mutual/tableView/mutual/LowerPagination";
import { apiPostFetcher } from "@/lib/fetcher";
import { ApiPaginationRequestWithQuery } from "@/validations/mutual/api/requests/validations";
import { TableComponentProps } from "@/validations/mutual/table/type";

const TableComponent: React.FC<TableComponentProps> = ({
    urls,
    schemas,
    translations,
    columns,
    initPagination,
    redirectUrls,
    setSelectedRow,
}) => {
    const defaultPagination = {
        page: initPagination?.page || 1,
        size: initPagination?.size || 10,
        orderFields: initPagination?.orderFields || [],
        orderTypes: initPagination?.orderTypes || [],
        query: initPagination?.query || {},
    }
    const [tableData, setTableData] = useState<any>(null);
    const [orgTableData, setOrgTableData] = useState<any>(null);
    const [tableColumns, setTableColumns] = useState<string[]>([]);
    const [pagination, setPagination] = useState<ApiPaginationRequestWithQuery>(defaultPagination);
    const [apiPagination, setApiPagination] = useState<any>({
        onPage: 1,
        onPageCount: 10,
        totalPage: 1,
        totalCount: 1,
        next: false,
        back: false,
    });

    const handleBack = async () => {
        setPagination({ ...pagination, page: pagination.page > 1 ? pagination.page - 1 : pagination.page });
        await fetchData();
    }
    const handleNext = async () => {
        setPagination({ ...pagination, page: pagination.page < apiPagination.totalPage ? pagination.page + 1 : pagination.page });
        await fetchData();
    }
    const fetchData = async () => {
        const response = await apiPostFetcher({
            url: urls.list,
            isNoCache: true,
            body: {
                page: pagination.page,
                size: pagination.size,
                orderFields: pagination.orderFields,
                orderTypes: pagination.orderTypes,
                query: pagination.query,
            },
        });
        if (response && response.data) {
            const oldData = response.data.data
            setOrgTableData(oldData)
            if (schemas.table) {
                const newData = Object.entries(oldData).map(([key]) => {
                    return schemas.table.safeParse(oldData[key as keyof typeof oldData]).data
                })
                setTableData(newData)
                setTableColumns(columns.table)
            }
            if (response.data.pagination) {
                setApiPagination(response.data.pagination);
            }
        }
    };
    useEffect(() => { fetchData() }, [pagination.page, pagination.size, pagination.orderFields, pagination.orderTypes]);

    const upperPaginationProps = {
        apiPagination,
        pagination,
        setPagination,
        defaultPagination,
    }
    const lowerPaginationProps = {
        pagination: apiPagination,
        handleBack,
        handleNext,
    }
    const tableProps = {
        data: tableData,
        orgData: orgTableData,
        columns: tableColumns,
        translations,
        redirectUrls,
        setSelectedRow,
    }
    return (
        <div>
            <div className="flex flex-col items-center justify-start my-6"><PaginationComponent {...upperPaginationProps} /></div>
            <div className="flex flex-col items-center justify-start my-6"><LowerPagination {...lowerPaginationProps} /></div>
            <div className="flex flex-col items-center justify-start my-6"><ComponentTable {...tableProps} /></div>
        </div>
    );
}

export default TableComponent;