import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Shell } from '@/layouts/Shell'
import { apiClient } from '@/services/apiClient'

interface ProductForm {
    // Step 1 - Catalog
    ean_code: string
    name: string
    description: string
    manufacturer: string
    category: string
    subcategory: string
    // Step 2 - Stock/Sales
    stock: string
    price: string
    expires_at: string
    observations: string
}

const categories = [
    'Analgésicos',
    'Antibióticos',
    'Anti-inflamatórios',
    'Cardiovasculares',
    'Dermatológicos',
    'Vitaminas',
    'Oftálmicos',
    'Respiratórios',
    'Gastrointestinais',
    'Antidiabéticos',
    'Perfumaria',
    'Higiene',
    'Outros'
]

export function ProductCreatePage() {
    const navigate = useNavigate()
    const [step, setStep] = useState(1)
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<string | null>(null)

    const [form, setForm] = useState<ProductForm>({
        ean_code: '',
        name: '',
        description: '',
        manufacturer: '',
        category: '',
        subcategory: '',
        stock: '',
        price: '',
        expires_at: '',
        observations: ''
    })

    const updateField = (field: keyof ProductForm, value: string) => {
        setForm(prev => ({ ...prev, [field]: value }))
    }

    const handleClear = () => {
        if (step === 1) {
            setForm(prev => ({
                ...prev,
                ean_code: '',
                name: '',
                description: '',
                manufacturer: '',
                category: '',
                subcategory: ''
            }))
        } else {
            setForm(prev => ({
                ...prev,
                stock: '',
                price: '',
                expires_at: '',
                observations: ''
            }))
        }
    }

    const handleNext = () => {
        // Validate step 1
        if (!form.ean_code || !form.name || !form.manufacturer || !form.category) {
            setError('Preencha todos os campos obrigatórios')
            return
        }
        setError(null)
        setStep(2)
    }

    const handleBack = () => {
        setStep(1)
        setError(null)
    }

    const handleSubmit = async () => {
        // Validate step 2
        if (!form.stock || !form.price || !form.expires_at) {
            setError('Preencha todos os campos obrigatórios')
            return
        }

        setLoading(true)
        setError(null)

        try {
            const priceCents = Math.round(parseFloat(form.price.replace(',', '.')) * 100)

            await apiClient.post('/v1/products', {
                ean_code: form.ean_code,
                name: form.name,
                description: form.description,
                manufacturer: form.manufacturer,
                category: form.category,
                subcategory: form.subcategory,
                batch: `L${new Date().getFullYear()}${String(Math.floor(Math.random() * 999)).padStart(3, '0')}`,
                expires_at: form.expires_at,
                price_cents: priceCents,
                stock: parseInt(form.stock),
                observations: form.observations
            })

            navigate('/inventory')
        } catch (err) {
            console.error(err)
            setError('Erro ao cadastrar produto')
        } finally {
            setLoading(false)
        }
    }

    return (
        <Shell>
            <div className="max-w-4xl mx-auto">
                {/* Header */}
                <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
                    <h1 className="text-2xl font-semibold text-gray-800">Novo cadastro de produto</h1>
                    <p className="text-gray-500 mt-1">
                        O fluxo é dividido em duas etapas: catálogo, venda/estoque. Informe os dados obrigatórios em cada aba para concluir o processo.
                    </p>
                </div>

                {/* Form Card */}
                <div className="bg-white rounded-lg shadow-sm p-6">
                    {/* Steps Indicator */}
                    <div className="flex justify-center mb-8">
                        <div className="flex items-center gap-16">
                            {/* Step 1 */}
                            <div className="flex flex-col items-center">
                                <div className={`w-10 h-10 rounded-full flex items-center justify-center text-white font-semibold ${step >= 1 ? 'bg-blue-600' : 'bg-gray-300'
                                    }`}>
                                    1
                                </div>
                                <p className={`mt-2 text-sm font-medium ${step >= 1 ? 'text-gray-800' : 'text-gray-400'}`}>
                                    Etapa 1
                                </p>
                                <p className="text-xs text-gray-500">Dados do catálogo</p>
                            </div>

                            {/* Progress Line */}
                            <div className={`w-32 h-1 ${step === 2 ? 'bg-blue-600' : 'bg-gray-200'}`} />

                            {/* Step 2 */}
                            <div className="flex flex-col items-center">
                                <div className={`w-10 h-10 rounded-full flex items-center justify-center text-white font-semibold ${step === 2 ? 'bg-blue-600' : 'bg-gray-300'
                                    }`}>
                                    2
                                </div>
                                <p className={`mt-2 text-sm font-medium ${step === 2 ? 'text-gray-800' : 'text-gray-400'}`}>
                                    Etapa 2
                                </p>
                                <p className="text-xs text-gray-500">Estoque e Venda</p>
                            </div>
                        </div>
                    </div>

                    {/* Error Message */}
                    {error && (
                        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded text-red-700 text-sm">
                            {error}
                        </div>
                    )}

                    {/* Step 1 Form */}
                    {step === 1 && (
                        <div className="space-y-6">
                            <div className="grid grid-cols-2 gap-6">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">
                                        Código EAN/Barras <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                        type="text"
                                        placeholder="Digite o código EAN"
                                        value={form.ean_code}
                                        onChange={(e) => updateField('ean_code', e.target.value)}
                                        className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">
                                        Nome <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                        type="text"
                                        placeholder="Digite o nome do produto (mín. 3 caracteres para sugestões)"
                                        value={form.name}
                                        onChange={(e) => updateField('name', e.target.value)}
                                        className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-6">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">
                                        Descrição
                                    </label>
                                    <textarea
                                        placeholder="Detalhes do produto"
                                        value={form.description}
                                        onChange={(e) => updateField('description', e.target.value)}
                                        rows={3}
                                        className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">
                                        Laboratório/Fabricante <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                        type="text"
                                        placeholder="Digite o nome do laboratório"
                                        value={form.manufacturer}
                                        onChange={(e) => updateField('manufacturer', e.target.value)}
                                        className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-6">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">
                                        Categoria <span className="text-red-500">*</span>
                                    </label>
                                    <select
                                        value={form.category}
                                        onChange={(e) => updateField('category', e.target.value)}
                                        className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
                                    >
                                        <option value="">Selecione uma categoria</option>
                                        {categories.map(cat => (
                                            <option key={cat} value={cat}>{cat}</option>
                                        ))}
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">
                                        Subcategoria
                                    </label>
                                    <input
                                        type="text"
                                        placeholder="Subcategoria (opcional)"
                                        value={form.subcategory}
                                        onChange={(e) => updateField('subcategory', e.target.value)}
                                        className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    />
                                </div>
                            </div>

                            {/* Step 1 Actions */}
                            <div className="flex justify-end gap-3 pt-4">
                                <button
                                    type="button"
                                    onClick={handleClear}
                                    className="px-6 py-2.5 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-50"
                                >
                                    Limpar
                                </button>
                                <button
                                    type="button"
                                    onClick={handleNext}
                                    className="px-6 py-2.5 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700"
                                >
                                    Avançar
                                </button>
                            </div>
                        </div>
                    )}

                    {/* Step 2 Form */}
                    {step === 2 && (
                        <div className="space-y-6">
                            <div className="grid grid-cols-2 gap-6">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">
                                        Quantidade em estoque <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                        type="number"
                                        placeholder="Digite a quantidade disponível"
                                        value={form.stock}
                                        onChange={(e) => updateField('stock', e.target.value)}
                                        min="0"
                                        className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">
                                        Preço de venda (R$) <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                        type="text"
                                        placeholder="0.00"
                                        value={form.price}
                                        onChange={(e) => updateField('price', e.target.value)}
                                        className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    Data de validade <span className="text-red-500">*</span>
                                </label>
                                <input
                                    type="date"
                                    value={form.expires_at}
                                    onChange={(e) => updateField('expires_at', e.target.value)}
                                    className="w-full max-w-xs px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    Observações
                                </label>
                                <textarea
                                    placeholder="Informações adicionais sobre o produto"
                                    value={form.observations}
                                    onChange={(e) => updateField('observations', e.target.value)}
                                    rows={4}
                                    className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"
                                />
                            </div>

                            {/* Step 2 Actions */}
                            <div className="flex justify-between pt-4">
                                <button
                                    type="button"
                                    onClick={handleBack}
                                    className="px-6 py-2.5 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-50"
                                >
                                    Voltar
                                </button>
                                <div className="flex gap-3">
                                    <button
                                        type="button"
                                        onClick={handleClear}
                                        className="px-6 py-2.5 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-50"
                                    >
                                        Reiniciar
                                    </button>
                                    <button
                                        type="button"
                                        onClick={handleSubmit}
                                        disabled={loading}
                                        className="px-6 py-2.5 bg-green-600 text-white rounded-lg font-medium hover:bg-green-700 disabled:opacity-50"
                                    >
                                        {loading ? 'Salvando...' : 'Concluir cadastro'}
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </Shell>
    )
}
