import React from "react";
import EmptyContent from "./EmptyContent";
import { twMerge } from "tailwind-merge";

type Props = {
    data?: { [k: string]: any }[];
};

export default function Table({ data }: Props) {
    if (!data || data.length === 0) {
        return (
            <EmptyContent
                title="No results"
                borderProps={{ className: "!p-2" }}
            />
        );
    }

    const headers = Object.keys(data[0]);

    return (
        <div className={twMerge("overflow-x-auto w-full")}>
            <table
                className={twMerge(
                    "min-w-full divide-y divide-gray dark:divide-gray-dark"
                )}
            >
                <thead className="bg-gray dark:bg-gray-dark">
                    <tr>
                        {headers.map((header) => (
                            <th
                                key={header}
                                className={twMerge(
                                    "px-3 py-2 text-left text-sm opacity-50",
                                    "font-semibold"
                                )}
                                title={header}
                            >
                                {header}
                            </th>
                        ))}
                    </tr>
                </thead>
                <tbody
                    className={twMerge(
                        "bg-background-light dark:bg-background-dark",
                        "divide-y divide-gray dark:divide-gray-dark"
                    )}
                >
                    {data.map((row, index) => (
                        <tr
                            key={index}
                            className={twMerge(
                                "hover:bg-gray/20 dark:hover:bg-gray-dark/10"
                            )}
                        >
                            {headers.map((header) => (
                                <td
                                    key={`${header}-${index}`}
                                    className={twMerge(
                                        "px-3 py-2 whitespace-nowrap text-sm text-foreground-light",
                                        "dark:text-foreground-dark max-w-[200px] overflow-hidden",
                                        "overflow-ellipsis"
                                    )}
                                    title={row[header]}
                                >
                                    {row[header]}
                                </td>
                            ))}
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}
