/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react-hooks/exhaustive-deps */
import Pagination from '@/components/pagination';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { User as Cashier } from '@/types';
import { Category } from '@/types/category';
import { Head, router, useForm, usePage } from '@inertiajs/react';
import { Save, Search, StickyNote, TicketPercent, Trash2, Truck, User, UserCircle, ScanBarcodeIcon, CheckCircle2, Printer, Check, Minus, Eraser, MonitorPause} from 'lucide-react';
import React, { useCallback, useEffect, useState, useRef } from 'react';
import PosLayout from './layout-pos/PosLayout';
import { Product, ProductLink } from '@/types/product';
import { Menu, MenuLink } from '@/types/menu';
import { Table } from '@/types/table';
import { toast } from 'sonner';
import { BankAccount } from '@/types/bank';
import { useAppContext } from '@/contexts/app-context';
import { Setting } from '@/types/setting';
import axios from 'axios';
import { debounce } from 'lodash';
import { DiscountPackage } from '@/types/discount-package';
import { Shift } from '@/types/shift';
import BarcodeScannerHtml5 from '@/components/barcode-scanner-html5';
import { Card, CardContent } from '@/components/ui/card';
import BluetoothPrintButton from '@/components/BluetoothPrintButton';

interface IndexProps {
    cashiers: Cashier[];
    categories: Category[];
    tables: Table[];
    banks: BankAccount[];
    settings: Setting[];
    shifts: Shift[];
    filters: {
        search?: string;
        category?: string;
    };
    items: {
        data: Product[] | Menu[];
        links: ProductLink[] | MenuLink[];
    };
    [key: string]: unknown;
}

interface Item {
    id?: string;
    name: string;
    price: number;
    quantity: number;
    discount_type: string;
    discount: string;
    note: string;
    type: string;
    total_price: number;
    stock: number;
    [key: string]: unknown;
}

interface CartItems {
    id?: string;
    name: string;
    price: number;
    quantity: number;
    discount_type: string;
    discount: string;
    note: string;
    total_price: number;
    type: string;
    stock: number;
    [key: string]: any;
}


