// Client-Side React Component
// Uses TanStack Query to fetch from /api/shim/sites/list

import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Loader2, Trash2, Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import type { Site, PaginationResult } from '@/lib/shim/types';

export default function SitesList() {
    const queryClient = useQueryClient();
    const [page, setPage] = useState(0);
    const limit = 10;

    // Fetch sites
    const { data, isLoading, error } = useQuery<PaginationResult<Site>>({
        queryKey: ['shim-sites', page],
        queryFn: async () => {
            const response = await fetch(
                `/api/shim/sites/list?limit=${limit}&offset=${page * limit}`,
                {
                    headers: {
                        'Authorization': `Bearer ${import.meta.env.PUBLIC_GOD_MODE_TOKEN || 'local-dev-token'}`
                    }
                }
            );

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

            return response.json();
        },
        staleTime: 30000, // Cache for 30 seconds
    });

    // Delete mutation
    const deleteMutation = useMutation({
        mutationFn: async (id: string) => {
            const response = await fetch(`/api/shim/sites/${id}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${import.meta.env.PUBLIC_GOD_MODE_TOKEN || 'local-dev-token'}`
                }
            });

            if (!response.ok) {
                throw new Error('Failed to delete site');
            }
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['shim-sites'] });
        }
    });

    if (isLoading) {
        return (
            <div className="flex items-center justify-center p-12">
                <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
                <span className="ml-3 text-slate-400">Loading sites from API...</span>
            </div>
        );
    }

    if (error) {
        return (
            <div className="p-6 bg-red-900/20 border border-red-700 rounded-lg">
                <p className="text-red-400">Error loading sites: {error.message}</p>
            </div>
        );
    }

    const sites = data?.data || [];

    return (
        <div className="space-y-4">
            {/* Sites List */}
            <div className="space-y-2">
                {sites.length === 0 ? (
                    <div className="p-8 bg-slate-800 rounded-lg text-center text-slate-400">
                        No sites found on this page.
                    </div>
                ) : (
                    sites.map((site) => (
                        <div
                            key={site.id}
                            className="p-4 bg-slate-800/50 rounded-lg border border-slate-700 hover:border-slate-600 transition flex justify-between items-center"
                        >
                            <div>
                                <h3 className="text-white font-semibold">{site.domain}</h3>
                                <p className="text-slate-400 text-sm">{site.site_url || 'No URL'}</p>
                            </div>
                            <div className="flex items-center gap-2">
                                <span
                                    className={`px-2 py-1 rounded text-xs font-medium ${site.status === 'active'
                                            ? 'bg-green-500/20 text-green-400'
                                            : 'bg-gray-500/20 text-gray-400'
                                        }`}
                                >
                                    {site.status}
                                </span>
                                <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => deleteMutation.mutate(site.id)}
                                    disabled={deleteMutation.isPending}
                                    className="text-red-400 hover:text-red-300 hover:bg-red-900/20"
                                >
                                    {deleteMutation.isPending ? (
                                        <Loader2 className="w-4 h-4 animate-spin" />
                                    ) : (
                                        <Trash2 className="w-4 h-4" />
                                    )}
                                </Button>
                            </div>
                        </div>
                    ))
                )}
            </div>

            {/* Pagination */}
            {data && data.total > limit && (
                <div className="flex justify-between items-center pt-4 border-t border-slate-700">
                    <p className="text-slate-400 text-sm">
                        Showing {page * limit + 1}-{Math.min((page + 1) * limit, data.total)} of {data.total}
                    </p>
                    <div className="flex gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() => setPage(p => Math.max(0, p - 1))}
                            disabled={page === 0}
                        >
                            Previous
                        </Button>
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() => setPage(p => p + 1)}
                            disabled={!data.hasMore}
                        >
                            Next
                        </Button>
                    </div>
                </div>
            )}
        </div>
    );
}
