import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link } from "@inertiajs/react";
import { Package, ArrowLeft } from "lucide-react";
import { Button } from "@/Components/ui/button";
import ProductForm from "@/Components/Product/ProductForm";
import { getEditBreadcrumbs, BREADCRUMB_MAP } from "@/utils/breadcrumb";
import type { Category, Product } from "./Index";
import type { Unit } from "@/Components/Unit/UnitManagerDialog";

interface Props {
    product: Product;
    categories: Category[];
    units: Unit[];
}

export default function Edit({ product, categories, units }: Props) {
    const urlParams = new URLSearchParams(window.location.search);
    const from = urlParams.get('from');
    const backUrl = from === 'show' ? route('products.show', product.id) : route('products.index');
    const backText = from === 'show' ? "返回商品詳情" : "返回商品列表";

    // 動態產生麵包屑
    const breadcrumbs = from === 'show'
        ? [
            ...JSON.parse(JSON.stringify(BREADCRUMB_MAP.products)),
            { label: `商品詳情 (${product.name})`, href: route('products.show', product.id) },
            { label: "編輯", isPage: true }
        ]
        : getEditBreadcrumbs("products");

    // 修正詳情層級的 isPage 狀態
    if (from === 'show' && breadcrumbs.length > 1) {
        breadcrumbs[breadcrumbs.length - 3].isPage = false; // "商品資料管理" 設為 false
        breadcrumbs[breadcrumbs.length - 2].isPage = false; // "商品詳情" 設為 false
    }

    return (
        <AuthenticatedLayout
            breadcrumbs={breadcrumbs}
        >
            <Head title={`編輯商品 - ${product.name}`} />

            <div className="container mx-auto p-6 max-w-7xl">
                {/* Header */}
                <div className="mb-6">
                    <Link href={backUrl}>
                        <Button
                            variant="outline"
                            className="gap-2 button-outlined-primary mb-4"
                        >
                            <ArrowLeft className="h-4 w-4" />
                            {backText}
                        </Button>
                    </Link>

                    <div className="mb-4">
                        <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
                            <Package className="h-6 w-6 text-primary-main" />
                            編輯商品：{product.name}
                        </h1>
                        <p className="text-gray-500 mt-1">
                            修改商品的基本資訊、價格或庫存單位設定。
                        </p>
                    </div>
                </div>

                {/* 表單內容 */}
                <ProductForm
                    initialData={product}
                    categories={categories}
                    units={units}
                />
            </div>
        </AuthenticatedLayout >
    );
}