export default function Index() {
    const { cashierShift, shifts, cashiers, categories, items, filters, banks, settings } = usePage<IndexProps>().props;

    const {
        selectedOrderType,
        setSelectedOrderType,
        selectedPlatform,
        setSelectedPlatform,
        selectedTable,
        setSelectedTable,
        transaction,
        setTransaction
    } = useAppContext();

    const lastInputTime = useRef<number>(0);
    const barcodeBuffer = useRef<string>('');
    const [scanBarcode, setScanBarcode] = useState('');
    const scanInputRef = useRef<HTMLInputElement>(null);
    const scanTimer = useRef<NodeJS.Timeout | null>(null);
    const [activeInput, setActiveInput] = useState<'search' | 'barcode' | null>('search');
    const [showCamera, setShowCamera] = useState(false);

    const { data, setData, post, processing, errors } = useForm({
        items: [] as any[],
        cashierId: '',
        note: '',
        selectedOrderType: '',
        selectedTable: '',
        selectedPlatform: '',
        filters: {
            search: filters.search,
            category: filters.category,
        },
        carts: [] as CartItems[],
        modalProduct: false as boolean,
        modalCashier: false as boolean,
        modalItem: false as boolean,
        modalDiscount: false as boolean,
        modalCustomer: false as boolean,
        newModalCustomer: false as boolean,
        modalShiftCashier: false as boolean,
        modalPayment: false as boolean,
        modalNote: false as boolean,
        modalDelivery: false as boolean,
        cashierShift: {
            shift_id: '',
            cash: 0,
        },
        newCust: {
            name: '',
            email: '',
            phone: '',
            address: '',
        },
        customers: [] as any[],
        searchCustomer: '',
        selectedCustomer: {
            id: '',
            name: '',
        },
        selectedItem: {
            name: '', quantity: 0, price: 0, discount_type: '', discount: '', note: '', type: '', stock: 0, total_price: 0,
        },
        selectedPaymentMethod: '',
        selectedBank: '',
        discounts: {
            code: '',
            discount_type: '',
            discount_amount: 0,
        },
        delivery: {
            name: '',
            no_resi: '',
            address: '',
            note: '',
            status: '',
        },
        notes: {
            no_ref: '',
            transaction_source: '',
            note: '',
        },
        pay: 0,
        remains: 0,
        return: 0,
        discount: 0,
        subTotal: 0,
        other: 0,
        ppn: 0,
        grandTotal: 0,
        isPendingOrder: false as boolean,
        invoice: '',
        modalTransaction: false as boolean,
       
        lastTransaction: {
            invoice: '',
            transaction_type: '',
            pay: '',
            return: ''
        },
        transaction_taxs: [] as { code: string; name: string; value: number }[],
    });

    

    const recalculateTotals = (carts: Item[], discount: number, settings: any[]) => {
        const subTotal = carts.reduce((sum, item) => sum + item.total_price, 0);
        const taxableBase = Math.max(subTotal - discount, 0);

        const activePpns = settings.filter((s) => s.code === 'PJK' && s.is_active);
        const ppnAmount = activePpns.reduce((total, s) => {
            if (s.value.endsWith('%')) {
                const percent = parseFloat(s.value) || 0;
                return total + (taxableBase * percent) / 100;
            } else {
                return total + (parseInt(s.value) || 0);
            }
        }, 0);

        const activeOprs = settings.filter((s) => s.code === 'OPR' && s.is_active);
        const oprAmount = activeOprs.reduce((total, s) => {
            if (s.value.endsWith('%')) {
                const percent = parseFloat(s.value) || 0;
                return total + (taxableBase * percent) / 100;
            } else {
                return total + (parseInt(s.value) || 0);
            }
        }, 0);

        const grandTotal = subTotal > 0 ? subTotal + ppnAmount + oprAmount - discount : 0;

        return { subTotal, ppnAmount, oprAmount, grandTotal };
    };


   

        const { subTotal, ppnAmount, oprAmount, grandTotal } = recalculateTotals(carts, 0, settings);
        const { rows } = buildTransactionTaxRows(settings, subTotal, 0);

        setData((prevData) => ({
            ...prevData,
            selectedOrderType: transaction.transaction_type,
            selectedTable: transaction.transaction_type === 'dine_in' ? transaction.table_id : '',
            selectedPlatform: '',
            selectedCustomer: {
                id: transaction.customer?.id ?? '',
                name: transaction.customer?.name ?? '',
            },
            carts,
            subTotal,
            ppn: ppnAmount,
            other: oprAmount,
            grandTotal,
            transaction_taxs: rows,
            isPendingOrder: true,
            invoice: transaction.invoice
        }));
    }, [transaction, settings]);


    const priceItem = (item: Product | Menu | DiscountPackage) => {
        switch (item.type) {
            case 'menu':
                return item.selling_price;
            case 'package':
                return item.total_price;
            default:
                return item.price;
        }
    }

    const fetchCoupon = async () => {
        try {
            const response = await axios(route('apps.options.get-coupons'), {
                params: {
                    code: data.discounts.code,
                }
            })

            if (response.data.code === 200)
                setData(prevData => ({
                    ...prevData,
                    discounts: {
                        code: response.data.data.code,
                        discount_type: response.data.data.type == 'percentage' ? 'persen' : 'nominal',
                        discount_amount: response.data.data.value,
                    }
                }));
        } catch (e) {
            console.log(e);
        }
    }

    useEffect(() => {
        if (data.discounts.code != '')
            fetchCoupon();
    }, [data.discounts.code]);

    useEffect(() => {
        setData('items', items.data);
    }, [items.data]);

  

        const value = platformSetting.value.trim();

       

        setData('items', updatedItems);
    }, [selectedPlatform, items.data, selectedOrderType, selectedTable]);

    useEffect(() => {
        const pay = Number(data.pay) || 0
        const total = Number(data.grandTotal) || 0

        if (pay >= total) {
            setData(prev => ({
                ...prev,
                return: pay - total,
                remains: 0,
            }))
        } else {
            setData(prev => ({
                ...prev,
                return: 0,
                remains: total - pay,
            }))
        }
    }, [data.pay])

    useEffect(() => {
        const taxableBase = Math.max(data.subTotal - data.discount, 0);

        const activePpns = settings.filter((setting) => setting.code === 'PJK' && setting.is_active);
        const ppnAmount = activePpns.reduce((total, setting) => {
            if (setting.value.endsWith('%')) {
                const percent = parseFloat(setting.value.replace('%', '')) || 0;
                return total + (taxableBase * percent) / 100;
            } else {
                return total + (parseInt(setting.value) || 0);
            }
        }, 0);

        setData((prev) => ({
            ...prev,
            ppn: ppnAmount,
            grandTotal: prev.subTotal > 0 ? prev.subTotal + ppnAmount + prev.other - prev.discount : 0,
        }));
    }, [data.subTotal, data.discount, settings]);

    useEffect(() => {
        const taxableBase = Math.max(data.subTotal - data.discount, 0);

        const activeOprs = settings.filter((setting) => setting.code === 'OPR' && setting.is_active);
        const oprAmount = activeOprs.reduce((total, setting) => {
            if (setting.value.endsWith('%')) {
                const percent = parseFloat(setting.value.replace('%', '')) || 0;
                return total + (taxableBase * percent) / 100;
            } else {
                return total + (parseInt(setting.value) || 0);
            }
        }, 0);

        setData((prev) => ({
            ...prev,
            other: oprAmount,
            grandTotal: prev.subTotal > 0 ? prev.subTotal + prev.ppn + oprAmount - prev.discount : 0,
        }));
    }, [data.subTotal, data.discount, data.ppn, settings]);

    // mark the current category as active
    const activeCategory = filters.category;


   

    // remove all carts data
    const removeChart = () => {
        setData(prevData => ({
            ...prevData,
            carts: [],
            selectedItem: {
                name: '', quantity: 0, price: 0, discount_type: '', discount: '', note: '', type: '', stock: 0, total_price: 0,
            },
            discounts: {
                code: '',
                discount_type: '',
                discount_amount: 0,
            },
            pay: 0,
            remains: 0,
            return: 0,
            discount: 0,
            subTotal: 0,
            other: 0,
            ppn: 0,
            grandTotal: 0,
            transaction_taxs: [],
        }))
    };

    // apply discounts
    const applyDiscount = () => {
        let discount = data.discounts.discount_amount;
        const subTotal = Number(data.subTotal);
        let grandTotal = subTotal;

        if (data.discounts.discount_type === 'nominal') {
            grandTotal = subTotal - Number(discount || 0);
        } else {
            grandTotal = subTotal - ((Number(discount || 0) / 100) * subTotal);
            discount = (Number(discount || 0) / 100) * subTotal;
        }

        const { rows, ppnAmount, oprAmount } = buildTransactionTaxRows(settings, subTotal, discount);

        setData({
            ...data,
            discount: discount,
            grandTotal: grandTotal,
            ppn: ppnAmount,
            other: oprAmount,
            transaction_taxs: rows,
            modalDiscount: !data.modalDiscount,
        });
    }

    // get last transaction
    const getLastTransaction = async () => {
        try {
            const response = await axios.get(route('apps.options.get-last-transactions'));
            setData(prevData => ({
                ...prevData,
                grandTotal: 0,
                lastTransaction: {
                    invoice: response.data.data.invoice,
                    transaction_type: response.data.data.transaction_type,
                    pay: response.data.data.pay,
                    return: response.data.data.change
                },
                transactionPrint: response.data.data,
                modalTransaction: true
            }))
        } catch (e) {
            console.log(e);
        }
    };

    // store data
   

    // sound add to cart
    const playAddToCartSound = () => {
        const audio = new Audio('/sounds/add-to-cart.mp3');
        audio.play();
    };

    // get list customer by request
    const getListCustomer = async () => {
        try {
            const response = await axios.get(route('apps.customers.list-customer-by-request'), {
                params: {
                    selectedCustomer: data.searchCustomer
                }
            });
            setData('customers', response.data);
        } catch (e) {
            console.log(e);
        }
    };

    const debouncedGetListCustomer = useCallback(
        debounce(() => {
            getListCustomer();
        }, 500),
        [data.searchCustomer]
    );

    

    // store customer
    const storeCustomer = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();

        try {
            const response = await axios.post(route('apps.customers.store'), {
                name: data.newCust.name,
                email: data.newCust.email,
                phone: data.newCust.phone,
                address: data.newCust.address
            })

            const newCustomer = response.data.customer;

            setData(prevData => ({
                ...prevData,
                newCust: {
                    name: '',
                    email: '',
                    phone: '',
                    address: '',
                },
                newModalCustomer: !prevData.newModalCustomer,
                modalCustomer: !prevData.modalCustomer,
                selectedCustomer: {
                    id: newCustomer.id,
                    name: newCustomer.name,
                },
            }));
        } catch (e) {
            console.log(e);
        }
    }

    // store cashier shift
    const storeCashierShift = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();

        post(route('apps.pos.open-cashier-shift'), {
            onSuccess: () => {
                toast('Shift kasir berhasil dibuka');
                setData(prevData => ({
                    ...prevData,
                    modalShiftCashier: !data.modalShiftCashier,
                    cashierShift: {
                        shift_id: '',
                        cash: 0,
                    }
                }));
            },
            onError: (errors) => {
                console.error(errors);
                toast.error('Gagal membuka shift kasir, silakan coba lagi.');
            }
        });
    }

    useEffect(() => {
        if (data.selectedPaymentMethod === 'transfer') {
            setData((prev) => ({ ...prev, pay: data.grandTotal }));
        } else if (data.selectedPaymentMethod === 'tunai') {
            setData((prev) => ({ ...prev, pay: 0 }));
        }
    }, [data.selectedPaymentMethod, data.grandTotal]);

    // filter menu by search
    


    

    const buildVariantLabel = (pv: any) => {
        try {
            const vals: Array<{ opt?: string; val?: string }> =
                (pv?.product_variant_values ?? []).map((vv: any) => ({
                    opt: vv?.variant_value?.variant_option?.name,
                    val: vv?.variant_value?.name,
                }));
            const parts = vals
                .filter((v) => v.opt && v.val)
                .map((v) => `${v.opt}: ${v.val}`);
            return parts.length ? ` [${parts.join(', ')}]` : '';
        } catch {
            return '';
        }
    };

    const nameFromMorph = (morph: any): string => {
        if (!morph) return 'Item';
        if ('discount_package_items' in morph) return morph?.name ?? 'Paket';
        if ('product' in morph || 'product_variant_values' in morph) {
            const base = morph?.product?.name ?? morph?.name ?? 'Produk';
            return `${base}${buildVariantLabel(morph)}`;
        }
        if ('category' in morph) return morph?.name ?? 'Menu';
        return morph?.name ?? 'Item';
    };

    type ReceiptItem = {
        name: string;
        qty: number;
        price: number;
        total: number;
    };

    const tx = {
        invoice: data?.transactionPrint?.invoice,
        cashier_name:
            data?.transactionPrint?.cashier_shift?.user?.name ??
            data?.transactionPrint?.cashier?.name ??
            data?.transactionPrint?.user?.name ??
            "-",
        order_type_label: mapOrderTypeLabel(
            data?.transactionPrint?.transaction_type,
            data?.transactionPrint?.platform
        ),
        table_number: data?.transactionPrint?.table?.number,
        customer_name: (data?.transactionPrint?.customer?.name ?? "Umum") || "Umum",
        items: mapDetailsToReceiptItems(data?.transactionPrint),
        subtotal: computeSubtotal(mapDetailsToReceiptItems(data?.transactionPrint)),
        discount: n(data?.transactionPrint?.discount),
        taxes: Array.isArray(data?.transactionPrint?.transaction_taxs)
            ? data?.transactionPrint?.transaction_taxs.map((t: any) => ({
                label: t?.name ?? t?.code ?? "Pajak",
                value: n(t?.value),
            }))
            : [],
        grand_total: n(
            data?.transactionPrint?.grand_total ?? data?.transactionPrint?.grandTotal
        ),
        pay: n(data?.transactionPrint?.paid),
        change: n(data?.transactionPrint?.return),
      
    };



    return (
        <>
            {!cashierShift
                ?
                <PosLayout>
                    <Head title="Kasir" />
                    <div className="flex h-full items-center justify-center">
                        <div className="text-center">
                            <h1 className="text-2xl font-bold mb-4">Shift Kasir Belum Dibuka</h1>
                            <p className="text-muted-foreground mb-4">Silakan buka shift kasir terlebih dahulu untuk melanjutkan.</p>
                            <Button type='button' onClick={() => setData('modalShiftCashier', !data.modalShiftCashier)}>Buka Shift Kasir</Button>
                        </div>

                        <Dialog open={data.modalShiftCashier} onOpenChange={() => setData('modalShiftCashier', !data.modalShiftCashier)}>
                            <DialogContent className="max-w-sm">
                                <DialogHeader>
                                    <DialogTitle>Buka Shift Kasir</DialogTitle>
                                    <DialogDescription>Silahkan buka shift kasir terlebih dahulu.</DialogDescription>
                                </DialogHeader>
                                <form className='space-y-4' onSubmit={storeCashierShift}>
                                    <div>
                                        <Label>Shift</Label>
                                        <Select value={String(data.cashierShift.shift_id)} onValueChange={(value) => setData('cashierShift.shift_id', value)}>
                                            <SelectTrigger className="w-full">
                                                <SelectValue placeholder="Pilih Shift" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {shifts.map((shift) => (
                                                    <SelectItem key={shift.id} value={String(shift.id)}>
                                                        {shift.name} ({shift.start_time} s.d {shift.end_time})
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <p className="text-red-500 text-xs">{errors['cashierShift.shift_id']}</p>
                                    </div>
                                    <div>
                                        <Label>Uang Kembalian</Label>
                                        <Input value={data.cashierShift.cash} onChange={(e) => setData('cashierShift.cash', Number(e.target.value))} />
                                        <p className="text-red-500 text-xs">{errors['cashierShift.cash']}</p>
                                    </div>
                                    <Button type='submit' variant={'secondary'}>
                                        <Save /> Buka Kasir
                                    </Button>
                                </form>
                            </DialogContent>
                        </Dialog>
                    </div>
                </PosLayout>
                :
                <PosLayout>
                    <Head title="Kasir" />
                    <div className="grid h-full grid-cols-1 gap-2 md:grid-cols-3">
                        <div className="border-border bg-card flex h-full min-h-0 flex-col justify-between rounded-xl border shadow-sm md:col-span-1">
                            {/* Area keranjang */}
                            <div className="flex min-h-0 flex-grow flex-col p-4">
                                <div className="relative mb-0">
                                    <div className="flex items-center justify-between">
                                        {/* Label Pelanggan */}
                                        <label className="flex cursor-pointer items-center gap-2 select-none">
                                            <button
                                                type="button"
                                                onClick={() => setData('modalCustomer', !data.modalCustomer)}
                                                className="rounded-md p-2 transition hover:bg-gray-100"
                                                aria-label="Pilih Pelanggan"
                                            >
                                                <User className="h-4 w-4 text-gray-600" />
                                            </button>
                                            <span className="text-sm text-foreground font-medium select-text">{data.selectedCustomer.name != '' ? data.selectedCustomer.name : 'Umum'}</span>
                                        </label>

                                        {/* Tombol Search (Mobile only) */}
                                        <button
                                            type="button"
                                            onClick={() => setData('modalProduct', !data.modalProduct)}
                                            className="block rounded-md p-2 transition hover:bg-gray-100 md:hidden"
                                            aria-label="Cari Produk"
                                        >
                                            <Search className="h-4 w-4 text-gray-600" />
                                        </button>
                                    </div>
                                </div>
                                <div className="border-border my-2 border-t" />

                                {/* Keranjang Items */}
                                <div className="mb-4 min-h-0 flex-grow overflow-y-auto pr-2">
                                    <div className="space-y-2">
                                        {data.carts.map((item, index) => (
                                            <div
                                                key={index}
                                                className="hover:bg-accent flex cursor-pointer items-start justify-between rounded p-2"
                                                onClick={() => handleModalItem(item)}
                                            >
                                                <div>
                                                    <span className="text-sm font-medium text-foreground">{item.name}</span>
                                                    <div className="text-muted-foreground mt-1 flex items-center gap-x-4 text-sm">
                                                        <span>Rp {item.price}</span>
                                                        <span>x{item.quantity}</span>
                                                    </div>
                                                    {item.details && item.details.length > 0 &&
                                                        <div className='flex flex-col gap-1'>
                                                            {item.details.map((detail: any, detailIndex: number) => (
                                                                <span key={detailIndex} className="text-xs text-muted-foreground"> - {detail.name}</span>
                                                            ))}
                                                        </div>
                                                    }
                                                    <p className="text-muted-foreground mt-0.5 text-xs italic">{item.note}</p>
                                                </div>
                                                <p className="text-sm font-medium text-foreground">Rp {item.total_price}</p>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </div>

                            <div className="bg-card rounded-b-xl border-t p-4">
                                <div className="text-muted-foreground mb-4 space-y-2 text-sm">
                                    <div className="flex justify-between">
                                        <span>Total Item</span>
                                        <span className="text-foreground font-medium">{data.carts.length}</span>
                                    </div>

                                    <div className="flex justify-between">
                                        <span>Total Belanja</span>
                                        <span className="text-foreground font-medium">Rp {data.subTotal}</span>
                                    </div>
                                    {data.discount > 0 && (
                                        <>
                                            <div className="flex justify-between">
                                                <span>Diskon</span>
                                                <span className="text-foreground font-medium">-Rp {data.discount}</span>
                                            </div>
                                            <hr className="border-border my-2" />
                                            <div className="flex justify-between">
                                                <span>Total Setelah Diskon</span>
                                                <span className="text-foreground font-medium">Rp {data.subTotal - data.discount}</span>
                                            </div>
                                        </>
                                    )}
                                    {data.carts.length > 0 && data.ppn > 0 && settings
                                        .filter((setting) => setting.code === 'PJK' && setting.is_active == true)
                                        .map((setting) => {
                                            const taxableBase = Math.max(data.subTotal - data.discount, 0);
                                            let amount = 0;
                                            if (setting.value.endsWith('%')) {
                                                const percent = parseFloat(setting.value.replace('%', '')) || 0;
                                                amount = (taxableBase * percent) / 100;
                                            } else {
                                                amount = parseInt(setting.value) || 0;
                                            }
                                            return (
                                                <div className="flex justify-between" key={setting.id}>
                                                    <span>{setting.name} ({setting.value})</span>
                                                    <span className="text-foreground font-medium">Rp {amount}</span>
                                                </div>
                                            );
                                        })}

                                    {data.carts.length > 0 && data.other > 0 && settings
                                        .filter((setting) => setting.code === 'OPR' && setting.is_active == true)
                                        .map((setting) => {
                                            const taxableBase = Math.max(data.subTotal - data.discount, 0);
                                            let amount = 0;
                                            if (setting.value.endsWith('%')) {
                                                const percent = parseFloat(setting.value.replace('%', '')) || 0;
                                                amount = (taxableBase * percent) / 100;
                                            } else {
                                                amount = parseInt(setting.value) || 0;
                                            }
                                            return (
                                                <div className="flex justify-between" key={setting.id}>
                                                    <span>{setting.name} ({setting.value})</span>
                                                    <span className="text-foreground font-medium">Rp {amount}</span>
                                                </div>
                                            );
                                        })}
                                </div>

                                <div className="mb-4 flex items-center justify-between gap-2">
                                    <div className="flex gap-1">
                                        <Button variant="destructive" size="icon" title="Batal" className="rounded-md" onClick={() => removeChart()}>
                                            <Trash2 className="h-5 w-5" />
                                        </Button>
                                    </div>

                                    <div className="flex gap-1">
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            title="Diskon"
                                            onClick={() => setData('modalDiscount', !data.modalDiscount)}
                                            className="hover:bg-primary/80 bg-muted border-border rounded-md border"
                                        >
                                            <TicketPercent className="h-5 w-5" />
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            title="Catatan"
                                            onClick={() => setData('modalNote', !data.modalNote)}
                                            className="hover:bg-primary/80 bg-muted border-border rounded-md border"
                                        >
                                            <StickyNote className="h-5 w-5" />
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            title="Pengiriman"
                                            onClick={() => setData('modalDelivery', !data.modalDelivery)}
                                            className="hover:bg-primary/80 bg-muted border-border rounded-md border"
                                        >
                                            <Truck className="h-5 w-5" />
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            title="Pelayan"
                                            onClick={() => setData('modalCashier', !data.modalCashier)}
                                            className="hover:bg-primary/80 bg-muted border-border rounded-md border"
                                        >
                                            <UserCircle className="h-5 w-5" />
                                        </Button>
                                        {/* <Button variant="ghost" size="icon" title="Pilih Meja" onClick={() => setIsMejaOpen(true)} className="hover:bg-primary/80 bg-muted border border-border rounded-md">
                                                    <LayoutGrid className="w-5 h-5" />
                                                </Button> */}
                                    </div>
                                </div>

                                <div className="flex gap-2">
                                    <Button className="flex-1 h-12 text-base rounded-lg" onClick={() => setData('modalPayment', !data.modalPayment)}>
                                        Bayar • Rp {data.grandTotal}
                                    </Button>
                                    <form onSubmit={storeData}>
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            title="Pending order"
                                            className="h-12 w-12 bg-warning hover:bg-primary border rounded-lg"
                                            type='submit'
                                            onClick={() => setData('isPendingOrder', true)}
                                        >
                                            <MonitorPause className="h-5 w-5" />
                                        </Button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        {/* Area Produk */}
                       
                    </div>

                    {/* Dialog Produk Mobile */}
                    <Dialog open={data.modalProduct} onOpenChange={(open) => setData('modalProduct', open)}>
                        <DialogContent className="max-w-full max-h-[90vh] p-4 overflow-y-auto">
                            <DialogHeader>
                                <DialogTitle>Pilih Produk</DialogTitle>
                            </DialogHeader>
                            <div className="mb-4 flex items-center gap-1 transition-all">
                                {/* Input Cari Produk */}
                                {activeInput === 'barcode' ? (
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setActiveInput('search');
                                            setTimeout(() => document.getElementById('searchInput')?.focus(), 50);
                                        }}
                                        className="p-2 rounded-md border hover:bg-accent"
                                        title="Cari produk"
                                    >
                                        <Search className="w-5 h-5 text-muted-foreground" />
                                    </button>
                                ) : (
                                    <Input
                                        id="searchInput"
                                        type="text"
                                        placeholder="Cari produk berdasarkan nama/barcode/sku"
                                        className="flex-1 transition-all"
                                        value={data.filters.search}
                                        onFocus={() => setActiveInput('search')}
                                        onChange={(e) => handleFilterSearch(e)}
                                    />
                                )}

                                {/* Input Scan Barcode */}
                                {activeInput === 'search' ? (
                                    <div className="flex items-center gap-1">
                                        <button
                                            type="button"
                                            onClick={() => {
                                                setActiveInput('barcode');
                                                setTimeout(() => {
                                                    setShowCamera(true);
                                                }, 100);
                                            }}
                                            className="p-2 rounded-md border hover:bg-accent"
                                            title="Scan barcode dengan kamera"
                                        >
                                            <ScanBarcodeIcon className="w-5 h-5 text-muted-foreground" />
                                        </button>
                                    </div>
                                ) : (
                                    <div className="flex-1">
                                        <Input
                                            type="text"
                                            placeholder="Scan barcode"
                                            className="w-full transition-all"
                                            value={scanBarcode}
                                            ref={scanInputRef}
                                            onFocus={() => setActiveInput('barcode')}
                                            onChange={(e) => {
                                                const value = e.target.value;
                                                setScanBarcode(value);
                                                if (scanTimer.current) clearTimeout(scanTimer.current);
                                                scanTimer.current = setTimeout(async () => {
                                                    const code = value.trim();
                                                    if (code.length >= 8) {
                                                        try {
                                                            const response = await axios.get(route('apps.pos.search-by-barcode', {
                                                                barcode: code
                                                            }));
                                                            const product = response.data.product;
                                                            if (product) {
                                                                addToCart(product);
                                                                toast('Produk berhasil ditambahkan ke keranjang');
                                                            } else {
                                                                toast('Produk tidak ditemukan');
                                                            }
                                                        } catch (error) {
                                                            console.error('Barcode scan error:', error);
                                                            toast('Gagal mencari produk');
                                                        }
                                                        setScanBarcode('');
                                                        scanInputRef.current?.focus();
                                                    }
                                                }, 100);
                                            }}
                                        />

                                        {/* Tampilkan Kamera setelah input scan */}
                                        {showCamera && (
                                            <div className="relative mt-2 border p-2 rounded-md bg-background z-50">
                                                <div className="w-full h-[200px] overflow-hidden rounded-md">
                                                    <BarcodeScannerHtml5
                                                        onScanSuccess={async (code) => {
                                                            try {
                                                                const response = await axios.get(route('apps.pos.search-by-barcode', {
                                                                    barcode: code,
                                                                }));
                                                                const product = response.data.product;
                                                                if (product) {
                                                                    addToCart(product);
                                                                    toast('Produk berhasil ditambahkan ke keranjang');
                                                                } else {
                                                                    toast('Produk tidak ditemukan');
                                                                }
                                                            } catch (error) {
                                                                console.error('Barcode scan error:', error);
                                                                toast('Gagal mencari produk');
                                                            }
                                                        }}

                                                    />
                                                </div>
                                                <button
                                                    className="absolute top-1 right-1 text-sm px-2 py-1 bg-red-500 text-white rounded"
                                                    onClick={() => setShowCamera(false)}
                                                >
                                                    Tutup
                                                </button>
                                                <div className="text-sm text-muted-foreground text-center mt-2">
                                                    Arahkan kamera ke barcode produk
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                )}

                            </div>
                            <div className="mb-4 flex items-center justify-between gap-4 flex-col-reverse">
                                {/* Kategori di kiri */}
                                <div className="flex flex-wrap gap-2">
                                    <Button variant={!filters.category ? 'default' : 'outline'} size="sm" onClick={() => handleCategoryChange(null)}>
                                        Semua
                                    </Button>
                                    {categories.map((category, key) => (
                                        <Button
                                            key={key}
                                            variant={String(activeCategory) === String(category.id) ? 'default' : 'outline'}
                                            size="sm"
                                            onClick={() => handleCategoryChange(category.id)}
                                        >
                                            {category.name}
                                        </Button>
                                    ))}
                                </div>

                                {/* Tombol Paket di kanan */}
                                <div>
                                    <Button size="sm" variant={String(activeCategory) === String('package') ? 'default' : 'outline'} onClick={() => handleCategoryChange('package')}>
                                        Paket
                                    </Button>
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-2 overflow-y-auto max-h-[60vh]">
                                {data.items.map((item, key) => (
                                    <button
                                        disabled={item.stock <= 0}
                                        key={key}
                                        onClick={() => addToCart(item)}
                                        className={`relative h-36 cursor-pointer overflow-hidden rounded-lg border border-border bg-muted shadow-sm transition hover:shadow-md ${item.stock <= 0 ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
                                    >
                                        {/* Gambar Produk */}
                                        <img
                                            src={item.image}
                                            alt="No Image"
                                            className="h-full w-full object-cover"
                                        />

                                        {/* Harga di kanan atas */}
                                        <div className="absolute right-1 top-1 rounded-md bg-black/70 px-2 py-0.5 text-xs text-white shadow">
                                            <sup>Rp</sup> {String(priceItem(item))}
                                        </div>

                                        {/* Nama Produk di bawah */}
                                        <div className="absolute bottom-0 left-0 w-full bg-black/60 px-2 py-1 text-white">
                                            <p className="line-clamp-2 text-sm font-medium">{item.name}</p>
                                        </div>
                                    </button>
                                ))}
                            </div>
                            {/* Footer Pagination */}
                            <div className="mt-4 flex items-center justify-start lg:justify-center border-t pt-4 overflow-x-auto">
                                <Pagination links={items.links} />
                            </div>
                        </DialogContent>
                    </Dialog>

                    {/* Dialog Pembayaran */}
                    <Dialog open={data.modalPayment} onOpenChange={() => setData('modalPayment', !data.modalPayment)}>
                        <DialogContent className="w-full max-w-2xl">
                            <DialogHeader>
                                <div className="border-border flex flex-wrap items-center justify-between gap-4 rounded-lg border p-4">
                                    <div>
                                        <p className="text-muted-foreground text-sm">Total</p>
                                        <p className="text-foreground text-lg font-semibold">Rp {data.grandTotal}</p>
                                    </div>

                                    <div>
                                        <p className="text-muted-foreground text-sm">Uang Kembalian</p>
                                        <p className="text-foreground text-lg font-semibold">Rp {data.return}</p>
                                    </div>

                                    <div>
                                        <p className="text-sm text-yellow-600">Sisa Bayar</p>
                                        <p className="text-lg font-semibold text-yellow-700">Rp {data.remains}</p>
                                    </div>
                                </div>
                            </DialogHeader>

                            <div className="space-y-4">
                                {/* Tombol pilihan metode */}
                                <div>
                                    <Label>Metode Pembayaran</Label>
                                    <div className="mt-1 flex gap-2">
                                        <Button variant={data.selectedPaymentMethod === 'tunai' ? 'default' : 'outline'} onClick={() => setData('selectedPaymentMethod', 'tunai')}>
                                            Tunai
                                        </Button>
                                        <Button variant={data.selectedPaymentMethod === 'transfer' ? 'default' : 'outline'} onClick={() => setData('selectedPaymentMethod', 'transfer')}>
                                            Transfer
                                        </Button>
                                    </div>
                                </div>

                                {data.selectedPaymentMethod === 'transfer' && (
                                    <div className="space-y-3">
                                        <Label className="text-foreground block text-sm font-medium">Pilih Bank</Label>
                                        <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
                                            {banks.map((bank, i) => (
                                                <button
                                                    key={i}
                                                    onClick={() => setData('selectedBank', bank.bank_name)}
                                                    className={`w-full rounded-lg border px-4 py-3 text-left transition ${data.selectedBank === bank.bank_name
                                                        ? 'border-primary bg-primary/10 ring-primary ring-1'
                                                        : 'border-border bg-muted hover:bg-muted/70'
                                                        } `}
                                                >
                                                    <p className="text-foreground font-semibold uppercase">{bank.bank_name}</p>
                                                    <p className="text-muted-foreground mt-1 text-sm">
                                                        {bank.account_number} a/n {bank.account_name}
                                                    </p>
                                                </button>
                                            ))}
                                        </div>
                                        <div>
                                            <Label htmlFor="jumlahBayar">Jumlah Bayar</Label>
                                            <Input id="jumlahBayar" type="text" placeholder="Masukkan nominal" className="mt-1" value={data.pay} onChange={(e) => setData('pay', Number(e.target.value))} />
                                        </div>
                                    </div>
                                )}

                                {data.selectedPaymentMethod === 'tunai' &&
                                    <>
                                        {/* Input jumlah bayar */}
                                        <div>
                                            <Label htmlFor="jumlahBayar">Jumlah Bayar</Label>
                                            <Input id="jumlahBayar" type="text" placeholder="Masukkan nominal" className="mt-1" value={data.pay} onChange={(e) => setData('pay', Number(e.target.value))} />
                                        </div>

                                        {/* Tombol nominal bantuan */}
                                        <div className="mt-2 flex flex-wrap gap-2">
                                            {[10000, 20000, 50000, 100000].map((nominal) => (
                                                <Button
                                                    key={nominal}
                                                    type="button"
                                                    variant="outline"
                                                    onClick={() =>
                                                        setData((prev) => ({
                                                            ...prev,
                                                            pay: Number(prev.pay || 0) + nominal,
                                                        }))
                                                    }
                                                >
                                                    +Rp {nominal.toLocaleString()}
                                                </Button>
                                            ))}

                                        </div>
                                    </>
                                }
                                <form onSubmit={storeData}>
                                    <Button className="w-full" type='submit' disabled={processing || data.selectedPaymentMethod == ''}>Selesaikan Transaksi</Button>
                                </form>
                            </div>
                        </DialogContent>
                    </Dialog>

                    {/* Dialog customer */}
                    <Dialog open={data.modalCustomer} onOpenChange={() => setData('modalCustomer', !data.modalCustomer)}>
                        <DialogContent className="max-w-sm">
                            <DialogHeader>
                                <DialogTitle>Pilih Pelanggan</DialogTitle>
                                <DialogDescription>Silakan pilih pelanggan dari daftar berikut atau tambahkan baru.</DialogDescription>
                            </DialogHeader>

                            <div className="space-y-2">
                                <Button variant="outline" size="sm" className="w-full" onClick={() => setData('newModalCustomer', !data.newModalCustomer)}>
                                    + Tambah Pelanggan Baru
                                </Button>

                                <Input
                                    type="text"
                                    placeholder="Cari nama pelanggan..."
                                    className="border-border focus:ring-primary mb-2 rounded-md border px-3 py-2 focus:ring-2 focus:outline-none"
                                    value={data.searchCustomer}
                                    onChange={(e) => {
                                        setData('searchCustomer', e.target.value);
                                        debouncedGetListCustomer();
                                    }}
                                />
                                {data.customers.length > 0 &&
                                    <ul className="max-h-40 overflow-y-auto rounded-md border p-2">
                                        {data.customers.map((customer, key) => (
                                            <li key={key} className="hover:bg-muted cursor-pointer rounded p-2" onClick={() => handleSelectCustomer(customer)}>
                                                {customer.name} - {customer.phone}
                                            </li>
                                        ))}
                                    </ul>
                                }
                            </div>
                        </DialogContent>
                    </Dialog>

                    {/* Dialog new customer */}
                    <Dialog open={data.newModalCustomer} onOpenChange={() => setData('newModalCustomer', !data.newModalCustomer)}>
                        <DialogContent className="max-w-sm">
                            <DialogHeader>
                                <DialogTitle>Tambah Pelanggan</DialogTitle>
                                <DialogDescription>Form ini digunakan untuk menambahkan data pelanggan</DialogDescription>
                            </DialogHeader>
                            <form onSubmit={storeCustomer}>
                                <div className='mb-4 flex flex-col gap-2'>
                                    <Label htmlFor="harga">Nama<span className='text-rose-500'>*</span></Label>
                                    <Input type='text' value={data.newCust.name} onChange={(e) => setData('newCust.name', e.target.value)} placeholder='Masukan nama pelanggan' />
                                </div>
                                <div className='mb-4 flex flex-col gap-2'>
                                    <Label htmlFor="harga">Nomor Hp<span className='text-rose-500'>*</span></Label>
                                    <Input type="number" value={data.newCust.phone} onChange={(e) => setData('newCust.phone', e.target.value)} placeholder='Masukan nomor hp pelanggan' />
                                </div>
                                <div className='mb-4 flex flex-col gap-2'>
                                    <Label htmlFor="harga">Email</Label>
                                    <Input type='email' value={data.newCust.email} onChange={(e) => setData('newCust.email', e.target.value)} placeholder='Masukan email pelanggan' />
                                </div>
                                <div className='mb-4 flex flex-col gap-2'>
                                    <Label htmlFor="harga">Alamat</Label>
                                    <Textarea rows={5} value={data.newCust.address} onChange={(e) => setData('newCust.address', e.target.value)} placeholder='Masukan alamat pelanggan' />
                                </div>
                                <div className='flex'>
                                    <Button>Simpan</Button>
                                </div>
                            </form>
                        </DialogContent>
                    </Dialog>

                    {/* Dialog Item */}
                    <Dialog open={data.modalItem} onOpenChange={(open) => {
                        if (!open) {
                            setData((prev: any) => ({
                                ...prev,
                                modalItem: false,
                                selectedItem: {
                                    name: '',
                                    quantity: 0,
                                    price: 0,
                                    discount_type: '',
                                    discount: '',
                                    note: '',
                                    type: '',
                                    total_price: 0,
                                    stock: 0,
                                },
                            }));
                        } else {
                            setData('modalItem', true);
                        }
                    }}>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>Edit: {data.selectedItem.name}</DialogTitle>
                                <DialogDescription>
                                    Ubah harga, jumlah, diskon (auto/manual), atau tambahkan catatan.
                                </DialogDescription>
                            </DialogHeader>

                            <div className="mt-2 space-y-4">
                                {/* Harga Normal */}
                                <div>
                                    <Label htmlFor="harga">Harga Normal (Rp)</Label>
                                    <Input
                                        id="harga"
                                        type="number"
                                        value={data.selectedItem.price}
                                        onChange={(e) => setData('selectedItem.price', Number(e.target.value))}
                                        placeholder="Contoh: 15000"
                                    />
                                </div>

                                {/* Quantity */}
                                <div>
                                    <Label htmlFor="qty">Jumlah</Label>
                                    <Input
                                        id="qty"
                                        type="number"
                                        value={data.selectedItem.quantity}
                                        onChange={(e) => setData('selectedItem.quantity', Number(e.target.value))}
                                        placeholder="Contoh: 2"
                                    />
                                </div>

                                {/* Diskon */}
                                <div className="space-y-2">
                                    <Label>Diskon</Label>

                                    <div className="flex gap-2">
                                        <Select
                                            value={data.selectedItem.discount_type ?? ''}
                                            onValueChange={(value) => {
                                                if (value === 'auto') {
                                                    setData('selectedItem.discount_type', '');
                                                    setData('selectedItem.discount', '');
                                                } else {
                                                    setData('selectedItem.discount_type', value);
                                                }
                                            }}
                                        >
                                            <SelectTrigger className="w-36">
                                                <SelectValue placeholder="Auto (Promo)" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="auto">Auto (Promo)</SelectItem>
                                                <SelectItem value="nominal">Rp</SelectItem>
                                                <SelectItem value="percentage">%</SelectItem>
                                            </SelectContent>
                                        </Select>

                                        <Input
                                            type="number"
                                            value={data.selectedItem.discount ?? ''}
                                            onChange={(e) => setData('selectedItem.discount', e.target.value)}
                                            placeholder={
                                                data.selectedItem.discount_type === 'percentage'
                                                    ? 'Contoh: 10'
                                                    : 'Contoh: 2000'
                                            }
                                            className="flex-1"
                                            disabled={!data.selectedItem.discount_type}
                                        />
                                    </div>
                                    <p className="text-xs text-muted-foreground">
                                        Pilih <b>Auto (Promo)</b> untuk memakai diskon secara otomatis. Pilih <b>Rp</b> atau <b>%</b> untuk input manual.
                                    </p>
                                </div>

                                {/* Catatan */}
                                <div>
                                    <Label htmlFor="catatan">Catatan Produk</Label>
                                    <Input
                                        id="catatan"
                                        type="text"
                                        value={data.selectedItem.note ?? ''}
                                        onChange={(e) => setData('selectedItem.note', e.target.value)}
                                        placeholder="Contoh: Tidak pedas"
                                    />
                                </div>
                            </div>

                            <div className="mt-4 flex justify-end gap-2">
                                <Button variant="destructive" onClick={() => removeFromCart(data.selectedItem)}>
                                    Hapus Item
                                </Button>

                                <Button
                                    onClick={() => {
                                        const typeRaw = data.selectedItem.discount_type ?? '';
                                        const mappedType =
                                            typeRaw === 'percentage' ? 'percentage' : (typeRaw as '' | 'nominal' | 'percentage');

                                        handleUpdateCartItem(
                                            data.selectedItem,
                                            Number(data.selectedItem.quantity),
                                            String(data.selectedItem.price),
                                            mappedType,
                                            String(data.selectedItem.discount ?? ''),
                                            String(data.selectedItem.note ?? '')
                                        );
                                    }}
                                >
                                    Simpan
                                </Button>
                            </div>
                        </DialogContent>
                    </Dialog>

                    {/* Dialog Diskon */}
                    <Dialog open={data.modalDiscount} onOpenChange={() => setData('modalDiscount', !data.modalDiscount)}>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>Tambah Diskon</DialogTitle>
                            </DialogHeader>

                            <div className="space-y-4">
                                {/* Kode Diskon */}
                                <div className="space-y-1">
                                    <Label>Kode Diskon</Label>
                                    <Input placeholder="Contoh: HEMAT10" value={data.discounts.code} onChange={(e) => setData('discounts.code', e.target.value)} />
                                </div>

                                {/* Tipe dan Nilai Diskon */}
                                <div className="space-y-1">
                                    <Label>Diskon</Label>
                                    <div className="flex gap-2">
                                        <Select value={data.discounts.discount_type} onValueChange={(value) => setData('discounts.discount_type', value)}>
                                            <SelectTrigger className="w-28">
                                                <SelectValue placeholder="Tipe" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="nominal">Rp</SelectItem>
                                                <SelectItem value="persen">%</SelectItem>
                                            </SelectContent>
                                        </Select>

                                        <Input type="text" placeholder="Contoh: 2000 atau 10" className="flex-1" value={data.discounts.discount_amount} onChange={(e) => setData('discounts.discount_amount', Number(e.target.value))} />
                                    </div>
                                </div>
                                <div className="mt-4 flex justify-end gap-2">
                                    <Button onClick={() => applyDiscount()}>
                                        Simpan
                                    </Button>
                                </div>
                            </div>
                        </DialogContent>
                    </Dialog>

                    {/* Dialog Catatan */}
                    <Dialog open={data.modalNote} onOpenChange={() => setData('modalNote', !data.modalNote)}>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>Catatan untuk Pesanan</DialogTitle>
                            </DialogHeader>

                            <div className="space-y-4">
                                {/* No Referensi */}
                                <div>
                                    <Label htmlFor="noReferensi">No Referensi</Label>
                                    <Input id="noReferensi" placeholder="Contoh: INV-00123" value={data.notes.no_ref} onChange={(e) => setData('notes.no_ref', e.target.value)} />
                                </div>

                                {/* Sumber Transaksi */}
                                <div>
                                    <Label htmlFor="sumberTransaksi">Sumber Transaksi</Label>
                                    <Input id="sumberTransaksi" placeholder="Contoh: Tokopedia, Shopee, dll." value={data.notes.transaction_source} onChange={(e) => setData('notes.transaction_source', e.target.value)} />
                                </div>
                                {/* Catatan */}
                                <div>
                                    <Label htmlFor="catatan">Catatan</Label>
                                    <Textarea id="catatan" placeholder="Contoh: Tidak pedas, tambahkan sambal, dll." rows={4} value={data.notes.note} onChange={(e) => setData('notes.note', e.target.value)} />
                                </div>
                                <div className="mt-4 flex justify-end gap-2">
                                    <Button onClick={() => setData('modalNote', !data.modalNote)}>
                                        Simpan
                                    </Button>
                                </div>
                            </div>
                        </DialogContent>
                    </Dialog>

                    {/* Dialog Pengiriman */}
                    <Dialog open={data.modalDelivery} onOpenChange={() => setData('modalDelivery', !data.modalDelivery)}>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>Informasi Pengiriman</DialogTitle>
                            </DialogHeader>
                            <div className="space-y-2">
                                <Label htmlFor="ekspedisi">Nama Ekspedisi</Label>
                                <Input id="ekspedisi" placeholder="Contoh: JNE, J&T, Sicepat" value={data.delivery.name} onChange={(e) => setData('delivery.name', e.target.value)} />

                                <Label htmlFor="resi">No Resi</Label>
                                <Input id="resi" placeholder="Contoh: JP1234567890" value={data.delivery.no_resi} onChange={(e) => setData('delivery.no_resi', e.target.value)} />

                                <Label htmlFor="alamat">Alamat Pengiriman</Label>
                                <Textarea id="alamat" placeholder="Alamat lengkap pengiriman" rows={3} value={data.delivery.address} onChange={(e) => setData('delivery.address', e.target.value)} />

                                <Label htmlFor="catatan">Catatan untuk Kurir</Label>
                                <Input id="catatan" placeholder="Contoh: Lewat pintu belakang" value={data.delivery.note} onChange={(e) => setData('delivery.note', e.target.value)} />

                                {/* Status Pengiriman */}
                                <div>
                                    <Label htmlFor="status-pengiriman">Status Pengiriman</Label>
                                    <Select value={data.delivery.status} onValueChange={(e) => setData('delivery.status', e)}>
                                        <SelectTrigger id="status-pengiriman">
                                            <SelectValue placeholder="Pilih Status" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="pending">Belum Dikirim</SelectItem>
                                            <SelectItem value="shipped">Sedang Dikirim</SelectItem>
                                            <SelectItem value="delivered">Sampai Tujuan</SelectItem>
                                            <SelectItem value="cancelled">Dibatalkan</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div className="mt-4 flex justify-end gap-2">
                                    <Button onClick={() => setData('modalDelivery', !data.modalDelivery)}>
                                        Simpan
                                    </Button>
                                </div>
                            </div>
                        </DialogContent>
                    </Dialog>

                    {/* Dialog Pelayan */}
                    <Dialog open={data.modalCashier} onOpenChange={() => setData('modalCashier', !data.modalCashier)}>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>Pilih Pelayan</DialogTitle>
                            </DialogHeader>
                            <div className="mt-2 flex flex-col gap-2">
                                <Label htmlFor="pelayan">Nama Pelayan</Label>
                                <Select value={data.cashierId} onValueChange={(value) => setData('cashierId', value)}>
                                    <SelectTrigger id="pelayan">
                                        <SelectValue placeholder="Pilih pelayan" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {cashiers.map((option) => (
                                            <SelectItem key={option.id} value={option.id}>
                                                {option.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="mt-4 flex justify-end gap-2">
                                <Button onClick={() => setData('modalCashier', !data.modalCashier)}>
                                    Simpan
                                </Button>
                            </div>
                        </DialogContent>
                    </Dialog>

                    {/* Dialog after transaction*/}
                    <Dialog open={data.modalTransaction}>
                        <DialogContent>
                            <div className='flex flex-col items-center justify-center'>
                                <CheckCircle2 className='w-20 h-20 text-teal-500' />
                                <div className='font-bold mt-4 text-2xl'>Transaksi Berhasil !</div>
                                <div className='text-gray-500 mt-2'>Transaki telah berhasil proses</div>
                            </div>
                            <Card className='rounded-xl bg-secondary w-full mt-4'>
                                <CardContent>
                                    <div className='flex flex-col gap-4'>
                                        <div className='flex items-center justify-between gap-4'>
                                            <div className='font-semibold text-sm text-gray-400'>Np Transaksi</div>
                                            <div>{data.lastTransaction.invoice}</div>
                                        </div>
                                        <div className='flex items-center justify-between gap-4'>
                                            <div className='font-semibold text-sm text-gray-400'>Total Bayar</div>
                                            <div><sup>Rp</sup> {data.lastTransaction.pay}</div>
                                        </div>
                                        <div className='flex items-center justify-between gap-4'>
                                            <div className='font-semibold text-sm text-gray-400'>Kembalian</div>
                                            <div><sup>Rp</sup> {data.lastTransaction.return}</div>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>
                            <div className='flex flex-row gap-2 items-center mt-4'>
                                <BluetoothPrintButton tx={tx} paperWidth={32} />
                                <Button
                                    type="button"
                                    variant="outline"
                                    className="w-full"
                                    onClick={() => handleWindowsPrint(data.transactionPrint, settings)}
                                >
                                    <Printer className="size-4" /> Windows Print
                                </Button>
                            </div>
                            <div className='flex flex-row gap-2 items-center mt-4'>
                                <Button type='button' onClick={() => handleCloseTable()} variant={'default'} className='w-full' disabled={data.lastTransaction.transaction_type != 'dine_in'}>
                                    <Eraser className='size-4' /> Kosongkan Meja
                                </Button>
                                <Button variant={'secondary'} className='w-full' onClick={() => handleKitchen()}>
                                    <Check className='size-4' /> Selesai
                                </Button>
                            </div>
                        </DialogContent>
                    </Dialog>
                </PosLayout>
            }
        </>
    );
}
