'use client'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/mutual/shadcnui/table";
import { useEffect, useState } from "react";
import { TableProps } from "@/validations/mutual/table/type";

const ComponentTablePlain: React.FC<TableProps> = ({
    data, orgData, columns, translations, redirectUrls, setSelectedRow
}) => {
    const [tableData, setTableData] = useState<any>(data);
    useEffect(() => {
        setTableData(data);
    }, [data]);

    const renderColumns = () => [translations?.rows, ...columns].map((column, index) => <TableHead key={`headers-${index}`}>{column}</TableHead>)
    const renderRows = () => (
        <>{tableData?.map((item: any, index: number) => {
            return (
                <TableRow key={`${index}-row`} >
                    <TableCell>{index + 1}</TableCell>
                    {
                        Object.entries(item).map(([key, value]: [string, any]) => (<TableCell key={`${index}-column-${key}`}>{value}</TableCell>))
                    }
                    {
                        Object.values(redirectUrls?.table || {}).map((redirectUrl: any, index: number) => {
                            return <TableCell className="cursor-pointer w-4" key={`${index}-action-${index}`} onClick={() => setSelectedRow?.(orgData[index])}>{redirectUrl}</TableCell>
                        })
                    }
                </TableRow>
            )
        })}</>
    )
    const noDataFound = (<>No Data Found</>)
    const renderTable = (
        <Table><TableHeader><TableRow>{renderColumns()}</TableRow></TableHeader><TableBody>{renderRows()}</TableBody></Table>
    )
    return (
        <>
            <div className="flex flex-row justify-between gap-2">
                {Object.values(redirectUrls?.page || {}).map((action, index) => (<div className="flex flex-row justify-center items-center gap-2" key={`page-action-${index}`}>{action}</div>))}
            </div>
            {tableData ? renderTable : noDataFound}
        </>
    )
}

export default ComponentTablePlain