import { useEffect, useState } from 'react'
import { adminService, Product, CreateProductRequest, Company } from '@/services/adminService'

export function ProductsPage() {
    const [products, setProducts] = useState<Product[]>([])
    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 [editingProduct, setEditingProduct] = useState<Product | null>(null)
    const [formData, setFormData] = useState<CreateProductRequest>({
        seller_id: '',
        name: '',
        description: '',
        batch: '',
        expires_at: '',
        price_cents: 0,
        stock: 0
    })

    const pageSize = 10

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

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

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

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        try {
            // Convert date to ISO 8601 format for backend
            const expiresAtISO = formData.expires_at
                ? new Date(formData.expires_at + 'T00:00:00Z').toISOString()
                : undefined

            if (editingProduct) {
                const updated = await adminService.updateProduct(editingProduct.id, {
                    name: formData.name,
                    description: formData.description,
                    batch: formData.batch,
                    expires_at: expiresAtISO,
                    price_cents: formData.price_cents,
                    stock: formData.stock
                })
                // Update local state instead of reloading
                setProducts(prev => prev.map(p =>
                    p.id === editingProduct.id ? { ...p, ...updated } : p
                ))
            } else {
                const newProduct = await adminService.createProduct({
                    ...formData,
                    expires_at: expiresAtISO || ''
                })
                // Add to local state
                setProducts(prev => [newProduct, ...prev])
                setTotal(prev => prev + 1)
            }
            setShowModal(false)
            resetForm()
        } catch (err) {
            console.error('Error saving product:', err)
            alert('Erro ao salvar produto')
        }
    }

    const handleDelete = async (id: string) => {
        if (!confirm('Tem certeza que deseja excluir este produto?')) return
        try {
            await adminService.deleteProduct(id)
            // Update local state instead of reloading
            setProducts(prev => prev.filter(p => p.id !== id))
            setTotal(prev => prev - 1)
        } catch (err: unknown) {
            console.error('Error deleting product:', err)
            // Check if it's a constraint error (product has orders)
            const message = (err as { response?: { data?: { error?: string } } })?.response?.data?.error
            if (message?.includes('related orders')) {
                alert('Não é possível excluir: este produto possui pedidos relacionados.')
            } else {
                alert('Erro ao excluir produto')
            }
        }
    }

    const openEdit = (product: Product) => {
        setEditingProduct(product)
        setFormData({
            seller_id: product.seller_id,
            name: product.name,
            description: product.description,
            batch: product.batch,
            expires_at: product.expires_at.split('T')[0],
            price_cents: product.price_cents,
            stock: product.stock
        })
        setShowModal(true)
    }

    const resetForm = () => {
        setEditingProduct(null)
        setFormData({
            seller_id: companies[0]?.id || '',
            name: '',
            description: '',
            batch: '',
            expires_at: '',
            price_cents: 0,
            stock: 0
        })
    }

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

    const formatPrice = (cents: number) => {
        return (cents / 100).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })
    }

    const formatDate = (dateStr: string) => {
        return new Date(dateStr).toLocaleDateString('pt-BR')
    }

    const isExpiringSoon = (dateStr: string) => {
        const expiresAt = new Date(dateStr)
        const now = new Date()
        const diffDays = Math.floor((expiresAt.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
        return diffDays <= 30
    }

    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">Produtos</h1>
                <button
                    onClick={openCreate}
                    className="rounded-lg px-4 py-2 text-sm font-medium text-white hover:opacity-90"
                    style={{ backgroundColor: '#0F4C81' }}
                >
                    + Novo Produto
                </button>
            </div>

            {/* Table */}
            <div className="overflow-hidden rounded-lg bg-white shadow">
                <table className="min-w-full divide-y divide-gray-200">
                    <thead className="text-white" style={{ backgroundColor: '#0F4C81' }}>
                        <tr>
                            <th className="px-4 py-3 text-left text-sm font-medium">Produto</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Loja</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Lote</th>
                            <th className="px-4 py-3 text-left text-sm font-medium">Validade</th>
                            <th className="px-4 py-3 text-right text-sm font-medium">Preço</th>
                            <th className="px-4 py-3 text-right text-sm font-medium">Estoque</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={7} className="py-8 text-center text-gray-500">
                                    Carregando...
                                </td>
                            </tr>
                        ) : products.length === 0 ? (
                            <tr>
                                <td colSpan={7} className="py-8 text-center text-gray-500">
                                    Nenhum produto encontrado
                                </td>
                            </tr>
                        ) : (
                            products.map((product) => {
                                const company = companies.find(c => c.id === product.seller_id)
                                return (
                                    <tr key={product.id} className="hover:bg-gray-50">
                                        <td className="px-4 py-3">
                                            <div className="text-sm font-medium text-gray-900">{product.name}</div>
                                            <div className="text-xs text-gray-500">{product.description}</div>
                                        </td>
                                        <td className="px-4 py-3">
                                            <span className="rounded bg-purple-100 px-2 py-1 text-xs font-medium text-purple-800">
                                                {company?.corporate_name || 'N/A'}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3 text-sm text-gray-600">{product.batch}</td>
                                        <td className="px-4 py-3">
                                            <span className={`rounded-full px-2 py-1 text-xs font-medium ${isExpiringSoon(product.expires_at)
                                                ? 'bg-red-100 text-red-800'
                                                : 'bg-green-100 text-green-800'
                                                }`}>
                                                {formatDate(product.expires_at)}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3 text-right text-sm font-medium text-gray-900">
                                            {formatPrice(product.price_cents)}
                                        </td>
                                        <td className="px-4 py-3 text-right">
                                            <span className={`rounded-full px-2 py-1 text-xs font-medium ${product.stock < 10
                                                ? 'bg-yellow-100 text-yellow-800'
                                                : 'bg-blue-100 text-blue-800'
                                                }`}>
                                                {product.stock}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3 text-right">
                                            <button
                                                onClick={() => openEdit(product)}
                                                className="mr-2 text-sm text-blue-600 hover:underline"
                                            >
                                                Editar
                                            </button>
                                            <button
                                                onClick={() => handleDelete(product.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" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
                    <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">
                            {editingProduct ? 'Editar Produto' : 'Novo Produto'}
                        </h2>
                        <form onSubmit={handleSubmit} className="space-y-4">
                            {!editingProduct && (
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Vendedor</label>
                                    <select
                                        value={formData.seller_id}
                                        onChange={(e) => setFormData({ ...formData, seller_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">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">Descrição</label>
                                <textarea
                                    value={formData.description}
                                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                                    className="mt-1 w-full rounded border px-3 py-2"
                                    rows={2}
                                />
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Lote</label>
                                    <input
                                        type="text"
                                        value={formData.batch}
                                        onChange={(e) => setFormData({ ...formData, batch: 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">Validade</label>
                                    <input
                                        type="date"
                                        value={formData.expires_at}
                                        onChange={(e) => setFormData({ ...formData, expires_at: 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">Preço (R$)</label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        min="0"
                                        value={formData.price_cents / 100}
                                        onChange={(e) => {
                                            const value = parseFloat(e.target.value)
                                            setFormData({ ...formData, price_cents: isNaN(value) ? 0 : Math.round(value * 100) })
                                        }}
                                        className="mt-1 w-full rounded border px-3 py-2"
                                        required
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Estoque</label>
                                    <input
                                        type="number"
                                        min="0"
                                        value={formData.stock}
                                        onChange={(e) => {
                                            const value = parseInt(e.target.value)
                                            setFormData({ ...formData, stock: isNaN(value) ? 0 : 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 px-4 py-2 text-sm text-white hover:opacity-90"
                                    style={{ backgroundColor: '#0F4C81' }}
                                >
                                    Salvar
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    )
}
