import { useEffect, useState } from 'react'
import { Shell } from '@/layouts/Shell'
import { apiClient } from '@/services/apiClient'
import { useAuth } from '@/context/AuthContext'

interface TeamMember {
    id: string
    name: string
    email: string
    role: string
    created_at: string
}

interface InviteForm {
    name: string
    email: string
    role: string
    password: string
}

const roleLabels: Record<string, string> = {
    'Dono': 'Dono',
    'Gerente': 'Gerente',
    'Comprador': 'Comprador',
    'Colaborador': 'Colaborador',
}

export function TeamPage() {
    const { user } = useAuth()
    const [members, setMembers] = useState<TeamMember[]>([])
    const [loading, setLoading] = useState(true)
    const [inviteOpen, setInviteOpen] = useState(false)
    const [inviting, setInviting] = useState(false)
    const [form, setForm] = useState<InviteForm>({
        name: '',
        email: '',
        role: 'Comprador',
        password: '',
    })

    useEffect(() => {
        loadTeam()
    }, [])

    const loadTeam = async () => {
        try {
            setLoading(true)
            const res = await apiClient.get<{ users: TeamMember[] }>('/v1/team')
            setMembers(res.users || [])
        } catch (err) {
            console.error('Erro ao carregar equipe:', err)
        } finally {
            setLoading(false)
        }
    }

    const handleInvite = async () => {
        if (!form.name || !form.email || !form.password) {
            alert('Preencha todos os campos')
            return
        }
        try {
            setInviting(true)
            await apiClient.post('/v1/team', form)
            alert('Membro convidado com sucesso!')
            setInviteOpen(false)
            setForm({ name: '', email: '', role: 'Comprador', password: '' })
            loadTeam()
        } catch (err) {
            console.error('Erro ao convidar:', err)
            alert('Erro ao convidar membro')
        } finally {
            setInviting(false)
        }
    }

    const canInvite = ['Dono', 'Gerente', 'Admin', 'owner', 'admin', 'seller'].includes(user?.role || '')

    return (
        <Shell>
            <div className="max-w-4xl mx-auto p-6">
                <div className="flex items-center justify-between mb-6">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900">Minha Equipe</h1>
                        <p className="text-sm text-gray-500 mt-1">Gerencie os membros da sua farmácia</p>
                    </div>
                    {canInvite && (
                        <button
                            onClick={() => setInviteOpen(true)}
                            className="px-4 py-2 rounded-lg font-medium text-white hover:opacity-90 transition"
                            style={{ backgroundColor: '#0F4C81' }}
                        >
                            + Convidar Membro
                        </button>
                    )}
                </div>

                {loading ? (
                    <div className="flex items-center justify-center py-12">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                    </div>
                ) : members.length === 0 ? (
                    <div className="text-center py-12 bg-gray-50 rounded-xl">
                        <p className="text-gray-500">Nenhum membro encontrado</p>
                    </div>
                ) : (
                    <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                        <table className="w-full">
                            <thead className="text-white border-b border-gray-200" style={{ backgroundColor: '#0F4C81' }}>
                                <tr>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Nome</th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Email</th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Função</th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">Desde</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-200">
                                {members.map((member) => (
                                    <tr key={member.id} className="hover:bg-gray-50">
                                        <td className="px-6 py-4 whitespace-nowrap font-medium text-gray-900">{member.name}</td>
                                        <td className="px-6 py-4 whitespace-nowrap text-gray-500">{member.email}</td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <span className="px-2 py-1 bg-blue-100 text-blue-800 rounded-full text-xs font-medium">
                                                {roleLabels[member.role] || member.role}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-gray-500 text-sm">
                                            {new Date(member.created_at).toLocaleDateString('pt-BR')}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}

                {/* Modal de Convite */}
                {inviteOpen && (
                    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
                        <div className="bg-white rounded-xl p-6 w-full max-w-md shadow-2xl">
                            <h2 className="text-xl font-bold mb-4">Convidar Membro</h2>
                            <div className="space-y-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Nome</label>
                                    <input
                                        type="text"
                                        value={form.name}
                                        onChange={(e) => setForm({ ...form, name: e.target.value })}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                        placeholder="Nome completo"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                                    <input
                                        type="email"
                                        value={form.email}
                                        onChange={(e) => setForm({ ...form, email: e.target.value })}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                        placeholder="email@empresa.com"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Função</label>
                                    <select
                                        value={form.role}
                                        onChange={(e) => setForm({ ...form, role: e.target.value })}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    >
                                        <option value="Gerente">Gerente</option>
                                        <option value="Comprador">Comprador</option>
                                        <option value="Colaborador">Colaborador</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Senha Temporária</label>
                                    <input
                                        type="password"
                                        value={form.password}
                                        onChange={(e) => setForm({ ...form, password: e.target.value })}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                        placeholder="••••••••"
                                    />
                                </div>
                            </div>
                            <div className="flex justify-end gap-3 mt-6">
                                <button
                                    onClick={() => setInviteOpen(false)}
                                    className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
                                >
                                    Cancelar
                                </button>
                                <button
                                    onClick={handleInvite}
                                    disabled={inviting}
                                    className="px-4 py-2 rounded-lg text-white transition disabled:opacity-50 hover:opacity-90"
                                    style={{ backgroundColor: '#0F4C81' }}
                                >
                                    {inviting ? 'Convidando...' : 'Convidar'}
                                </button>
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </Shell>
    )
}
