import React, { useEffect, useState } from 'react';

type ProductRecord = {
    id: string;
    sku: string | null;
    name: string;
    categoryId?: string | null;
    category: string;
    price: string;
    status: string;
    currencyCode: string;
    stockMode?: string;
    stockQuantity?: number;
    initialStockQuantity?: number;
    availabilityStatus?: string;
    description?: string | null;
};

type ProductsBootstrap = {
    companyName: string;
    productsEndpoint: string;
    categoriesEndpoint: string;
    createEndpoint: string;
    updateBase: string;
    stockAdjustBase: string;
    stockMovementBase: string;
    csrfToken: string;
};

export function ProductsWorkspace({ bootstrap }: { bootstrap: ProductsBootstrap }) {
    const [products, setProducts] = useState<ProductRecord[]>([]);
    const [categories, setCategories] = useState<Array<{ id: string; name: string }>>([]);
    const [loading, setLoading] = useState(true);
    const [editing, setEditing] = useState<ProductRecord | null>(null);
    const [selectedProductId, setSelectedProductId] = useState<string | null>(null);
    const [movements, setMovements] = useState<Array<{
        id: string;
        movementType: string;
        quantityBefore: number;
        quantityChange: number;
        quantityAfter: number;
        notes: string | null;
        author: string;
        createdAt: string | null;
    }>>([]);
    const [stockNotes, setStockNotes] = useState<Record<string, string>>({});
    const [stockAdds, setStockAdds] = useState<Record<string, string>>({});
    const [form, setForm] = useState({
        category_id: '',
        sku: '',
        name: '',
        description: '',
        price: '0',
        compare_price: '',
        currency_code: 'USD',
        status: 'active',
        stock_mode: 'tracked',
        stock_quantity: '0',
        availability_status: 'available',
    });

    async function loadProducts() {
        const [productsResponse, categoriesResponse] = await Promise.all([
            fetch(bootstrap.productsEndpoint, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json' },
            }),
            fetch(bootstrap.categoriesEndpoint, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json' },
            }),
        ]);

        const productsJson = await productsResponse.json();
        const categoriesJson = await categoriesResponse.json();
        setProducts(productsJson.data ?? []);
        setCategories(categoriesJson.data ?? []);
        setLoading(false);
    }

    useEffect(() => {
        void loadProducts();
    }, [bootstrap.productsEndpoint, bootstrap.categoriesEndpoint]);

    useEffect(() => {
        async function loadMovements() {
            if (!selectedProductId) {
                setMovements([]);
                return;
            }

            const response = await fetch(`${bootstrap.stockMovementBase}/${selectedProductId}/stock-movements`, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json' },
            });
            const json = await response.json();
            setMovements(json.data ?? []);
        }

        void loadMovements();
    }, [selectedProductId, bootstrap.stockMovementBase]);

    function resetForm() {
        setEditing(null);
        setForm({
            category_id: '',
            sku: '',
            name: '',
            description: '',
            price: '0',
            compare_price: '',
            currency_code: 'USD',
            status: 'active',
            stock_mode: 'tracked',
            stock_quantity: '0',
            availability_status: 'available',
        });
    }

    function startEdit(product: ProductRecord) {
        setEditing(product);
        setSelectedProductId(product.id);
        setForm({
            category_id: product.categoryId ?? '',
            sku: product.sku ?? '',
            name: product.name,
            description: product.description ?? '',
            price: product.price.replace('$', ''),
            compare_price: '',
            currency_code: product.currencyCode,
            status: product.status,
            stock_mode: product.stockMode ?? 'tracked',
            stock_quantity: String(product.stockQuantity ?? 0),
            availability_status: product.availabilityStatus ?? 'available',
        });
    }

    async function submitProduct() {
        const endpoint = editing ? `${bootstrap.updateBase}/${editing.id}` : bootstrap.createEndpoint;
        const method = editing ? 'PATCH' : 'POST';

        await fetch(endpoint, {
            method,
            credentials: 'same-origin',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': bootstrap.csrfToken,
            },
            body: JSON.stringify({
                category_id: form.category_id || null,
                sku: form.sku || null,
                name: form.name,
                description: form.description || null,
                price: Number(form.price),
                compare_price: form.compare_price ? Number(form.compare_price) : null,
                currency_code: form.currency_code,
                status: form.status,
                stock_mode: form.stock_mode,
                stock_quantity: Number(form.stock_quantity),
                availability_status: form.availability_status,
            }),
        });

        await loadProducts();
        resetForm();
    }

    async function addStock(product: ProductRecord) {
        const quantity = Number(stockAdds[product.id] ?? 0);
        if (!quantity || quantity <= 0) {
            return;
        }

        await fetch(`${bootstrap.stockAdjustBase}/${product.id}/stock-adjustments`, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': bootstrap.csrfToken,
            },
            body: JSON.stringify({
                quantity_change: quantity,
                notes: stockNotes[product.id] || null,
            }),
        });

        setStockAdds((current) => ({ ...current, [product.id]: '' }));
        setStockNotes((current) => ({ ...current, [product.id]: '' }));
        await loadProducts();
        setSelectedProductId(product.id);
    }

    return (
        <div className="space-y-6">
            <section className="rounded-[30px] border border-slate-200/80 bg-white p-8 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
                    <div>
                        <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">Product catalog</p>
                        <h2 className="mt-2 text-3xl font-semibold tracking-tight text-slate-950">Merchant catalog management</h2>
                        <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-600">
                            Create products, choose tracked stock or availability-only mode, set initial stock, and add purchased stock later with notes so inventory stays practical and simple.
                        </p>
                    </div>
                    <button type="button" onClick={resetForm} className="rounded-2xl bg-slate-950 px-5 py-3 text-sm font-semibold text-white hover:bg-slate-800">
                        New product
                    </button>
                </div>
            </section>

            <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <div className="grid gap-4 xl:grid-cols-4">
                    <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Product name" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                    <input value={form.sku} onChange={(e) => setForm({ ...form, sku: e.target.value })} placeholder="SKU" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                    <select value={form.category_id} onChange={(e) => setForm({ ...form, category_id: e.target.value })} className="rounded-2xl border border-slate-300 px-4 py-3 text-sm">
                        <option value="">Uncategorized</option>
                        {categories.map((category) => <option key={category.id} value={category.id}>{category.name}</option>)}
                    </select>
                    <input value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} placeholder="Price" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                    <input value={form.stock_quantity} onChange={(e) => setForm({ ...form, stock_quantity: e.target.value })} placeholder={editing ? 'Current stock' : 'Initial stock'} className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                    <select value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })} className="rounded-2xl border border-slate-300 px-4 py-3 text-sm">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                    <select value={form.stock_mode} onChange={(e) => setForm({ ...form, stock_mode: e.target.value })} className="rounded-2xl border border-slate-300 px-4 py-3 text-sm">
                        <option value="tracked">Tracked</option>
                        <option value="untracked">Available without stock management</option>
                    </select>
                    <select value={form.availability_status} onChange={(e) => setForm({ ...form, availability_status: e.target.value })} className="rounded-2xl border border-slate-300 px-4 py-3 text-sm">
                        <option value="available">Available</option>
                        <option value="out_of_stock">Out of stock</option>
                    </select>
                    <button type="button" onClick={submitProduct} className="rounded-2xl bg-emerald-500 px-5 py-3 text-sm font-semibold text-slate-950 hover:bg-emerald-400">
                        {editing ? 'Update product' : 'Create product'}
                    </button>
                </div>
            </section>

            <section className="overflow-hidden rounded-[30px] border border-slate-200/80 bg-white shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <div className="border-b border-slate-200 px-6 py-5">
                    <h3 className="text-xl font-semibold text-slate-950">{bootstrap.companyName} products</h3>
                    <p className="mt-1 text-sm text-slate-500">{loading ? 'Loading catalog...' : `${products.length} product records available.`}</p>
                </div>

                <div className="overflow-x-auto">
                    <table className="min-w-full divide-y divide-slate-200 text-sm">
                        <thead className="bg-slate-50 text-left text-slate-500">
                            <tr>
                                <th className="px-6 py-4 font-semibold">SKU</th>
                                <th className="px-6 py-4 font-semibold">Name</th>
                                <th className="px-6 py-4 font-semibold">Category</th>
                                <th className="px-6 py-4 font-semibold">Price</th>
                                <th className="px-6 py-4 font-semibold">Stock</th>
                                <th className="px-6 py-4 font-semibold">Availability</th>
                                <th className="px-6 py-4 font-semibold">Status</th>
                                <th className="px-6 py-4 font-semibold">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-200">
                            {products.map((product) => (
                                <tr key={product.id}>
                                    <td className="px-6 py-5 text-slate-600">{product.sku ?? 'N/A'}</td>
                                    <td className="px-6 py-5 font-semibold text-slate-950">{product.name}</td>
                                    <td className="px-6 py-5 text-slate-600">{product.category}</td>
                                    <td className="px-6 py-5 text-slate-600">{product.price}</td>
                                    <td className="px-6 py-5 text-slate-600">
                                        <div className="space-y-2">
                                            <div>{product.stockMode === 'tracked' ? `${product.stockQuantity ?? 0} / initial ${product.initialStockQuantity ?? 0}` : 'Not managed'}</div>
                                            {product.stockMode === 'tracked' ? (
                                                <div className="space-y-2">
                                                    <div className="flex gap-2">
                                                        <input
                                                            value={stockAdds[product.id] ?? ''}
                                                            onChange={(e) => setStockAdds((current) => ({ ...current, [product.id]: e.target.value }))}
                                                            placeholder="+ stock"
                                                            className="w-24 rounded-xl border border-slate-300 px-2 py-1 text-xs"
                                                        />
                                                        <button
                                                            type="button"
                                                            onClick={() => addStock(product)}
                                                            className="rounded-xl border border-slate-300 px-3 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                                                        >
                                                            Add
                                                        </button>
                                                    </div>
                                                    <input
                                                        value={stockNotes[product.id] ?? ''}
                                                        onChange={(e) => setStockNotes((current) => ({ ...current, [product.id]: e.target.value }))}
                                                        placeholder="Note for stock purchase"
                                                        className="w-full rounded-xl border border-slate-300 px-2 py-1 text-xs"
                                                    />
                                                </div>
                                            ) : null}
                                        </div>
                                    </td>
                                    <td className="px-6 py-5 text-slate-600">
                                        <span className={`rounded-full px-3 py-1 text-xs font-semibold ${
                                            product.stockMode === 'tracked'
                                                ? (product.stockQuantity ?? 0) <= 0
                                                    ? 'bg-rose-100 text-rose-700'
                                                    : (product.stockQuantity ?? 0) <= 5
                                                        ? 'bg-amber-100 text-amber-700'
                                                        : 'bg-emerald-100 text-emerald-700'
                                                : (product.availabilityStatus ?? 'available') === 'out_of_stock'
                                                    ? 'bg-rose-100 text-rose-700'
                                                    : 'bg-blue-100 text-blue-700'
                                        }`}>
                                            {product.stockMode === 'tracked'
                                                ? ((product.stockQuantity ?? 0) <= 0
                                                    ? 'out_of_stock'
                                                    : (product.stockQuantity ?? 0) <= 5
                                                        ? 'low_stock'
                                                        : 'available')
                                                : (product.availabilityStatus ?? 'available')}
                                        </span>
                                    </td>
                                    <td className="px-6 py-5">
                                        <span className="rounded-full bg-emerald-100 px-3 py-1 text-xs font-semibold text-emerald-700">
                                            {product.status}
                                        </span>
                                    </td>
                                    <td className="px-6 py-5 text-slate-600">
                                        <div className="flex flex-col gap-2">
                                            <button type="button" onClick={() => startEdit(product)} className="text-left font-medium text-emerald-700 hover:text-emerald-600">
                                                Edit
                                            </button>
                                            <button type="button" onClick={() => setSelectedProductId(product.id)} className="text-left text-sm text-slate-600 hover:text-slate-900">
                                                View stock history
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </section>

            {selectedProductId ? (
                <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <div className="flex items-center justify-between gap-4">
                        <div>
                            <h3 className="text-xl font-semibold text-slate-950">Stock movement history</h3>
                            <p className="mt-1 text-sm text-slate-500">See every initial stock, restock, and order deduction with notes.</p>
                        </div>
                    </div>

                    <div className="mt-5 overflow-x-auto">
                        <table className="min-w-full divide-y divide-slate-200 text-sm">
                            <thead className="bg-slate-50 text-left text-slate-500">
                                <tr>
                                    <th className="px-4 py-3 font-semibold">Type</th>
                                    <th className="px-4 py-3 font-semibold">Before</th>
                                    <th className="px-4 py-3 font-semibold">Change</th>
                                    <th className="px-4 py-3 font-semibold">After</th>
                                    <th className="px-4 py-3 font-semibold">Notes</th>
                                    <th className="px-4 py-3 font-semibold">By</th>
                                    <th className="px-4 py-3 font-semibold">Date</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-200">
                                {movements.map((movement) => (
                                    <tr key={movement.id}>
                                        <td className="px-4 py-4 text-slate-600">{movement.movementType}</td>
                                        <td className="px-4 py-4 text-slate-600">{movement.quantityBefore}</td>
                                        <td className="px-4 py-4 text-slate-600">{movement.quantityChange}</td>
                                        <td className="px-4 py-4 text-slate-600">{movement.quantityAfter}</td>
                                        <td className="px-4 py-4 text-slate-600">{movement.notes ?? 'No note'}</td>
                                        <td className="px-4 py-4 text-slate-600">{movement.author}</td>
                                        <td className="px-4 py-4 text-slate-600">{movement.createdAt ?? 'N/A'}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </section>
            ) : null}
        </div>
    );
}

export type { ProductsBootstrap };
