'use no memo';

import { Form, Head, Link, usePage } from '@inertiajs/react';
import { ArrowLeft, Minus, Plus, ShoppingCart, Trash2 } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { toast } from 'sonner';
import { InputError } from '@/components/ui';
import { NumberInput } from '@/components/inputs';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';
import { Label } from '@/components/ui/label';
import {
    Sheet,
    SheetContent,
    SheetFooter,
    SheetHeader,
    SheetTitle,
} from '@/components/ui/sheet';
import { Textarea } from '@/components/ui/textarea';
import { useStokOpnameDraftSave } from '@/hooks/use-stok-opname-draft';
import { formatNumber } from '@/lib/format';
import { loadStokOpnameDraft } from '@/lib/stok-opname-draft';
import { index as stokOpnameIndex, update } from '@/routes/admin/manage/stok-opnames';
import type { ProductForStokOpname, StokOpnameForEdit } from './columns';

type StockType = 'good' | 'reject' | 'retail';

type CartLine = {
    key: string;
    photoUrl: string | null;
    title: string;
    subtitle: string;
    quantity: number;
    onAdjust: (delta: number) => void;
    onSet: (value: number) => void;
    onRemove: () => void;
};

type Props = {
    stokOpname: StokOpnameForEdit;
    products: ProductForStokOpname[];
};

