import React from "react";
import { useForm } from "@inertiajs/react";
import {
    Loader2,
    Plus,
    Trash2,
    ShoppingBag,
    User,
    UserCheck,
    Calendar,
    MapPin,
    Receipt,
    FileText,
    Sparkles,
    AlertCircle,
    X,
} from "lucide-react";

import {
    Dialog,
    DialogContent,
    DialogTitle,
    DialogDescription,
    DialogClose,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";

interface Option {
    id: number | string;
    name: string;
    price?: number;
}

interface OrderItem {
    product_id: string;
    qty: number;
    price: number;
    discount: number;
}

interface CreateOrderDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    customers?: Option[];
    salesList?: Option[];
    products?: Option[];
}

export function CreateOrderDialog({
    open,
    onOpenChange,
    customers = [],
    salesList = [],
    products = [],
}: CreateOrderDialogProps) {
    const today = new Date().toISOString().split("T")[0];

    const { data, setData, post, transform, processing, errors, reset } =
        useForm({
            customer_id: "",
            sales_id: "",
            order_date: today,
            visit_id: "",
            items: [
                { product_id: "", qty: 1, price: 0, discount: 0 },
            ] as OrderItem[],
            notes: "",
            order_discount: 0,
            tax: 0,
        });

    const handleAddItem = () => {
        setData("items", [
            ...data.items,
            { product_id: "", qty: 1, price: 0, discount: 0 },
        ]);
    };

    const handleRemoveItem = (index: number) => {
        if (data.items.length === 1) return;
        const newItems = data.items.filter((_, i) => i !== index);
        setData("items", newItems);
    };

    const handleItemChange = (
        index: number,
        field: keyof OrderItem,
        value: string | number,
    ) => {
        const newItems = [...data.items];

        if (field === "product_id") {
            const selectedProduct = products.find(
                (p) => String(p.id) === String(value),
            );
            newItems[index] = {
                ...newItems[index],
                product_id: String(value),
                price: Number(selectedProduct?.price ?? newItems[index].price),
            };
        } else {
            const numValue =
                typeof value === "string" ? parseFloat(value) || 0 : value;
            newItems[index] = {
                ...newItems[index],
                [field]: numValue,
            };
        }

        setData("items", newItems);
    };

    const subtotal = data.items.reduce((acc, item) => {
        const itemTotal =
            (Number(item.qty) || 0) * (Number(item.price) || 0) -
            (Number(item.discount) || 0);
        return acc + Math.max(0, itemTotal);
    }, 0);

    const total = Math.max(
        0,
        subtotal - (Number(data.order_discount) || 0) + (Number(data.tax) || 0),
    );

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        transform((raw) => ({
            ...raw,
            visit_id: raw.visit_id ? Number(raw.visit_id) : null,
            customer_id: raw.customer_id ? Number(raw.customer_id) : "",
            sales_id: raw.sales_id ? Number(raw.sales_id) : "",
            items: raw.items.map((item) => ({
                product_id: Number(item.product_id),
                qty: Number(item.qty),
                unit_price: Number(item.price),
                price: Number(item.price),
                discount: Number(item.discount),
            })),
        }));

        post("/crm/orders", {
            onSuccess: () => {
                reset();
                onOpenChange(false);
            },
        });
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            {/* Modal Container Solid dengan CSS selector [&>button] untuk menyembunyikan X bawaan jika ada */}
            <DialogContent className="w-[95vw] sm:max-w-5xl md:max-w-6xl rounded-3xl border border-border bg-muted p-0 shadow-2xl max-h-[90vh] overflow-hidden flex flex-col [&>button]:hidden">
                {/* Header Banner */}
                <div className="bg-linear-to-r from-slate-900 via-indigo-950 to-slate-900 px-6 py-5 text-white shrink-0 border-b border-slate-800 flex items-center justify-between gap-4">
                    <div className="flex items-center gap-3">
                        <div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-indigo-500/20 text-indigo-300 ring-1 ring-indigo-400/30">
                            <ShoppingBag className="h-5 w-5" />
                        </div>
                        <div>
                            <div className="flex items-center gap-2">
                                <DialogTitle className="text-xl font-bold tracking-tight text-white">
                                    Buat Order Penjualan
                                </DialogTitle>
                                <span className="inline-flex items-center gap-1 rounded-full bg-indigo-500/20 px-2.5 py-0.5 text-[10px] font-semibold text-indigo-300 ring-1 ring-inset ring-indigo-400/30">
                                    <Sparkles className="h-3 w-3" />
                                    Sales Order
                                </span>
                            </div>
                            <DialogDescription className="text-xs text-muted-foreground/60 mt-0.5">
                                Kelola transaksi penjualan baru, tentukan item,
                                dan atur penyesuaian harga.
                            </DialogDescription>
                        </div>
                    </div>

                    {/* Area Kanan Header: Total & Tombol Close */}
                    <div className="flex items-center gap-3">
                        <div className="hidden sm:flex flex-col items-end rounded-2xl bg-card/10 px-4 py-1.5 border border-white/10 backdrop-blur-md">
                            <span className="text-[10px] uppercase tracking-wider text-muted-foreground/60 font-semibold">
                                Est. Total
                            </span>
                            <span className="text-lg font-black text-indigo-300">
                                Rp {total.toLocaleString("id-ID")}
                            </span>
                        </div>

                        {/* Tombol Close Kustom Putih */}
                        <DialogClose className="rounded-full bg-card/10 p-2 text-muted-foreground/60 hover:bg-card/20 hover:text-white transition-all focus:outline-none ring-1 ring-white/10">
                            <X className="h-4 w-4" />
                            <span className="sr-only">Tutup</span>
                        </DialogClose>
                    </div>
                </div>

                {/* Form Body Scrollable */}
                <form
                    id="order-form"
                    onSubmit={handleSubmit}
                    className="p-6 space-y-6 overflow-y-auto flex-1 bg-muted"
                >
                    {/* Alert Validation Errors */}
                    {Object.keys(errors).length > 0 && (
                        <div className="rounded-2xl bg-red-50 p-4 border border-red-200 text-xs text-red-700 shadow-sm flex gap-3 items-start">
                            <AlertCircle className="w-5 h-5 text-red-500 shrink-0 mt-0.5" />
                            <div className="space-y-1">
                                <strong className="font-semibold text-red-800">
                                    Terdapat kesalahan pengisian data:
                                </strong>
                                <ul className="list-disc ml-4 space-y-0.5 text-red-600">
                                    {Object.entries(errors).map(
                                        ([key, err]) => (
                                            <li key={key}>{err}</li>
                                        ),
                                    )}
                                </ul>
                            </div>
                        </div>
                    )}

                    {/* Section 1: Informasi Utama */}
                    <div className="rounded-2xl border border-border/80 bg-card p-5 shadow-sm space-y-4">
                        <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-muted-foreground border-b border-slate-100 pb-2">
                            <User className="w-4 h-4 text-indigo-600" />
                            <span>Informasi Utama Transaksi</span>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
                            {/* Customer */}
                            <div className="space-y-1.5">
                                <Label className="text-xs font-semibold text-foreground/80 flex items-center gap-1.5">
                                    Customer{" "}
                                    <span className="text-red-500">*</span>
                                </Label>
                                <Select
                                    value={data.customer_id}
                                    onValueChange={(val) =>
                                        setData("customer_id", val)
                                    }
                                >
                                    <SelectTrigger className="bg-muted/50 rounded-xl border-border hover:bg-muted focus:bg-card text-xs font-medium h-9">
                                        <SelectValue placeholder="Pilih Customer..." />
                                    </SelectTrigger>
                                    <SelectContent className="rounded-xl">
                                        {customers.map((c) => (
                                            <SelectItem
                                                key={c.id}
                                                value={String(c.id)}
                                                className="text-xs"
                                            >
                                                {c.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            {/* Sales */}
                            <div className="space-y-1.5">
                                <Label className="text-xs font-semibold text-foreground/80 flex items-center gap-1.5">
                                    Sales Representative{" "}
                                    <span className="text-red-500">*</span>
                                </Label>
                                <Select
                                    value={data.sales_id}
                                    onValueChange={(val) =>
                                        setData("sales_id", val)
                                    }
                                >
                                    <SelectTrigger className="bg-muted/50 rounded-xl border-border hover:bg-muted focus:bg-card text-xs font-medium h-9">
                                        <SelectValue placeholder="Pilih Sales..." />
                                    </SelectTrigger>
                                    <SelectContent className="rounded-xl">
                                        {salesList.map((s) => (
                                            <SelectItem
                                                key={s.id}
                                                value={String(s.id)}
                                                className="text-xs"
                                            >
                                                {s.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            {/* Tanggal */}
                            <div className="space-y-1.5">
                                <Label className="text-xs font-semibold text-foreground/80 flex items-center gap-1.5">
                                    Tanggal Transaksi
                                </Label>
                                <Input
                                    type="date"
                                    value={data.order_date}
                                    onChange={(e) =>
                                        setData("order_date", e.target.value)
                                    }
                                    className="bg-muted/50 rounded-xl border-border text-xs font-medium focus:bg-card h-9"
                                />
                            </div>

                            {/* Visit ID */}
                            <div className="space-y-1.5">
                                <Label className="text-xs font-semibold text-foreground/80 flex items-center gap-1.5">
                                    Visit ID{" "}
                                    <span className="text-muted-foreground/80 font-normal">
                                        (Opsional)
                                    </span>
                                </Label>
                                <Input
                                    placeholder="Contoh: VST-1029"
                                    value={data.visit_id}
                                    onChange={(e) =>
                                        setData("visit_id", e.target.value)
                                    }
                                    className="bg-muted/50 rounded-xl border-border text-xs font-medium focus:bg-card h-9"
                                />
                            </div>
                        </div>
                    </div>

                    {/* Section 2: Items Table */}
                    <div className="rounded-2xl border border-border/80 bg-card p-5 shadow-sm space-y-4">
                        <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                            <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-muted-foreground">
                                <ShoppingBag className="w-4 h-4 text-indigo-600" />
                                <span>Daftar Produk / Item Order</span>
                            </div>
                            <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={handleAddItem}
                                className="rounded-xl border-indigo-200 text-indigo-600 hover:bg-indigo-50 font-semibold text-xs h-8 px-3"
                            >
                                <Plus className="mr-1.5 h-3.5 w-3.5" />
                                Tambah Item
                            </Button>
                        </div>

                        {/* Header Bar */}
                        <div className="hidden md:grid grid-cols-12 gap-3 text-[11px] font-bold uppercase tracking-wider text-muted-foreground bg-muted/80 p-2.5 rounded-xl border border-border/60">
                            <div className="col-span-4 px-1">Produk</div>
                            <div className="col-span-2 text-center">
                                Jumlah (Qty)
                            </div>
                            <div className="col-span-2 text-right">
                                Harga Satuan (Rp)
                            </div>
                            <div className="col-span-2 text-right">
                                Diskon (Rp)
                            </div>
                            <div className="col-span-2 text-right pr-2">
                                Subtotal Baris
                            </div>
                        </div>

                        {/* Item Rows */}
                        <div className="space-y-2.5">
                            {data.items.map((item, index) => {
                                const rowSubtotal = Math.max(
                                    0,
                                    (Number(item.qty) || 0) *
                                        (Number(item.price) || 0) -
                                        (Number(item.discount) || 0),
                                );

                                return (
                                    <div
                                        key={index}
                                        className="grid grid-cols-12 gap-3 items-center bg-muted/50 hover:bg-muted/50 p-2.5 rounded-xl border border-border/80 transition-all"
                                    >
                                        <div className="col-span-12 md:col-span-4">
                                            <Select
                                                value={item.product_id}
                                                onValueChange={(val) =>
                                                    handleItemChange(
                                                        index,
                                                        "product_id",
                                                        val,
                                                    )
                                                }
                                            >
                                                <SelectTrigger className="bg-card rounded-xl border-border text-xs font-medium h-9">
                                                    <SelectValue placeholder="Pilih Produk..." />
                                                </SelectTrigger>
                                                <SelectContent className="rounded-xl">
                                                    {products.map((p) => (
                                                        <SelectItem
                                                            key={p.id}
                                                            value={String(p.id)}
                                                            className="text-xs"
                                                        >
                                                            {p.name}
                                                        </SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                        </div>

                                        <div className="col-span-4 md:col-span-2">
                                            <Input
                                                type="number"
                                                min="1"
                                                value={item.qty}
                                                onChange={(e) =>
                                                    handleItemChange(
                                                        index,
                                                        "qty",
                                                        e.target.value,
                                                    )
                                                }
                                                className="bg-card rounded-xl border-border text-center text-xs font-medium h-9"
                                            />
                                        </div>

                                        <div className="col-span-4 md:col-span-2">
                                            <Input
                                                type="number"
                                                min="0"
                                                value={item.price}
                                                onChange={(e) =>
                                                    handleItemChange(
                                                        index,
                                                        "price",
                                                        e.target.value,
                                                    )
                                                }
                                                className="bg-card rounded-xl border-border text-right text-xs font-medium h-9"
                                            />
                                        </div>

                                        <div className="col-span-3 md:col-span-2">
                                            <Input
                                                type="number"
                                                min="0"
                                                value={item.discount}
                                                onChange={(e) =>
                                                    handleItemChange(
                                                        index,
                                                        "discount",
                                                        e.target.value,
                                                    )
                                                }
                                                className="bg-card rounded-xl border-border text-right text-xs font-medium h-9"
                                            />
                                        </div>

                                        <div className="col-span-12 md:col-span-2 flex items-center justify-between md:justify-end gap-2 pt-2 md:pt-0 border-t md:border-t-0 border-border/50">
                                            <span className="text-xs font-bold text-foreground md:hidden">
                                                Subtotal:
                                            </span>
                                            <span className="text-xs font-bold text-foreground tracking-tight">
                                                Rp{" "}
                                                {rowSubtotal.toLocaleString(
                                                    "id-ID",
                                                )}
                                            </span>
                                            <Button
                                                type="button"
                                                variant="ghost"
                                                size="sm"
                                                onClick={() =>
                                                    handleRemoveItem(index)
                                                }
                                                disabled={
                                                    data.items.length === 1
                                                }
                                                className="h-8 w-8 p-0 text-muted-foreground/80 hover:text-red-600 hover:bg-red-50 rounded-lg disabled:opacity-30 transition-colors ml-1"
                                            >
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>

                    {/* Section 3: Notes & Financial Calculation */}
                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-5">
                        <div className="lg:col-span-7 rounded-2xl border border-border/80 bg-card p-5 shadow-sm flex flex-col justify-between space-y-3">
                            <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-muted-foreground border-b border-slate-100 pb-2">
                                <FileText className="w-4 h-4 text-indigo-600" />
                                <span>Catatan / Keterangan Order</span>
                            </div>
                            <Textarea
                                rows={4}
                                placeholder="Tambahkan instruksi pengiriman, syarat pembayaran khusus, atau catatan internal CRM..."
                                value={data.notes}
                                onChange={(e) =>
                                    setData("notes", e.target.value)
                                }
                                className="bg-muted/50 rounded-xl border-border resize-none text-xs focus:bg-card flex-1"
                            />
                        </div>

                        <div className="lg:col-span-5 rounded-2xl border border-border/80 bg-card p-5 shadow-sm space-y-3">
                            <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-muted-foreground border-b border-slate-100 pb-2">
                                <Receipt className="w-4 h-4 text-indigo-600" />
                                <span>Rincian Pembayaran</span>
                            </div>

                            <div className="space-y-2 text-xs font-medium">
                                <div className="flex justify-between items-center text-muted-foreground">
                                    <span>Subtotal Item</span>
                                    <span className="font-semibold text-foreground">
                                        Rp {subtotal.toLocaleString("id-ID")}
                                    </span>
                                </div>

                                <div className="flex justify-between items-center gap-4">
                                    <span className="text-muted-foreground shrink-0">
                                        Diskon Nota (Rp)
                                    </span>
                                    <Input
                                        type="number"
                                        min="0"
                                        value={data.order_discount}
                                        onChange={(e) =>
                                            setData(
                                                "order_discount",
                                                parseFloat(e.target.value) || 0,
                                            )
                                        }
                                        className="h-8 w-32 bg-muted/50 rounded-lg border-border text-right text-xs font-medium focus:bg-card"
                                    />
                                </div>

                                <div className="flex justify-between items-center gap-4">
                                    <span className="text-muted-foreground shrink-0">
                                        Pajak (Rp)
                                    </span>
                                    <Input
                                        type="number"
                                        min="0"
                                        value={data.tax}
                                        onChange={(e) =>
                                            setData(
                                                "tax",
                                                parseFloat(e.target.value) || 0,
                                            )
                                        }
                                        className="h-8 w-32 bg-muted/50 rounded-lg border-border text-right text-xs font-medium focus:bg-card"
                                    />
                                </div>
                            </div>

                            <div className="pt-3 border-t border-border flex justify-between items-center bg-slate-900 text-white p-3.5 rounded-xl shadow-sm">
                                <div className="flex flex-col">
                                    <span className="text-[10px] uppercase tracking-wider text-muted-foreground/80 font-semibold">
                                        Total Tagihan
                                    </span>
                                    <span className="text-[10px] text-indigo-300">
                                        Termasuk pajak & diskon
                                    </span>
                                </div>
                                <span className="text-lg font-black text-indigo-300 tracking-tight">
                                    Rp {total.toLocaleString("id-ID")}
                                </span>
                            </div>
                        </div>
                    </div>
                </form>

                {/* Footer Modal Sticky Solid */}
                <div className="bg-card border-t border-border px-6 py-4 flex items-center justify-end gap-3 shrink-0">
                    <Button
                        type="button"
                        variant="outline"
                        onClick={() => onOpenChange(false)}
                        className="rounded-xl border-border font-semibold text-xs text-foreground/80 hover:bg-muted"
                    >
                        Batal
                    </Button>
                    <Button
                        type="submit"
                        form="order-form"
                        disabled={processing}
                        className="rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-semibold text-xs px-6 shadow-md shadow-indigo-600/20"
                    >
                        {processing ? (
                            <span className="flex items-center gap-2">
                                <Loader2 className="w-4 h-4 animate-spin" />
                                Menyimpan Transaksi...
                            </span>
                        ) : (
                            "Simpan & Terbitkan Order"
                        )}
                    </Button>
                </div>
            </DialogContent>
        </Dialog>
    );
}
