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

export function CompaniesPage() {
    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 [editingCompany, setEditingCompany] = useState<Company | null>(null)
    const [formData, setFormData] = useState<CreateCompanyRequest>({
        cnpj: '',
        corporate_name: '',
        category: 'farmacia',
        license_number: '',
        latitude: -16.3281,
        longitude: -48.9530,
        city: 'Anápolis',
        state: 'GO'
    })

    const pageSize = 10

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

    const loadCompanies = async () => {
        setLoading(true)
        try {
            const data = await adminService.listCompanies(page, pageSize)
            setCompanies(data.tenants || [])
            setTotal(data.total)
        } catch (err) {
            console.error('Error loading companies:', err)
        } finally {
            setLoading(false)
        }
    }

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        try {
            if (editingCompany) {
                await adminService.updateCompany(editingCompany.id, formData)
            } else {
                await adminService.createCompany(formData)
            }
            setShowModal(false)
            resetForm()
            loadCompanies()
        } catch (err) {
            console.error('Error saving company:', err)
            alert('Erro ao salvar empresa')
        }
    }

    const handleDelete = async (id: string) => {
        if (!confirm('Tem certeza que deseja excluir esta empresa?')) return
        try {
            await adminService.deleteCompany(id)
            loadCompanies()
        } catch (err) {
            console.error('Error deleting company:', err)
            alert('Erro ao excluir empresa')
        }
    }

    const handleVerify = async (id: string) => {
        try {
            await adminService.verifyCompany(id)
            loadCompanies()
        } catch (err) {
            console.error('Error verifying company:', err)
        }
    }

    const openEdit = (company: Company) => {
        setEditingCompany(company)
        setFormData({
            cnpj: company.cnpj,
            corporate_name: company.corporate_name,
            category: company.category,
            license_number: company.license_number,
            latitude: company.latitude,
            longitude: company.longitude,
            city: company.city,
            state: company.state
        })
        setShowModal(true)
    }

    const resetForm = () => {
        setEditingCompany(null)
        setFormData({
            cnpj: '',
            corporate_name: '',
            category: 'farmacia',
            license_number: '',
            latitude: -16.3281,
            longitude: -48.9530,
            city: 'Anápolis',
            state: 'GO'
        })
    }

    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">Empresas</h1>
                <button
                    onClick={openCreate}
                    className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
                >
                    + Nova Empresa
                </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">Razão Social</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">CNPJ</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Categoria</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Cidade</th>
                            <th className="px-4 py-3 text-center text-sm font-medium">Verificada</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={6} className="py-8 text-center text-gray-500">
                                    Carregando...
                                </td>
                            </tr>
                        ) : companies.length === 0 ? (
                            <tr>
                                <td colSpan={6} className="py-8 text-center text-gray-500">
                                    Nenhuma empresa encontrada
                                </td>
                            </tr>
                        ) : (
                            companies.map((company) => (
                                <tr key={company.id} className="hover:bg-gray-50">
                                    <td className="px-4 py-3 text-sm font-medium text-gray-900">{company.corporate_name}</td>
                                    <td className="px-4 py-3 text-sm text-gray-600">{company.cnpj}</td>
                                    <td className="px-4 py-3">
                                        <span className="rounded-full bg-purple-100 px-2 py-1 text-xs font-medium text-purple-800 capitalize">
                                            {company.category}
                                        </span>
                                    </td>
                                    <td className="px-4 py-3 text-sm text-gray-600">{company.city}/{company.state}</td>
                                    <td className="px-4 py-3 text-center">
                                        <button
                                            onClick={() => handleVerify(company.id)}
                                            className={`rounded-full px-2 py-1 text-xs font-medium ${company.is_verified
                                                ? 'bg-green-100 text-green-800'
                                                : 'bg-yellow-100 text-yellow-800'
                                                }`}
                                        >
                                            {company.is_verified ? '✓ Verificada' : 'Pendente'}
                                        </button>
                                    </td>
                                    <td className="px-4 py-3 text-right">
                                        <button
                                            onClick={() => openEdit(company)}
                                            className="mr-2 text-sm text-blue-600 hover:underline"
                                        >
                                            Editar
                                        </button>
                                        <button
                                            onClick={() => handleDelete(company.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-lg rounded-lg bg-white p-6 shadow-xl max-h-[90vh] overflow-y-auto">
                        <h2 className="mb-4 text-xl font-bold">
                            {editingCompany ? 'Editar Empresa' : 'Nova Empresa'}
                        </h2>
                        <form onSubmit={handleSubmit} className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div className="col-span-2">
                                    <label className="block text-sm font-medium text-gray-700">Razão Social</label>
                                    <input
                                        type="text"
                                        value={formData.corporate_name}
                                        onChange={(e) => setFormData({ ...formData, corporate_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">CNPJ</label>
                                    <input
                                        type="text"
                                        value={formData.cnpj}
                                        onChange={(e) => setFormData({ ...formData, cnpj: 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">Categoria</label>
                                    <select
                                        value={formData.category}
                                        onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                                        className="mt-1 w-full rounded border px-3 py-2"
                                    >
                                        <option value="farmacia">Farmácia</option>
                                        <option value="distribuidora">Distribuidora</option>
                                    </select>
                                </div>
                                <div className="col-span-2">
                                    <label className="block text-sm font-medium text-gray-700">Licença Sanitária</label>
                                    <input
                                        type="text"
                                        value={formData.license_number}
                                        onChange={(e) => setFormData({ ...formData, license_number: 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">Cidade</label>
                                    <input
                                        type="text"
                                        value={formData.city}
                                        onChange={(e) => setFormData({ ...formData, city: 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">Estado</label>
                                    <input
                                        type="text"
                                        value={formData.state}
                                        onChange={(e) => setFormData({ ...formData, state: e.target.value })}
                                        className="mt-1 w-full rounded border px-3 py-2"
                                        maxLength={2}
                                        required
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Latitude</label>
                                    <input
                                        type="number"
                                        step="any"
                                        value={formData.latitude}
                                        onChange={(e) => setFormData({ ...formData, latitude: parseFloat(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">Longitude</label>
                                    <input
                                        type="number"
                                        step="any"
                                        value={formData.longitude}
                                        onChange={(e) => setFormData({ ...formData, longitude: parseFloat(e.target.value) })}
                                        className="mt-1 w-full rounded border px-3 py-2"
                                        required
                                    />
                                </div>
                            </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>
    )
}
