import { ReactNode } from 'react';
import { Link, router } from '@inertiajs/react';

interface TableProps {
    children: ReactNode;
    className?: string;
    pagination?: {
        data: unknown[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
        links: Array<{ url: string | null; label: string; active: boolean }>;
    };
}

export default function Table({ children, className = '', pagination }: TableProps) {
    // Check if pagination should be shown
    const shouldShowPagination = pagination && 
        typeof pagination.total === 'number' &&
        pagination.total > 0 && 
        typeof pagination.last_page === 'number' &&
        pagination.last_page > 1 && 
        Array.isArray(pagination.links) && 
        pagination.links.length > 0;

    return (
        <div className="space-y-4">
            <div className="overflow-hidden rounded-lg border border-gray-200 dark:border-gray-700">
                <div className="overflow-x-auto">
                    <table className={`min-w-full divide-y divide-gray-200 dark:divide-gray-700 ${className}`}>
                        {children}
                    </table>
                </div>
            </div>
            {shouldShowPagination && <TablePagination pagination={pagination} />}
        </div>
    );
}

interface TableHeaderProps {
    children: ReactNode;
}

export function TableHeader({ children }: TableHeaderProps) {
    return (
        <thead className="bg-gray-50 dark:bg-gray-800">
            <tr>{children}</tr>
        </thead>
    );
}

interface TableHeaderCellProps {
    children: ReactNode;
    className?: string;
}

export function TableHeaderCell({ children, className = '' }: TableHeaderCellProps) {
    return (
        <th
            scope="col"
            className={`px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400 ${className}`}
        >
            {children}
        </th>
    );
}

interface TableBodyProps {
    children: ReactNode;
}

export function TableBody({ children }: TableBodyProps) {
    return <tbody className="divide-y divide-gray-200 bg-white dark:divide-gray-700 dark:bg-gray-800">{children}</tbody>;
}

interface TableRowProps {
    children: ReactNode;
    className?: string;
    onClick?: () => void;
}

export function TableRow({ children, className = '', onClick }: TableRowProps) {
    return (
        <tr
            className={`transition-colors hover:bg-gray-50 dark:hover:bg-gray-700/50 ${onClick ? 'cursor-pointer' : ''} ${className}`}
            onClick={onClick}
        >
            {children}
        </tr>
    );
}

interface TableCellProps {
    children: ReactNode;
    className?: string;
    colSpan?: number;
}

export function TableCell({ children, className = '', colSpan }: TableCellProps) {
    return (
        <td
            colSpan={colSpan}
            className={`whitespace-nowrap px-6 py-4 text-sm text-gray-900 dark:text-gray-300 ${className}`}
        >
            {children}
        </td>
    );
}

interface TablePaginationProps {
    pagination: {
        data: unknown[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
        links: Array<{ url: string | null; label: string; active: boolean }>;
    };
}

export function TablePagination({ pagination }: TablePaginationProps) {
    // Helper function to extract path from full URL
    const getPathFromUrl = (url: string | null): string | null => {
        if (!url) {
            return null;
        }
        
        // If already a relative URL, return as is
        if (url.startsWith('/')) {
            return url;
        }
        
        try {
            const urlObj = new URL(url);
            return urlObj.pathname + urlObj.search;
        } catch {
            // If URL parsing fails, try to extract path manually
            const match = url.match(/https?:\/\/[^/]+(.+)/);
            if (match) {
                return match[1];
            }
            // If no match, assume it's already a relative path
            return url;
        }
    };

    return (
        <div className="flex items-center justify-between rounded-lg border border-gray-200 bg-white px-4 py-3 dark:border-gray-700 dark:bg-gray-800 sm:px-6">
            <div className="text-sm text-gray-700 dark:text-gray-300">
                Menampilkan <span className="font-medium">{pagination.data.length}</span> dari{' '}
                <span className="font-medium">{pagination.total}</span> hasil
            </div>
            <div className="flex flex-wrap items-center gap-2">
                {pagination.links.map((link, index) => {
                    if (link.url === null) {
                        return (
                            <span
                                key={index}
                                className={`px-3 py-2 text-sm rounded-md ${
                                    link.active
                                        ? 'bg-[#d4af37] text-white dark:bg-[#b8941f]'
                                        : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 cursor-not-allowed'
                                }`}
                                dangerouslySetInnerHTML={{ __html: link.label }}
                            />
                        );
                    }

                    const path = getPathFromUrl(link.url);

                    return (
                        <Link
                            key={index}
                            href={path || link.url}
                            className={`px-3 py-2 text-sm rounded-md transition-colors ${
                                link.active
                                    ? 'bg-[#d4af37] text-white dark:bg-[#b8941f]'
                                    : 'bg-white text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700'
                            }`}
                            dangerouslySetInnerHTML={{ __html: link.label }}
                        />
                    );
                })}
            </div>
        </div>
    );
}

