import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Mail } from 'lucide-react';
import { projectInvitations } from '@/client';
import { useProject } from '@/contexts';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Spinner } from '@/components/ui/spinner';

export function SettingsMembers() {
    const { project } = useProject();
    const [page] = useState(1);
    const perPage = 10;

    const { data: invitationsData, isLoading } = useQuery({
        queryKey: ['projectInvitations', project?.name, page, perPage],
        queryFn: async () => {
            const resp = await projectInvitations({
                path: { project_name: project!.name },
                query: { page, per_page: perPage },
            });
            return resp.data?.data ?? null;
        },
        enabled: !!project?.name,
    });

    if (!project) return null;

    const invitations = Array.isArray(invitationsData)
        ? invitationsData
        : (invitationsData as { items?: unknown[] })?.items || [];

    const statusBadge = (status: string) => {
        const colors: Record<string, string> = {
            pending: 'bg-yellow-100 text-yellow-800 border-yellow-300',
            accepted: 'bg-green-100 text-green-800 border-green-300',
            rejected: 'bg-red-100 text-red-800 border-red-300',
        };
        return (
            <span className={`inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium border ${colors[status] || ''}`}>
                {status}
            </span>
        );
    };

    return (
        <div className="space-y-6">
            <div>
                <h2 className="text-lg font-semibold">Members</h2>
                <p className="text-sm text-muted-foreground">
                    Manage invitations and member access.
                </p>
            </div>

            <div className="border rounded-md">
                <div className="bg-muted/50 border-b px-4 py-3">
                    <h3 className="text-sm font-medium">Invitations</h3>
                </div>

                {isLoading ? (
                    <div className="flex items-center justify-center h-32">
                        <Spinner />
                    </div>
                ) : invitations.length === 0 ? (
                    <div className="text-center py-8 text-sm text-muted-foreground">
                        <Mail className="h-10 w-10 mx-auto mb-2 text-muted-foreground/50" />
                        <p>No invitations.</p>
                    </div>
                ) : (
                    <>
                        <table className="w-full">
                            <thead>
                                <tr className="border-b">
                                    <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                                        User
                                    </th>
                                    <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                                        Role
                                    </th>
                                    <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                                        Status
                                    </th>
                                    <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                                        Sent
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-border">
                                {invitations.map(
                                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                    (inv: any) => (
                                        <tr key={inv.uid || inv.id} className="hover:bg-muted/30">
                                            <td className="px-4 py-3">
                                                <div className="flex items-center gap-3">
                                                    <Avatar className="h-8 w-8">
                                                        <AvatarImage src={inv.avatar_url || ''} />
                                                        <AvatarFallback>
                                                            {(inv.email || '?').charAt(0).toUpperCase()}
                                                        </AvatarFallback>
                                                    </Avatar>
                                                    <div>
                                                        <div className="font-medium">
                                                            {inv.email}
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td className="px-4 py-3">
                                                <Badge variant="outline">{inv.scope || 'Member'}</Badge>
                                            </td>
                                            <td className="px-4 py-3">
                                                {statusBadge(inv.status || 'pending')}
                                            </td>
                                            <td className="px-4 py-3 text-sm text-muted-foreground">
                                                {inv.created_at
                                                    ? new Date(inv.created_at).toLocaleDateString()
                                                    : '-'}
                                            </td>
                                        </tr>
                                    ),
                                )}
                            </tbody>
                        </table>
                    </>
                )}
            </div>
        </div>
    );
}
