import { useEffect, useState } from 'react'
import { adminService, User, CreateUserRequest, Company } from '../../services/adminService'

export function UsersPage() {
    const [users, setUsers] = useState<User[]>([])
    const [companies, setCompanies] = useState<Company[]>([])
    const [loading, setLoading] = useState(true)
    const [page, setPage] = useState(1)
    const [total, setTotal] = useState(0)
    const [showModal, setShowModal] = useState(false)
    const [editingUser, setEditingUser] = useState<User | null>(null)
    const [formData, setFormData] = useState<CreateUserRequest>({
        company_id: '',
        role: 'Colaborador',
        name: '',
        username: '',
        email: '',
        password: ''
    })

    const pageSize = 10

    useEffect(() => {
        loadUsers()
        loadCompanies()
    }, [page])

    const loadUsers = async () => {
        setLoading(true)
        try {
            const data = await adminService.listUsers(page, pageSize)
            setUsers(data.users || [])
            setTotal(data.total)
        } catch (err) {
            console.error('Error loading users:', err)
        } finally {
            setLoading(false)
        }
    }

    const loadCompanies = async () => {
        try {
            const data = await adminService.listCompanies(1, 1000)
            setCompanies(data.tenants || [])
        } catch (err) {
            console.error('Error loading companies:', err)
        }
    }

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        try {
            if (editingUser) {
                await adminService.updateUser(editingUser.id, formData)
            } else {
                await adminService.createUser(formData)
            }
            setShowModal(false)
            resetForm()
            loadUsers()
            loadUsers()
        } catch (err: any) {
            console.error('Error saving user:', err)
            alert(`Erro ao salvar usuário: ${err.response?.data?.error || err.message}`)
        }
    }

    const handleDelete = async (id: string) => {
        if (!confirm('Tem certeza que deseja excluir este usuário?')) return
        try {
            await adminService.deleteUser(id)
            loadUsers()
        } catch (err) {
            console.error('Error deleting user:', err)
            alert('Erro ao excluir usuário')
        }
    }

    const openEdit = (user: User) => {
        setEditingUser(user)
        setFormData({
            company_id: user.company_id,
            role: user.role,
            name: user.name,
            username: user.username,
            email: user.email,
            password: ''
        })
        setShowModal(true)
    }

    const resetForm = () => {
        setEditingUser(null)
        setFormData({
            company_id: companies[0]?.id || '',
            role: 'Colaborador',
            name: '',
            username: '',
            email: '',
            password: ''
        })
    }

    const openCreate = () => {
        resetForm()
        setShowModal(true)
    }

    const totalPages = Math.ceil(total / pageSize)

    return (
        <div>
            <div className="mb-6 flex items-center justify-between">
                <h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
                <button
                    onClick={openCreate}
                    className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
                >
                    + Novo Usuário
                </button>
            </div>

            {/* Table */}
            <div className="overflow-hidden rounded-lg bg-white shadow">
                <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-blue-900 text-white">
                        <tr>
                            <th className="px-4 py-3 text-left text-sm font-medium">Nome</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Username</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Email</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Função</th>
                            <th className="px-4 py-3 text-right text-sm font-medium">Ações</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                        {loading ? (
                            <tr>
                                <td colSpan={5} className="py-8 text-center text-gray-500">
                                    Carregando...
                                </td>
                            </tr>
                        ) : users.length === 0 ? (
                            <tr>
                                <td colSpan={5} className="py-8 text-center text-gray-500">
                                    Nenhum usuário encontrado
                                </td>
                            </tr>
                        ) : (
                            users.map((user) => (
                                <tr key={user.id} className="hover:bg-gray-50">
                                    <td className="px-4 py-3 text-sm font-medium text-gray-900">{user.name}</td>
                                    <td className="px-4 py-3 text-sm text-gray-600">{user.username}</td>
                                    <td className="px-4 py-3 text-sm text-gray-600">{user.email}</td>
                                    <td className="px-4 py-3">
                                        <span className="rounded-full bg-blue-100 px-2 py-1 text-xs font-medium text-blue-800">
                                            {user.role}
                                        </span>
                                    </td>
                                    <td className="px-4 py-3 text-right">
                                        <button
                                            onClick={() => openEdit(user)}
                                            className="mr-2 text-sm text-blue-600 hover:underline"
                                        >
                                            Editar
                                        </button>
                                        <button
                                            onClick={() => handleDelete(user.id)}
                                            className="text-sm text-red-600 hover:underline"
                                        >
                                            Excluir
                                        </button>
                                    </td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
                <div className="mt-4 flex items-center justify-between">
                    <p className="text-sm text-gray-600">
                        Mostrando {(page - 1) * pageSize + 1} a {Math.min(page * pageSize, total)} de {total}
                    </p>
                    <div className="flex gap-2">
                        <button
                            onClick={() => setPage(page - 1)}
                            disabled={page === 1}
                            className="rounded border px-3 py-1 text-sm disabled:opacity-50"
                        >
                            Anterior
                        </button>
                        <button
                            onClick={() => setPage(page + 1)}
                            disabled={page >= totalPages}
                            className="rounded border px-3 py-1 text-sm disabled:opacity-50"
                        >
                            Próxima
                        </button>
                    </div>
                </div>
            )}

            {/* Modal */}
            {showModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
                    <div className="w-full max-w-md rounded-lg bg-white p-6 shadow-xl">
                        <h2 className="mb-4 text-xl font-bold">
                            {editingUser ? 'Editar Usuário' : 'Novo Usuário'}
                        </h2>
                        <form onSubmit={handleSubmit} className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700">Empresa</label>
                                <select
                                    value={formData.company_id}
                                    onChange={(e) => setFormData({ ...formData, company_id: e.target.value })}
                                    className="mt-1 w-full rounded border px-3 py-2"
                                    required
                                >
                                    <option value="">Selecione...</option>
                                    {companies.map((c) => (
                                        <option key={c.id} value={c.id}>
                                            {c.corporate_name}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700">Função</label>
                                <select
                                    value={formData.role}
                                    onChange={(e) => setFormData({ ...formData, role: e.target.value })}
                                    className="mt-1 w-full rounded border px-3 py-2"
                                >
                                    <option value="Admin">Admin</option>
                                    <option value="Dono">Dono</option>
                                    <option value="Colaborador">Colaborador</option>
                                    <option value="Entregador">Entregador</option>
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700">Nome</label>
                                <input
                                    type="text"
                                    value={formData.name}
                                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                    className="mt-1 w-full rounded border px-3 py-2"
                                    required
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700">Username</label>
                                <input
                                    type="text"
                                    value={formData.username}
                                    onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                                    className="mt-1 w-full rounded border px-3 py-2"
                                    required
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700">Email</label>
                                <input
                                    type="email"
                                    value={formData.email}
                                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                    className="mt-1 w-full rounded border px-3 py-2"
                                    required
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700">
                                    Senha {editingUser && '(deixe vazio para manter)'}
                                </label>
                                <input
                                    type="password"
                                    value={formData.password}
                                    onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                    className="mt-1 w-full rounded border px-3 py-2"
                                    required={!editingUser}
                                />
                            </div>
                            <div className="flex justify-end gap-2 pt-4">
                                <button
                                    type="button"
                                    onClick={() => setShowModal(false)}
                                    className="rounded border px-4 py-2 text-sm"
                                >
                                    Cancelar
                                </button>
                                <button
                                    type="submit"
                                    className="rounded bg-blue-600 px-4 py-2 text-sm text-white hover:bg-blue-700"
                                >
                                    Salvar
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    )
}
