import { useQuery } from '@tanstack/react-query';
import { useAuth } from '../context/AuthContext';
import { organizations } from '../services/api';
import { cn } from '../lib/utils';
import { Users as UsersIcon, Plus, Shield, Mail, MoreVertical, Crown, UserCog, Eye, Loader2 } from 'lucide-react';

const roleConfig = {
    owner: { label: 'Owner', badge: 'badge-yellow', icon: Crown },
    admin: { label: 'Admin', badge: 'badge-red', icon: Shield },
    member: { label: 'Member', badge: 'badge-blue', icon: UserCog },
    viewer: { label: 'Viewer', badge: 'badge-gray', icon: Eye },
};

const MemberSkeleton = () => (
    <div className="flex items-center gap-4 px-5 py-4 table-row">
        <div className="skeleton w-9 h-9 rounded-lg" />
        <div className="flex-1 space-y-1.5">
            <div className="skeleton h-4 w-32" />
            <div className="skeleton h-3 w-48" />
        </div>
        <div className="skeleton h-5 w-16 rounded-md" />
    </div>
);

export default function Team() {
    const { currentOrg } = useAuth();

    const { data, isLoading } = useQuery({
        queryKey: ['org-members', currentOrg?.id],
        queryFn: () => organizations.members(currentOrg.id),
        enabled: !!currentOrg
    });

    if (!currentOrg) return <div className="flex items-center justify-center h-full p-8"><p className="text-gray-500">Select an organization</p></div>;

    const members = data?.data || [];
    const membersByRole = {};
    members.forEach(m => {
        const role = m.role || 'member';
        if (!membersByRole[role]) membersByRole[role] = [];
        membersByRole[role].push(m);
    });

    return (
        <div className="p-6 animate-fade-in">
            <div className="page-header">
                <div>
                    <h1 className="page-title">Team</h1>
                    <p className="page-subtitle">{members.length} member{members.length !== 1 ? 's' : ''} in {currentOrg.name}</p>
                </div>
                <button className="btn btn-primary">
                    <Plus size={16} /> Invite Member
                </button>
            </div>

            {/* Role summary */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                {Object.entries(roleConfig).map(([key, cfg]) => {
                    const Icon = cfg.icon;
                    const count = membersByRole[key]?.length || 0;
                    return (
                        <div key={key} className="stat-card">
                            <div className="flex items-center justify-between relative z-10">
                                <div>
                                    <p className="text-xs font-medium text-gray-400 uppercase tracking-wide">{cfg.label}s</p>
                                    <p className="text-2xl font-bold text-white mt-1">{count}</p>
                                </div>
                                <Icon size={18} className="text-gray-600" />
                            </div>
                        </div>
                    );
                })}
            </div>

            {/* Members list */}
            <div className="card overflow-hidden">
                <div className="flex items-center gap-4 px-5 py-3 border-b border-gray-800/50 text-xs font-medium text-gray-500 uppercase tracking-wide">
                    <div className="w-9" />
                    <div className="flex-1">Member</div>
                    <div className="w-24">Role</div>
                    <div className="w-32">Joined</div>
                    <div className="w-8" />
                </div>

                {isLoading ? (
                    Array(3).fill(0).map((_, i) => <MemberSkeleton key={i} />)
                ) : members.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-16">
                        <div className="w-14 h-14 rounded-2xl bg-gray-800/50 flex items-center justify-center mb-3">
                            <UsersIcon size={24} className="text-gray-600" />
                        </div>
                        <p className="text-gray-400 font-medium">No team members</p>
                        <p className="text-gray-600 text-sm mt-1">Invite your team to collaborate</p>
                    </div>
                ) : (
                    members.map(member => {
                        const role = roleConfig[member.role] || roleConfig.member;
                        const RoleIcon = role.icon;
                        return (
                            <div key={member.id || member.user_id} className="flex items-center gap-4 px-5 py-3.5 table-row group">
                                <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-xs font-semibold text-white flex-shrink-0">
                                    {member.full_name?.[0]?.toUpperCase() || member.email?.[0]?.toUpperCase() || '?'}
                                </div>
                                <div className="flex-1 min-w-0">
                                    <p className="text-sm font-medium text-gray-200 truncate">{member.full_name || 'Unnamed'}</p>
                                    <p className="text-xs text-gray-500 flex items-center gap-1"><Mail size={10} /> {member.email}</p>
                                </div>
                                <div className="w-24">
                                    <span className={cn("badge text-[10px]", role.badge)}>
                                        <RoleIcon size={10} />
                                        {role.label}
                                    </span>
                                </div>
                                <div className="w-32 text-xs text-gray-500">
                                    {member.joined_at ? new Date(member.joined_at).toLocaleDateString() : '—'}
                                </div>
                                <div className="w-8">
                                    <button className="btn btn-ghost btn-icon opacity-0 group-hover:opacity-100">
                                        <MoreVertical size={14} />
                                    </button>
                                </div>
                            </div>
                        );
                    })
                )}
            </div>
        </div>
    );
}
