import { Head, Link } from '@inertiajs/react';
import { useCallback } from 'react';
import type { Order } from '@/types/order';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Trash2, ShoppingBag, Printer, Bluetooth, Usb, Unplug, Plus, X, ArrowLeft } from 'lucide-react';
import { DataTable } from '@/components/data-table';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
    DropdownMenuRadioGroup,
    DropdownMenuRadioItem,
    DropdownMenuSub,
    DropdownMenuSubTrigger,
    DropdownMenuSubContent,
} from "@/components/ui/dropdown-menu"
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogMedia,
    AlertDialogTitle,
} from "@/components/ui/alert-dialog"

import * as orderRoutes from '@/routes/order';
import { useOrderIndex } from './hooks/use-order-index';
import { getColumns } from './partials/columns';
import { usePrinter } from '@/hooks/use-printer';
import { EscPosEncoder } from '@/lib/esc-pos-encoder';
import { format } from 'date-fns';
import { id } from 'date-fns/locale';
import { toast } from 'sonner';
import { DeleteConfirmation } from '@/components/modal/delete-confirmation';

export default function OrderIndex({ orders }: { orders: Order[] }) {
    const {
        isDeleteDialogOpen,
        isBulkDeleteDialogOpen,
        orderToDelete,
        rowsToDelete,
        rowSelection,
        setRowSelection,
        setRowsToDelete,
        setIsDeleteDialogOpen,
        setIsBulkDeleteDialogOpen,
        onDelete,
        confirmDelete,
        confirmBulkDelete,
    } = useOrderIndex();

    const {
        isConnected,
        name,
        connectBluetooth,
        connectUsb,
        disconnect,
        sendData,
        paperSize,
        setPaperSize
    } = usePrinter();

    const handlePrint = useCallback(async (order: Order) => {
        if (!isConnected) {
            toast.error('Hubungkan printer terlebih dahulu');
            return;
        }

        const width = paperSize === '58' ? 32 : 48;
        const line = '-'.repeat(width);

        const encoder = new EscPosEncoder();
        const result = encoder
            .initialize()
            .align(1)
            .size(1)
            .bold(true)
            .line('VN Grup')
            .size(0)
            .bold(false)
            .line(line)
            .align(0)
            .line(`No. Invoice : ${order.invoice_number}`)
            .line(`Tanggal     : ${format(new Date(order.created_at), 'dd MMMM yyyy HH:mm', { locale: id })}`)
            .line(`Pelanggan   : ${order.customer_name}`)
            .line(line);

        order.items?.forEach((item, index) => {
            if (index > 0) result.line();
            result.line(item.product?.name || 'Produk');
            const qtyPrice = `${item.qty} x ${item.price_formatted}`;
            const subtotal = item.total_formatted;
            const spaces = width - qtyPrice.length - subtotal.length;
            result.line(qtyPrice + ' '.repeat(Math.max(0, spaces)) + subtotal);
        });

        result.line(line);

        const discountAmount = Number(order.discount || 0);
        if (discountAmount > 0) {
            const discountLabel = 'Diskon:';
            const discountVal = `- Rp ${discountAmount.toLocaleString('id-ID')}`;
            const dSpaces = width - discountLabel.length - discountVal.length;
            result.line(discountLabel + ' '.repeat(Math.max(0, dSpaces)) + discountVal);
        }

        const totalLabel = 'TOTAL:';
        const totalVal = order.total_formatted;
        const tSpaces = width - totalLabel.length - totalVal.length;
        result.bold(true).line(totalLabel + ' '.repeat(Math.max(0, tSpaces)) + totalVal).bold(false);

        result
            .line(line)
            .align(1)
            .feed(1)
            .line('Terima Kasih')
            .line('Selamat Belanja Kembali')
            .feed(1)
            .cut();

        await sendData(result.encode());
    }, [isConnected, sendData, paperSize]);

    const columns = getColumns({ onDelete, onPrint: handlePrint });

    return (
        <div className="flex flex-col gap-6 p-6">
            <Head title="Pesanan" />

            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight text-foreground">Pesanan</h1>
                </div>
                <div className="flex items-center gap-2">
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant={isConnected ? "outline" : "secondary"} className="gap-2">
                                <Printer className="size-4" />
                                {isConnected ? name : 'Hubungkan Printer'}
                                {isConnected && <div className="size-2 rounded-full bg-green-500 animate-pulse" />}
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-56">
                            <DropdownMenuLabel>Koneksi Printer</DropdownMenuLabel>
                            <DropdownMenuSeparator />
                            {isConnected ? (
                                <>
                                    <DropdownMenuSub>
                                        <DropdownMenuSubTrigger>
                                            Ukuran Kertas: {paperSize}mm
                                        </DropdownMenuSubTrigger>
                                        <DropdownMenuSubContent>
                                            <DropdownMenuRadioGroup value={paperSize} onValueChange={(v) => setPaperSize(v as any)}>
                                                <DropdownMenuRadioItem value="58">58mm</DropdownMenuRadioItem>
                                                <DropdownMenuRadioItem value="80">80mm</DropdownMenuRadioItem>
                                            </DropdownMenuRadioGroup>
                                        </DropdownMenuSubContent>
                                    </DropdownMenuSub>
                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem onClick={disconnect} variant="destructive">
                                        <Unplug className="mr-2 size-4" />
                                        Putus Koneksi
                                    </DropdownMenuItem>
                                </>
                            ) : (
                                <>
                                    <DropdownMenuItem onClick={connectBluetooth}>
                                        <Bluetooth className="mr-2 size-4" />
                                        Bluetooth
                                    </DropdownMenuItem>
                                    <DropdownMenuItem onClick={connectUsb}>
                                        <Usb className="mr-2 size-4" />
                                        USB
                                    </DropdownMenuItem>
                                </>
                            )}
                        </DropdownMenuContent>
                    </DropdownMenu>

                    <Link href={orderRoutes.create().url}>
                        <Button className="gap-2">
                            <Plus className="size-4" />
                            Tambah
                        </Button>
                    </Link>
                </div>
            </div>

            <Card className="overflow-hidden border-none shadow-lg bg-card/50 backdrop-blur-sm p-5">
                <CardContent className="p-0">
                    <DataTable
                        columns={columns}
                        data={orders}
                        rowSelection={rowSelection}
                        onRowSelectionChange={setRowSelection}
                        bulkActions={[
                            {
                                label: 'Hapus Terpilih',
                                onClick: (rows) => {
                                    setRowsToDelete(rows);
                                    setIsBulkDeleteDialogOpen(true);
                                },
                                icon: Trash2,
                                variant: 'destructive'
                            },
                        ]}
                    />
                </CardContent>
            </Card>

            {/* Single Delete Confirmation */}
            <DeleteConfirmation
                isOpen={isDeleteDialogOpen}
                onOpenChange={setIsDeleteDialogOpen}
                title="Hapus pesanan?"
                description={
                    <>
                        Tindakan ini tidak dapat dibatalkan. Pesanan <strong>{orderToDelete?.invoice_number}</strong> akan dihapus secara permanen dan stok akan dikembalikan.
                    </>
                }
                onDelete={confirmDelete}
            />

            {/* Bulk Delete Confirmation */}
            <DeleteConfirmation
                isOpen={isBulkDeleteDialogOpen}
                onOpenChange={setIsBulkDeleteDialogOpen}
                title={`Hapus ${rowsToDelete.length} pesanan?`}
                description={
                    <>
                        Tindakan ini tidak dapat dibatalkan. <strong>{rowsToDelete.length}</strong> item yang terpilih akan dihapus secara permanen.
                    </>
                }
                onDelete={confirmBulkDelete}
            />
        </div>
    );
}

OrderIndex.layout = {
    breadcrumbs: [
        {
            title: 'Kelola',
        }
    ],
};
