import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuth } from '../context/AuthContext';
import { organizations } from '../services/api';

const roleColors = {
    owner: 'bg-yellow-500/20 text-yellow-400',
    admin: 'bg-red-500/20 text-red-400',
    manager: 'bg-purple-500/20 text-purple-400',
    analyst: 'bg-blue-500/20 text-blue-400',
    viewer: 'bg-gray-500/20 text-gray-400'
};

export default function Team() {
    const { currentOrg } = useAuth();
    const queryClient = useQueryClient();
    const [showInvite, setShowInvite] = useState(false);
    const [inviteForm, setInviteForm] = useState({ email: '', role: 'viewer' });
    
    const { data, isLoading } = useQuery({
        queryKey: ['org-members', currentOrg?.id],
        queryFn: () => organizations.members(currentOrg.id),
        enabled: !!currentOrg
    });
    
    const inviteMutation = useMutation({
        mutationFn: () => organizations.invite(currentOrg.id, inviteForm),
        onSuccess: () => {
            queryClient.invalidateQueries(['org-members', currentOrg?.id]);
            setShowInvite(false);
            setInviteForm({ email: '', role: 'viewer' });
        }
    });
    
    if (!currentOrg) return <div className="p-8 text-center text-gray-400">Select an organization</div>;
    
    const members = data?.data || [];
    
    return (
        <div className="p-8">
            <div className="flex items-center justify-between mb-6">
                <h1 className="text-2xl font-bold">Team</h1>
                <button onClick={() => setShowInvite(true)} className="btn btn-primary">
                    + Invite Member
                </button>
            </div>
            
            <div className="card">
                {isLoading ? (
                    <div className="text-center py-8 text-gray-400">Loading...</div>
                ) : (
                    <div className="divide-y divide-gray-700">
                        {members.map(member => (
                            <div key={member.id} className="flex items-center justify-between p-4">
                                <div className="flex items-center gap-4">
                                    <div className="w-10 h-10 bg-primary-600 rounded-full flex items-center justify-center font-semibold">
                                        {member.user?.full_name?.[0] || member.user?.email?.[0] || '?'}
                                    </div>
                                    <div>
                                        <p className="font-medium">{member.user?.full_name || 'Unknown'}</p>
                                        <p className="text-sm text-gray-400">{member.user?.email}</p>
                                    </div>
                                </div>
                                <span className={`px-3 py-1 rounded text-sm ${roleColors[member.role]}`}>
                                    {member.role}
                                </span>
                            </div>
                        ))}
                    </div>
                )}
            </div>
            
            {/* Invite modal */}
            {showInvite && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
                    <div className="bg-gray-800 rounded-xl w-full max-w-md p-6">
                        <h2 className="text-lg font-semibold mb-4">Invite Team Member</h2>
                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium mb-2">Email</label>
                                <input
                                    type="email"
                                    value={inviteForm.email}
                                    onChange={(e) => setInviteForm({...inviteForm, email: e.target.value})}
                                    className="input"
                                    placeholder="colleague@company.com"
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium mb-2">Role</label>
                                <select
                                    value={inviteForm.role}
                                    onChange={(e) => setInviteForm({...inviteForm, role: e.target.value})}
                                    className="input"
                                >
                                    <option value="viewer">Viewer - Read only</option>
                                    <option value="analyst">Analyst - Can analyze</option>
                                    <option value="manager">Manager - Can manage issues</option>
                                    <option value="admin">Admin - Full access</option>
                                </select>
                            </div>
                        </div>
                        <div className="flex gap-2 mt-6">
                            <button onClick={() => setShowInvite(false)} className="btn btn-secondary flex-1">Cancel</button>
                            <button 
                                onClick={() => inviteMutation.mutate()}
                                disabled={!inviteForm.email || inviteMutation.isPending}
                                className="btn btn-primary flex-1"
                            >
                                {inviteMutation.isPending ? 'Sending...' : 'Send Invite'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
