import { Head, Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Loader2 } from 'lucide-react';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { validateForm } from '@/lib/validation';

const productSchema = z.object({
    name: z.string().min(1, 'Product name is required'),
    description: z.string().optional(),
    category_id: z.string().min(1, 'Category is required'),
    brand_id: z.string().min(1, 'Brand is required'),
    vendor_id: z.string().min(1, 'Supplier vendor is required'),
    vendor_price: z.number().min(0, 'Vendor price must be 0 or greater'),
    default_sell_price: z
        .number()
        .min(0, 'Default selling price must be 0 or greater'),
    status: z.enum(['active', 'inactive']),
});

export default function Edit({ product, categories, brands, vendors }: any) {
    const p = product.data;
    const categoryList = Array.isArray(categories)
        ? categories
        : categories?.data || [];
    const brandList = Array.isArray(brands) ? brands : brands?.data || [];
    const vendorList = Array.isArray(vendors) ? vendors : vendors?.data || [];

    const { data, setData, put, processing, errors, setError, clearErrors } =
        useForm({
            name: p.name,
            description: p.description || '',
            category_id: p.category_id || '',
            brand_id: p.brand_id || '',
            vendor_id: p.vendor_id || '',
            vendor_price: p.vendor_price || 0,
            default_sell_price: p.default_sell_price || 0,
            status: p.status || 'active',
        });

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

        if (validateForm(data, productSchema, setError, clearErrors)) {
            put(`/products/${p.id}`);
        }
    };

    return (
        <>
            <Head title="Edit Product" />
            <div className="mx-auto flex w-full max-w-2xl flex-1 flex-col gap-6 p-6">
                {/* Header */}
                <div className="flex items-center gap-4">
                    <Button
                        asChild
                        size="icon"
                        variant="ghost"
                        className="rounded-xl"
                    >
                        <Link href="/products">
                            <ArrowLeft className="size-4" />
                        </Link>
                    </Button>
                    <div>
                        <h1 className="text-3xl font-extrabold tracking-tight text-foreground">
                            Edit Product
                        </h1>
                        <p className="text-sm text-muted-foreground">
                            Modify core specifications, statuses, and pricing
                            indices.
                        </p>
                    </div>
                </div>

                {/* Form Card */}
                <div className="rounded-2xl border border-border bg-card p-6">
                    <form
                        onSubmit={handleSubmit}
                        className="flex flex-col gap-4"
                    >
                        {/* Name */}
                        <div className="flex flex-col gap-1.5">
                            <Label htmlFor="name">Product Name</Label>
                            <Input
                                id="name"
                                value={data.name}
                                onChange={(e) =>
                                    setData('name', e.target.value)
                                }
                                placeholder="E.g. Wireless Noise-Cancelling Headphones"
                                className="rounded-xl"
                            />
                            {errors.name && (
                                <span className="text-xs font-medium text-rose-500">
                                    {errors.name}
                                </span>
                            )}
                        </div>

                        {/* Description */}
                        <div className="flex flex-col gap-1.5">
                            <Label htmlFor="description">Description</Label>
                            <textarea
                                id="description"
                                value={data.description}
                                onChange={(e) =>
                                    setData('description', e.target.value)
                                }
                                placeholder="Detailed overview of specs..."
                                className="min-h-[80px] rounded-xl border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"
                            />
                            {errors.description && (
                                <span className="text-xs font-medium text-rose-500">
                                    {errors.description}
                                </span>
                            )}
                        </div>

                        {/* Category, Brand, Vendor Row */}
                        <div className="grid gap-4 sm:grid-cols-3">
                            {/* Category */}
                            <div className="flex flex-col gap-1.5">
                                <Label htmlFor="category_id">Category</Label>
                                <select
                                    id="category_id"
                                    value={data.category_id}
                                    onChange={(e) =>
                                        setData('category_id', e.target.value)
                                    }
                                    className="h-10 rounded-xl border border-input bg-card px-3 text-sm focus:ring-2 focus:ring-ring focus:outline-none"
                                >
                                    <option value="">Select Category</option>
                                    {categoryList.map((c: any) => (
                                        <option key={c.id} value={c.id}>
                                            {c.name}
                                        </option>
                                    ))}
                                </select>
                                {errors.category_id && (
                                    <span className="text-xs font-medium text-rose-500">
                                        {errors.category_id}
                                    </span>
                                )}
                            </div>

                            {/* Brand */}
                            <div className="flex flex-col gap-1.5">
                                <Label htmlFor="brand_id">Brand</Label>
                                <select
                                    id="brand_id"
                                    value={data.brand_id}
                                    onChange={(e) =>
                                        setData('brand_id', e.target.value)
                                    }
                                    className="h-10 rounded-xl border border-input bg-card px-3 text-sm focus:ring-2 focus:ring-ring focus:outline-none"
                                >
                                    <option value="">Select Brand</option>
                                    {brandList.map((b: any) => (
                                        <option key={b.id} value={b.id}>
                                            {b.name}
                                        </option>
                                    ))}
                                </select>
                                {errors.brand_id && (
                                    <span className="text-xs font-medium text-rose-500">
                                        {errors.brand_id}
                                    </span>
                                )}
                            </div>

                            {/* Vendor */}
                            <div className="flex flex-col gap-1.5">
                                <Label htmlFor="vendor_id">
                                    Supplier Vendor
                                </Label>
                                <select
                                    id="vendor_id"
                                    value={data.vendor_id}
                                    onChange={(e) =>
                                        setData('vendor_id', e.target.value)
                                    }
                                    className="h-10 rounded-xl border border-input bg-card px-3 text-sm focus:ring-2 focus:ring-ring focus:outline-none"
                                >
                                    <option value="">Select Vendor</option>
                                    {vendorList.map((v: any) => (
                                        <option key={v.id} value={v.id}>
                                            {v.name}
                                        </option>
                                    ))}
                                </select>
                                {errors.vendor_id && (
                                    <span className="text-xs font-medium text-rose-500">
                                        {errors.vendor_id}
                                    </span>
                                )}
                            </div>
                        </div>

                        {/* Prices Row */}
                        <div className="grid gap-4 sm:grid-cols-2">
                            {/* Vendor Price */}
                            <div className="flex flex-col gap-1.5">
                                <Label htmlFor="vendor_price">
                                    Vendor Price Snapshot Cost ($)
                                </Label>
                                <Input
                                    id="vendor_price"
                                    type="number"
                                    step="0.01"
                                    value={data.vendor_price}
                                    onChange={(e) =>
                                        setData(
                                            'vendor_price',
                                            parseFloat(e.target.value) || 0,
                                        )
                                    }
                                    className="rounded-xl"
                                />
                                {errors.vendor_price && (
                                    <span className="text-xs font-medium text-rose-500">
                                        {errors.vendor_price}
                                    </span>
                                )}
                            </div>

                            {/* Default Sell Price */}
                            <div className="flex flex-col gap-1.5">
                                <Label htmlFor="default_sell_price">
                                    Default Selling Price ($)
                                </Label>
                                <Input
                                    id="default_sell_price"
                                    type="number"
                                    step="0.01"
                                    value={data.default_sell_price}
                                    onChange={(e) =>
                                        setData(
                                            'default_sell_price',
                                            parseFloat(e.target.value) || 0,
                                        )
                                    }
                                    className="rounded-xl"
                                />
                                {errors.default_sell_price && (
                                    <span className="text-xs font-medium text-rose-500">
                                        {errors.default_sell_price}
                                    </span>
                                )}
                            </div>
                        </div>

                        {/* Status */}
                        <div className="flex flex-col gap-1.5">
                            <Label htmlFor="status">Status</Label>
                            <select
                                id="status"
                                value={data.status}
                                onChange={(e) =>
                                    setData('status', e.target.value as any)
                                }
                                className="h-10 rounded-xl border border-input bg-card px-3 text-sm focus:ring-2 focus:ring-ring focus:outline-none"
                            >
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                            {errors.status && (
                                <span className="text-xs font-medium text-rose-500">
                                    {errors.status}
                                </span>
                            )}
                        </div>

                        {/* Footer */}
                        <div className="mt-4 flex items-center justify-end gap-3">
                            <Button
                                asChild
                                variant="ghost"
                                className="rounded-xl"
                            >
                                <Link href="/products">Cancel</Link>
                            </Button>
                            <Button
                                type="submit"
                                disabled={processing}
                                className="flex items-center gap-1.5 rounded-xl"
                            >
                                {processing && (
                                    <Loader2 className="size-4 animate-spin" />
                                )}
                                <span>Save Changes</span>
                            </Button>
                        </div>
                    </form>
                </div>
            </div>
        </>
    );
}

Edit.layout = {
    breadcrumbs: [
        { title: 'Products', href: '/products' },
        { title: 'Edit Product', href: '/products/edit' },
    ],
};
