import { useState, useEffect } from 'react';

interface CollectionTableProps {
    endpoint: string;
    columns: string[];
    title?: string;
}

export default function CollectionTable({ endpoint, columns, title }: CollectionTableProps) {
    const [data, setData] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [page, setPage] = useState(0);
    const [total, setTotal] = useState(0);
    const limit = 50;

    const fetchData = async () => {
        setLoading(true);
        try {
            const token = localStorage.getItem('godToken') || '';
            const response = await fetch(`${endpoint}?limit=${limit}&offset=${page * limit}`, {
                headers: {
                    'X-God-Token': token
                }
            });

            if (!response.ok) {
                throw new Error('Failed to fetch data');
            }

            const result = await response.json();
            setData(result.data || []);
            setTotal(result.meta?.total || 0);
        } catch (err: any) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, [endpoint, page]);

    if (loading) {
        return (
            <div className="flex items-center justify-center p-12">
                <div className="text-xl text-gray-400">Loading...</div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="bg-red-900/20 border border-red-500 rounded-lg p-6">
                <div className="text-red-400 font-semibold mb-2">Error</div>
                <div className="text-gray-300">{error}</div>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <h1 className="text-3xl font-bold text-gold-500">{title || 'Collection'}</h1>
                <div className="text-sm text-gray-400">
                    {total} total items
                </div>
            </div>

            {/* Table */}
            <div className="bg-titanium border border-edge-normal rounded-xl overflow-hidden">
                <table className="w-full">
                    <thead className="bg-graphite border-b border-edge-subtle">
                        <tr>
                            {columns.map(col => (
                                <th key={col} className="px-6 py-4 text-left text-sm font-semibold text-gray-300 uppercase tracking-wider">
                                    {col.replace(/_/g, ' ')}
                                </th>
                            ))}
                            <th className="px-6 py-4 text-right text-sm font-semibold text-gray-300 uppercase">
                                Actions
                            </th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-edge-subtle">
                        {data.length === 0 ? (
                            <tr>
                                <td colSpan={columns.length + 1} className="px-6 py-12 text-center text-gray-500">
                                    No items found
                                </td>
                            </tr>
                        ) : (
                            data.map((item, idx) => (
                                <tr key={item.id || idx} className="hover:bg-graphite/50 transition-colors">
                                    {columns.map(col => (
                                        <td key={col} className="px-6 py-4 text-sm text-gray-300">
                                            {typeof item[col] === 'object'
                                                ? JSON.stringify(item[col]).substring(0, 50) + '...'
                                                : item[col] || '-'
                                            }
                                        </td>
                                    ))}
                                    <td className="px-6 py-4 text-right">
                                        <button className="text-gold-500 hover:text-gold-400 text-sm font-medium">
                                            View
                                        </button>
                                    </td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            {/* Pagination */}
            {total > limit && (
                <div className="flex items-center justify-between">
                    <button
                        onClick={() => setPage(p => Math.max(0, p - 1))}
                        disabled={page === 0}
                        className="px-4 py-2 bg-graphite border border-edge-normal rounded-lg text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:bg-jet transition-colors"
                    >
                        Previous
                    </button>
                    <div className="text-sm text-gray-400">
                        Page {page + 1} of {Math.ceil(total / limit)}
                    </div>
                    <button
                        onClick={() => setPage(p => p + 1)}
                        disabled={(page + 1) * limit >= total}
                        className="px-4 py-2 bg-graphite border border-edge-normal rounded-lg text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:bg-jet transition-colors"
                    >
                        Next
                    </button>
                </div>
            )}
        </div>
    );
}