export default function StokOpnameEdit({ stokOpname, products }: Props) {
    const { auth } = usePage().props as { auth: { user?: { id?: number } } };
    const userId = auth.user?.id;

    const draft = loadStokOpnameDraft('edit', userId);

    const [selectedProductId, setSelectedProductId] = useState(
        draft?.selectedProductId ?? '',
    );

    const [physicalStocks, setPhysicalStocks] = useState<Record<string, Record<StockType, number>>>(() => {
        if (draft?.physicalStocks && Object.keys(draft.physicalStocks).length > 0) {
            return draft.physicalStocks;
        }

        const initial: Record<string, Record<StockType, number>> = {};
        for (const item of stokOpname.items) {
            const variantId = String(item.product_variant_id);
            if (!initial[variantId]) {
                initial[variantId] = { good: 0, reject: 0, retail: 0 };
            }
            initial[variantId][item.stock_quality] = item.physical_stock;
        }
        return initial;
    });
    const [notes, setNotes] = useState(draft?.notes ?? stokOpname.notes ?? '');
    const [cartOpen, setCartOpen] = useState(false);

    const draftData = useMemo(
        () => ({
            selectedProductId,
            physicalStocks,
            notes,
        }),
        [selectedProductId, physicalStocks, notes],
    );

    useStokOpnameDraftSave('edit', draftData, userId);

    const physicalStocksRef = useRef(physicalStocks);

    useEffect(() => {
        physicalStocksRef.current = physicalStocks;
    }, [physicalStocks]);

    const selectedProduct = useMemo(
        () => products.find((p) => String(p.id) === selectedProductId) ?? null,
        [products, selectedProductId],
    );

    const variantById = useMemo(
        () =>
            new Map(
                products.flatMap((p: ProductForStokOpname) =>
                    p.product_variants.map((v) => [v.id, v]),
                ),
            ),
        [products],
    );

    const productByVariantId = useMemo(
        () =>
            new Map(
                products.flatMap((p: ProductForStokOpname) =>
                    p.product_variants.map((v) => [v.id, p.name]),
                ),
            ),
        [products],
    );

    const updatePhysicalStock = useCallback((variantId: number, stockType: StockType, value: number) => {
        setPhysicalStocks((prev) => ({
            ...prev,
            [variantId]: {
                ...prev[variantId],
                [stockType]: Math.max(0, value),
            },
        }));
    }, []);

    const hasAnyStock = useCallback((variantId: number) => {
        const stocks = physicalStocks[variantId];
        if (!stocks) return false;
        return stocks.good > 0 || stocks.reject > 0 || stocks.retail > 0;
    }, [physicalStocks]);

    const cartItems: CartLine[] = (() => {
        const lines: CartLine[] = [];

        for (const [variantId, stocks] of Object.entries(physicalStocks)) {
            const id = Number(variantId);
            const variant = variantById.get(id);
            if (!variant) continue;

            for (const [stockType, quantity] of Object.entries(stocks)) {
                if (quantity <= 0) continue;

                const type = stockType as StockType;
                const typeLabel = type === 'good' ? 'Bagus' : type === 'reject' ? 'Reject' : 'Ecer';

                lines.push({
                    key: `variant-${id}-${type}`,
                    photoUrl: variant.photo_url,
                    title: `${productByVariantId.get(id) ?? ''} — ${variant.name}`,
                    subtitle: `${typeLabel}: ${formatNumber(quantity)}`,
                    quantity,
                    onAdjust: (delta) => updatePhysicalStock(id, type, quantity + delta),
                    onSet: (value) => updatePhysicalStock(id, type, value),
                    onRemove: () => updatePhysicalStock(id, type, 0),
                });
            }
        }

        return lines.sort((a, b) => a.title.localeCompare(b.title));
    })();

    function formatQuantity(value: number): string {
        return formatNumber(value, { maximumFractionDigits: 4 });
    }

    function getPayload() {
        const items: Array<{ product_variant_id: number; stock_quality: StockType; physical_stock: number }> = [];

        for (const [variantId, stocks] of Object.entries(physicalStocksRef.current)) {
            const variant = variantById.get(Number(variantId));
            if (!variant) continue;

            for (const [stockType, quantity] of Object.entries(stocks)) {
                if (quantity <= 0) continue;

                items.push({
                    product_variant_id: Number(variantId),
                    stock_quality: stockType as StockType,
                    physical_stock: quantity,
                });
            }
        }

        return {
            opname_date: stokOpname.opname_date,
            items,
            notes: notes || null,
        };
    }

    return (
        <>
            <Head title="Edit Stok Opname" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <div className="flex items-center justify-between">
                    <h2 className="text-2xl font-semibold tracking-tight">
                        Edit Stok Opname
                    </h2>
                    <Button asChild variant="outline">
                        <Link href={stokOpnameIndex.url()}>
                            <ArrowLeft className="h-4 w-4" />
                            Kembali
                        </Link>
                    </Button>
                </div>

                <Form
                    action={update(stokOpname.id)}
                    transform={(formData) => ({
                        ...formData,
                        ...getPayload(),
                    })}
                    onError={() => {
                        toast.error('Ada data yang belum sesuai, silakan periksa kembali input Anda.');
                    }}
                >
                    {({ errors, processing }) => (
                        <div className="grid gap-6 md:grid-cols-3">
                            <div className="space-y-6 md:col-span-2">
                                <Card>
                                    <CardHeader>
                                        <CardTitle>Pilih Produk</CardTitle>
                                    </CardHeader>
                                    <CardContent className="space-y-4">
                                        <div className="grid gap-2">
                                            <Label>
                                                Nama Produk{' '}
                                                <span className="text-destructive">
                                                    *
                                                </span>
                                            </Label>
                                            <Combobox
                                                items={products}
                                                itemToStringLabel={(p) =>
                                                    p.name
                                                }
                                                value={selectedProduct}
                                                onValueChange={(value) =>
                                                    setSelectedProductId(
                                                        value
                                                            ? String(value.id)
                                                            : '',
                                                    )
                                                }
                                            >
                                                <ComboboxInput
                                                    placeholder="Cari produk..."
                                                    className="w-full"
                                                />
                                                <ComboboxContent>
                                                    <ComboboxEmpty>
                                                        Tidak ada produk
                                                        ditemukan.
                                                    </ComboboxEmpty>
                                                    <ComboboxList>
                                                        {(p) => (
                                                            <ComboboxItem
                                                                key={p.id}
                                                                value={p}
                                                            >
                                                                {p.name}
                                                            </ComboboxItem>
                                                        )}
                                                    </ComboboxList>
                                                </ComboboxContent>
                                            </Combobox>
                                            <InputError
                                                message={errors.items}
                                            />
                                        </div>

                                        {selectedProduct && (
                                            <div className="space-y-4">
                                                {selectedProduct.product_variants.map(
                                                    (variant) => {
                                                        const isActive = hasAnyStock(variant.id);

                                                        return (
                                                            <div
                                                                key={variant.id}
                                                                className={`rounded-lg border p-4 ${isActive ? 'border-primary bg-primary/5' : ''}`}
                                                            >
                                                                <div className="flex items-start gap-3">
                                                                    {variant.photo_url ? (
                                                                        <img
                                                                            src={variant.photo_url}
                                                                            alt={variant.name}
                                                                            className="h-12 w-12 shrink-0 rounded-md object-cover"
                                                                        />
                                                                    ) : (
                                                                        <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
                                                                            N/A
                                                                        </div>
                                                                    )}
                                                                    <div className="min-w-0 flex-1">
                                                                        <p className="font-medium">
                                                                            {variant.name}
                                                                        </p>
                                                                        <div className="mt-2 flex gap-3">
                                                                            <div className="flex-1 space-y-1 rounded-md border p-2">
                                                                                <p className="text-xs text-muted-foreground">
                                                                                    Bagus: <span className="font-medium text-foreground">{formatQuantity(variant.stock)}</span>
                                                                                </p>
                                                                                <div className="flex items-center gap-1">
                                                                                    <Button
                                                                                        type="button"
                                                                                        variant="outline"
                                                                                        size="icon"
                                                                                        disabled={!physicalStocks[variant.id]?.good}
                                                                                        onClick={() =>
                                                                                            updatePhysicalStock(variant.id, 'good', (physicalStocks[variant.id]?.good ?? 0) - 1)
                                                                                        }
                                                                                    >
                                                                                        <Minus className="h-3 w-3" />
                                                                                    </Button>
                                                                                    <NumberInput
                                                                                        className="flex-1 text-center text-xs"
                                                                                        value={physicalStocks[variant.id]?.good ?? 0}
                                                                                        onValueChange={(val) =>
                                                                                            updatePhysicalStock(variant.id, 'good', val)
                                                                                        }
                                                                                    />
                                                                                    <Button
                                                                                        type="button"
                                                                                        variant="outline"
                                                                                        size="icon"
                                                                                        onClick={() =>
                                                                                            updatePhysicalStock(variant.id, 'good', (physicalStocks[variant.id]?.good ?? 0) + 1)
                                                                                        }
                                                                                    >
                                                                                        <Plus className="h-3 w-3" />
                                                                                    </Button>
                                                                                </div>
                                                                            </div>
                                                                            <div className="flex-1 space-y-1 rounded-md border p-2">
                                                                                <p className="text-xs text-muted-foreground">
                                                                                    Reject: <span className="font-medium text-foreground">{formatQuantity(variant.reject_stock)}</span>
                                                                                </p>
                                                                                <div className="flex items-center gap-1">
                                                                                    <Button
                                                                                        type="button"
                                                                                        variant="outline"
                                                                                        size="icon"
                                                                                        disabled={!physicalStocks[variant.id]?.reject}
                                                                                        onClick={() =>
                                                                                            updatePhysicalStock(variant.id, 'reject', (physicalStocks[variant.id]?.reject ?? 0) - 1)
                                                                                        }
                                                                                    >
                                                                                        <Minus className="h-3 w-3" />
                                                                                    </Button>
                                                                                    <NumberInput
                                                                                        className="flex-1 text-center text-xs"
                                                                                        value={physicalStocks[variant.id]?.reject ?? 0}
                                                                                        onValueChange={(val) =>
                                                                                            updatePhysicalStock(variant.id, 'reject', val)
                                                                                        }
                                                                                    />
                                                                                    <Button
                                                                                        type="button"
                                                                                        variant="outline"
                                                                                        size="icon"
                                                                                        onClick={() =>
                                                                                            updatePhysicalStock(variant.id, 'reject', (physicalStocks[variant.id]?.reject ?? 0) + 1)
                                                                                        }
                                                                                    >
                                                                                        <Plus className="h-3 w-3" />
                                                                                    </Button>
                                                                                </div>
                                                                            </div>
                                                                            <div className="flex-1 space-y-1 rounded-md border p-2">
                                                                                <p className="text-xs text-muted-foreground">
                                                                                    Ecer: <span className="font-medium text-foreground">{formatQuantity(variant.retail_stock)}</span>
                                                                                </p>
                                                                                <div className="flex items-center gap-1">
                                                                                    <Button
                                                                                        type="button"
                                                                                        variant="outline"
                                                                                        size="icon"
                                                                                        disabled={!physicalStocks[variant.id]?.retail}
                                                                                        onClick={() =>
                                                                                            updatePhysicalStock(variant.id, 'retail', (physicalStocks[variant.id]?.retail ?? 0) - 1)
                                                                                        }
                                                                                    >
                                                                                        <Minus className="h-3 w-3" />
                                                                                    </Button>
                                                                                    <NumberInput
                                                                                        className="flex-1 text-center text-xs"
                                                                                        value={physicalStocks[variant.id]?.retail ?? 0}
                                                                                        onValueChange={(val) =>
                                                                                            updatePhysicalStock(variant.id, 'retail', val)
                                                                                        }
                                                                                    />
                                                                                    <Button
                                                                                        type="button"
                                                                                        variant="outline"
                                                                                        size="icon"
                                                                                        onClick={() =>
                                                                                            updatePhysicalStock(variant.id, 'retail', (physicalStocks[variant.id]?.retail ?? 0) + 1)
                                                                                        }
                                                                                    >
                                                                                        <Plus className="h-3 w-3" />
                                                                                    </Button>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        );
                                                    },
                                                )}
                                            </div>
                                        )}
                                    </CardContent>
                                </Card>
                            </div>

                            <div className="space-y-6 md:col-span-1">
                                <Card className="sticky top-6">
                                    <CardHeader>
                                        <CardTitle>Ringkasan</CardTitle>
                                    </CardHeader>
                                    <CardContent className="space-y-4">
                                        <div className="space-y-2">
                                            <div className="flex items-center justify-between text-sm">
                                                <span className="text-muted-foreground">
                                                    Jumlah Item
                                                </span>
                                                <span className="font-medium">
                                                    {cartItems.length}
                                                </span>
                                            </div>
                                        </div>

                                        <div className="grid gap-2">
                                            <Label htmlFor="notes">
                                                Keterangan
                                            </Label>
                                            <Textarea
                                                id="notes"
                                                value={notes}
                                                onChange={(e) =>
                                                    setNotes(e.target.value)
                                                }
                                                placeholder="Masukkan keterangan"
                                                maxLength={100}
                                            />
                                            <InputError
                                                message={errors.notes}
                                            />
                                        </div>

                                        <Button
                                            type="submit"
                                            className="w-full"
                                            disabled={
                                                processing ||
                                                cartItems.length === 0
                                            }
                                        >
                                            {processing
                                                ? 'Menyimpan...'
                                                : 'Simpan'}
                                        </Button>
                                    </CardContent>
                                </Card>
                            </div>
                        </div>
                    )}
                </Form>

                <Button
                    type="button"
                    onClick={() => setCartOpen(true)}
                    className="fixed top-1/2 right-4 z-50 h-14 w-14 -translate-y-1/2 rounded-full shadow-lg"
                    size="icon"
                    aria-label="Buka keranjang stok opname"
                >
                    <ShoppingCart className="h-5 w-5" />
                    {cartItems.length > 0 && (
                        <span className="absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-xs font-semibold text-white">
                            {cartItems.length}
                        </span>
                    )}
                </Button>

                <Sheet open={cartOpen} onOpenChange={setCartOpen}>
                    <SheetContent side="right" className="w-full sm:max-w-md">
                        <SheetHeader>
                            <SheetTitle>Keranjang Stok Opname</SheetTitle>
                        </SheetHeader>

                        <div className="flex-1 space-y-4 overflow-y-auto px-6 pb-6">
                            {cartItems.length === 0 ? (
                                <p className="text-sm text-muted-foreground">
                                    Keranjang kosong.
                                </p>
                            ) : (
                                (() => {
                                    const groupedByVariant: Record<string, { title: string; photoUrl: string | null; items: typeof cartItems }> = {};
                                    for (const item of cartItems) {
                                        const variantKey = item.key.split('-').slice(0, 2).join('-');
                                        if (!groupedByVariant[variantKey]) {
                                            groupedByVariant[variantKey] = {
                                                title: item.title,
                                                photoUrl: item.photoUrl,
                                                items: [],
                                            };
                                        }
                                        groupedByVariant[variantKey].items.push(item);
                                    }

                                    return Object.entries(groupedByVariant).map(([variantKey, group]) => (
                                        <div key={variantKey} className="rounded-lg border p-3 space-y-3">
                                            <div className="flex items-center justify-between">
                                                <div className="flex items-center gap-3">
                                                    {group.photoUrl ? (
                                                        <div className="h-10 w-10 shrink-0 overflow-hidden rounded-md border">
                                                            <img
                                                                src={group.photoUrl}
                                                                alt={group.title}
                                                                className="h-full w-full object-cover"
                                                            />
                                                        </div>
                                                    ) : (
                                                        <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
                                                            N/A
                                                        </div>
                                                    )}
                                                    <p className="font-medium">{group.title}</p>
                                                </div>
                                                <Button
                                                    type="button"
                                                    variant="ghost"
                                                    size="icon-sm"
                                                    onClick={() => {
                                                        for (const item of group.items) {
                                                            item.onRemove();
                                                        }
                                                    }}
                                                >
                                                    <Trash2 className="h-4 w-4 text-destructive" />
                                                </Button>
                                            </div>
                                            <div className="space-y-2">
                                                {group.items.map((item) => {
                                                    const stockType = item.key.split('-').pop();
                                                    const typeLabel = stockType === 'good' ? 'Bagus' : stockType === 'reject' ? 'Reject' : 'Ecer';

                                                    return (
                                                        <div key={item.key} className="flex items-center justify-between gap-2">
                                                            <span className="text-xs text-muted-foreground w-14">{typeLabel}</span>
                                                            <div className="flex items-center gap-1">
                                                                <Button
                                                                    type="button"
                                                                    variant="outline"
                                                                    size="icon-sm"
                                                                    disabled={item.quantity <= 0}
                                                                    onClick={() => item.onAdjust(-1)}
                                                                >
                                                                    <Minus className="h-3 w-3" />
                                                                </Button>
                                                                <NumberInput
                                                                    className="w-16 text-center text-xs"
                                                                    value={item.quantity}
                                                                    onValueChange={item.onSet}
                                                                />
                                                                <Button
                                                                    type="button"
                                                                    variant="outline"
                                                                    size="icon-sm"
                                                                    onClick={() => item.onAdjust(1)}
                                                                >
                                                                    <Plus className="h-3 w-3" />
                                                                </Button>
                                                            </div>
                                                            <span className="font-medium text-xs">
                                                                {formatQuantity(item.quantity)} pcs
                                                            </span>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        </div>
                                    ));
                                })()
                            )}
                        </div>

                        <SheetFooter>
                            <div className="flex items-center justify-between border-t pt-4">
                                <span className="text-sm">Total Item</span>
                                <span className="text-sm font-semibold">
                                    {cartItems.length}
                                </span>
                            </div>
                        </SheetFooter>
                    </SheetContent>
                </Sheet>

            </div>
        </>
    );
}
