import { Head, useForm } from "@inertiajs/react"
import AppLayout from "@/layouts/app-layout"
import type { BreadcrumbItem } from "@/types"
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Toggle } from "@/components/ui/toggle"
import { useRef } from "react"

type Props = {
    settings: {
        label_width: number
        label_height: number
        margin_top: number
        margin_left: number
        show_product_name: boolean
        show_price: boolean
        show_variant: boolean
    }
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: "Settings", href: "/apps/settings" },
    { title: "Barcode Label Settings", href: "#" },
]

export default function BarcodeLabelSettings({ settings }: Props) {

    const { data, setData, post, processing } = useForm({
        ...settings,
        media_type: settings.media_type ?? "roll",
        labels_per_row: settings.labels_per_row ?? 1,
        labels_per_sheet: settings.labels_per_sheet ?? 30,
        row_spacing: settings.row_spacing ?? 3,
        column_spacing: settings.column_spacing ?? 3,
        text_size_name: settings.text_size_name ?? 10,
        text_size_variant: settings.text_size_variant ?? 9,
        text_size_price: settings.text_size_price ?? 11,

    })

    const handleSubmit = (e: any) => {
        e.preventDefault()
        post("/settings/barcode-label") // route-mu
    }

    const previewCount =
        data.media_type === "lembar"
            ? data.labels_per_sheet
            : 5; // default 5 untuk roll/traktor

    const columns =
        data.media_type === "lembar"
            ? Math.ceil(Math.sqrt(previewCount))
            : data.labels_per_row;

    const previewRef = useRef<HTMLDivElement>(null)

    const handlePrint = () => {
    if (!previewRef.current) return;

    const printContent = previewRef.current.innerHTML;
    const printWindow = window.open("", "", "width=800,height=600");

    if (!printWindow) return;

    printWindow.document.open();
    printWindow.document.write(`
        <html>
            <head>
                <title>Cetak Label</title>
                <style>
                    @page { margin: 0; }

                    body {
                        padding: 0;
                        margin: 0;
                        font-family: sans-serif;
                    }

                    /* GRID untuk posisi label */
                    .label-grid {
                        display: grid;
                        grid-template-columns: repeat(${columns}, ${data.label_width}mm);
                        gap: ${data.row_spacing}mm ${data.column_spacing}mm;
                        padding-top: ${data.margin_top}mm;
                        padding-left: ${data.margin_left}mm;
                    }

                    /* KOTAK LABEL */
                    .label-item {
                        width: ${data.label_width}mm;
                        height: ${data.label_height}mm;
                        box-sizing: border-box;
                        border: 1px solid #000 !important;
                        padding: 2mm;
                        display: flex;
                        flex-direction: column;
                        justify-content: space-between;
                        font-size: 10px;
                    }

                    .text-center { text-align: center; }
                    .fw-bold { font-weight: bold; }
                </style>
            </head>

            <body>
                <div class="label-grid">
                    ${[...Array(previewCount)]
                        .map(() => {
                            return `
                                <div class="label-item">
                                    ${
                                        data.show_product_name
                                            ? `<div style="font-size:${data.text_size_name}mm">
                                                Nama Produk
                                            </div>`
                                            : ""
                                    }

                                    ${
                                        data.show_variant
                                            ? `<div style="font-size:${data.text_size_variant}mm">
                                                Varian: Pedas
                                            </div>`
                                            : ""
                                    }

                                    <div class="text-center" style="opacity:0.8">
                                        [ BARCODE ]
                                    </div>

                                    ${
                                        data.show_price
                                            ? `<div class="fw-bold" style="font-size:${data.text_size_price}mm">
                                                Rp 12.000
                                            </div>`
                                            : ""
                                    }
                                </div>
                            `
                        })
                        .join("")}
                </div>
            </body>
        </html>
    `);

    printWindow.document.close();

    printWindow.focus();
    setTimeout(() => {
        printWindow.print();
        printWindow.close();
    }, 300);
};



    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Barcode Label Settings" />

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">

                {/* FORM PENGATURAN */}
                <Card>
                    <CardHeader>
                        <CardTitle>Pengaturan Label Barcode</CardTitle>
                    </CardHeader>

                    <CardContent>
                        <form className="space-y-4" onSubmit={handleSubmit}>

                            <div>
                                <Label>Jenis Media</Label>
                                <select
                                    className="border rounded px-3 py-2 w-full bg-background text-foreground"
                                    value={data.media_type}
                                    onChange={(e) => setData("media_type", e.target.value)}
                                >
                                    <option value="roll">Roll</option>
                                    <option value="traktor">Traktor</option>
                                    <option value="lembar">Lembaran</option>
                                </select>
                            </div>

                            {/* Hanya tampil untuk roll & traktor */}
                            {data.media_type !== "lembar" && (
                                <div>
                                    <Label>Stiker per Baris</Label>
                                    <Input
                                        type="number"
                                        value={data.labels_per_row}
                                        onChange={(e) => setData("labels_per_row", e.target.value)}
                                    />
                                </div>
                            )}

                            {/* Hanya tampil untuk lembar */}
                            {data.media_type === "lembar" && (
                                <div>
                                    <Label>Jumlah Stiker per Lembar</Label>
                                    <Input
                                        type="number"
                                        value={data.labels_per_sheet}
                                        onChange={(e) => setData("labels_per_sheet", e.target.value)}
                                    />
                                </div>
                            )}


                            <div>
                                <Label>Lebar Label (mm)</Label>
                                <Input
                                    type="number"
                                    value={data.label_width}
                                    onChange={(e) => setData("label_width", e.target.value)}
                                />
                            </div>

                            <div>
                                <Label>Tinggi Label (mm)</Label>
                                <Input
                                    type="number"
                                    value={data.label_height}
                                    onChange={(e) => setData("label_height", e.target.value)}
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-2">
                                <div>
                                    <Label>Jarak Antar Dua Baris (Row Spacing)</Label>
                                    <Input
                                        type="number"
                                        value={data.row_spacing}
                                        onChange={(e) => setData("row_spacing", e.target.value)}
                                    />
                                </div>

                                <div>
                                    <Label>Jarak Antar Dua Kolom (Column Spacing)</Label>
                                    <Input
                                        type="number"
                                        value={data.column_spacing}
                                        onChange={(e) => setData("column_spacing", e.target.value)}
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-2">
                                <div>
                                    <Label>Margin Atas (mm)</Label>
                                    <Input
                                        type="number"
                                        value={data.margin_top}
                                        onChange={(e) => setData("margin_top", e.target.value)}
                                    />
                                </div>

                                <div>
                                    <Label>Margin Kiri (mm)</Label>
                                    <Input
                                        type="number"
                                        value={data.margin_left}
                                        onChange={(e) => setData("margin_left", e.target.value)}
                                    />
                                </div>
                            </div>

                            {/* Toggle Show Product Name */}
                            <div className="flex items-center justify-between py-2">
                                <Label className="text-foreground">Tampilkan Nama Produk</Label>
                                <Toggle
                                    pressed={data.show_product_name}
                                    onPressedChange={(value) => setData("show_product_name", value)}
                                    className={`
            px-4 py-1 rounded-lg border border-border transition-all
            ${data.show_product_name ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}
        `}
                                >
                                    {data.show_product_name ? "On" : "Off"}
                                </Toggle>
                            </div>

                            <div className="flex items-center justify-between py-2">
                                <Label className="text-foreground">Tampilkan Variasi</Label>
                                <Toggle
                                    pressed={data.show_variant}
                                    onPressedChange={(value) => setData("show_variant", value)}
                                    className={`
            px-4 py-1 rounded-lg border border-border transition-all
            ${data.show_variant ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}
        `}
                                >
                                    {data.show_variant ? "On" : "Off"}
                                </Toggle>
                            </div>

                            <div className="flex items-center justify-between py-2">
                                <Label className="text-foreground">Tampilkan Harga</Label>
                                <Toggle
                                    pressed={data.show_price}
                                    onPressedChange={(value) => setData("show_price", value)}
                                    className={`
            px-4 py-1 rounded-lg border border-border transition-all
            ${data.show_price ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}
        `}
                                >
                                    {data.show_price ? "On" : "Off"}
                                </Toggle>
                            </div>

                            <div className="grid grid-cols-3 gap-2">
                                <div>
                                    <Label>Ukuran Nama (px)</Label>
                                    <Input
                                        type="number"
                                        value={data.text_size_name}
                                        onChange={(e) => setData("text_size_name", e.target.value)}
                                    />
                                </div>

                                <div>
                                    <Label>Ukuran Variasi (px)</Label>
                                    <Input
                                        type="number"
                                        value={data.text_size_variant}
                                        onChange={(e) => setData("text_size_variant", e.target.value)}
                                    />
                                </div>

                                <div>
                                    <Label>Ukuran Harga (px)</Label>
                                    <Input
                                        type="number"
                                        value={data.text_size_price}
                                        onChange={(e) => setData("text_size_price", e.target.value)}
                                    />
                                </div>
                            </div>



                            <Button disabled={processing} className="w-full">
                                Simpan Pengaturan
                            </Button>
                        </form>
                    </CardContent>
                </Card>

                {/* PREVIEW */}
                <Card>
                    <CardHeader className="flex items-center justify-between">
                        <CardTitle>Preview Label</CardTitle>

                        <Button variant="outline" onClick={handlePrint}>
                            Cetak Preview
                        </Button>
                    </CardHeader>


                    <CardContent>
                        <div
                            ref={previewRef}
                            className="p-4 border rounded bg-card text-card-foreground"
                        >

                            <div
                                style={{
                                    display: "grid",
                                    gridTemplateColumns: `repeat(${columns}, ${data.label_width}mm)`,
gap: `${data.row_spacing}mm ${data.column_spacing}mm`,
paddingTop: `${data.margin_top}mm`,
paddingLeft: `${data.margin_left}mm`,

                                }}
                            >

                                {[...Array(previewCount)].map((_, i) => (
                                    <div
                                        key={i}
                                        style={{
                                            width: `${data.label_width}mm`,
                                            height: `${data.label_height}mm`,
                                            padding: "4px",
                                        }}
                                        className="text-xs border border-border rounded bg-background text-foreground flex flex-col"
                                    >
                                        {data.show_product_name && (
                                            <div
                                                className="truncate"
                                                style={{ fontSize: `${data.text_size_name}mm` }}
                                            >
                                                Nama Produk {i}
                                            </div>
                                        )}

                                        {data.show_variant && (
                                            <div style={{ fontSize: `${data.text_size_variant}mm` }}>
                                                Varian: Pedas {i}
                                            </div>
                                        )}

                                        <div
                                            className="mt-auto mb-1 text-center opacity-80"
                                            style={{ fontSize: `${data.text_size_variant}mm` }}
                                        >
                                            [ BARCODE ]
                                        </div>

                                        {data.show_price && (
                                            <div
                                                className="font-semibold"
                                                style={{ fontSize: `${data.text_size_price}mm` }}
                                            >
                                                Rp 12.000
                                            </div>
                                        )}

                                    </div>
                                ))}

                            </div>

                        </div>
                    </CardContent>
                </Card>



            </div>
        </AppLayout>
    )
}
