import { Head, router, useForm, usePage } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import InputError from '@/components/input-error';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Checkbox } from '@/components/ui/checkbox';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem, SharedData } from '@/types';
import { ChevronDown, MoreVertical, Pencil, Trash2 } from 'lucide-react';

type Product = {
    id: number;
    name: string;
    description?: string | null;
    product_type: 'physique' | 'service';
    unit?: string | null;
    price: number;
    is_active: boolean;
    partner?: { id: number; name: string } | null;
    image_url?: string | null;
    stock_quantity_available?: number | null;
    stock_reorder_level?: number | null;
};

type ProductsPageProps = {
    products: Product[];
    partners: { id: number; name: string }[];
    isAdmin: boolean;
    filters: {
        search?: string;
        type?: string;
        status?: string;
        partner_id?: string | number;
    };
};

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Produits', href: '/produits' },
];

export default function ProductsIndex({
    products,
    partners,
    deliveryServices = [],
    isAdmin,
    isEcommerce = false,
    filters,
}: ProductsPageProps) {
    const { props } = usePage<SharedData>();
    const permissions = props.permissions ?? null;
    const canAddProduct = isAdmin || !permissions || permissions.products?.can_add;
    const canEditProduct = isAdmin || !permissions || permissions.products?.can_edit;
    const canDeleteProduct = isAdmin || !permissions || permissions.products?.can_delete;
    const showProductActions = canEditProduct || canDeleteProduct;
    const [createOpen, setCreateOpen] = useState(false);
    const [editOpen, setEditOpen] = useState(false);
    const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
    const [filterState, setFilterState] = useState({
        search: filters.search ?? '',
        type: filters.type ?? 'all',
        status: filters.status ?? 'all',
        partner_id: filters.partner_id ? String(filters.partner_id) : 'all',
        delivery_service_id: filters.delivery_service_id ? String(filters.delivery_service_id) : 'all',
    });
    const filterTimerRef = useRef<number | null>(null);
    const {
        data,
        setData,
        post,
        processing,
        errors: createErrors,
        reset,
    } = useForm({
        partner_id: partners[0]?.id ?? '',
        name: '',
        description: '',
        product_type: 'physique',
        unit: '',
        price: '',
        is_active: true,
        image: null as File | null,
        delivery_service_ids: [] as number[],
    });
    const {
        data: editData,
        setData: setEditData,
        post: editPost,
        processing: editProcessing,
        errors: editErrors,
        reset: resetEdit,
    } = useForm({
        name: '',
        description: '',
        product_type: 'physique' as 'physique' | 'service',
        unit: '',
        price: '',
        is_active: true,
        image: null as File | null,
        remove_image: false,
        delivery_service_ids: [] as number[],
    });

    const submit = (event: React.FormEvent) => {
        event.preventDefault();
        post('/produits', {
            forceFormData: true,
            onSuccess: () => {
                reset();
                setCreateOpen(false);
            },
        });
    };

    const openEdit = (product: Product) => {
        setSelectedProduct(product);
        setEditData({
            name: product.name,
            description: product.description ?? '',
            product_type: product.product_type,
            unit: product.unit ?? '',
            price: product.price != null ? String(product.price) : '0',
            is_active: product.is_active,
            image: null,
            remove_image: false,
            delivery_service_ids: product.delivery_services?.map((d) => d.id) ?? [],
        });
        setEditOpen(true);
    };

    const submitEdit = (event: React.FormEvent) => {
        event.preventDefault();
        if (!selectedProduct) {
            return;
        }
        // POST + _method=PUT pour que Laravel reçoive bien tous les champs (PUT + multipart/form-data ne fonctionne pas)
        editPost(`/produits/${selectedProduct.id}`, {
            forceFormData: true,
            method: 'put',
            onSuccess: () => {
                resetEdit();
                setEditOpen(false);
                setSelectedProduct(null);
            },
        });
    };

    const destroyProduct = (product: Product) => {
        if (!window.confirm(`Supprimer le produit "${product.name}" ?`)) {
            return;
        }
        router.delete(`/produits/${product.id}`);
    };

    const applyFilters = () => {
        router.get(
            '/produits',
            {
                search: filterState.search || undefined,
                type: filterState.type !== 'all' ? filterState.type : undefined,
                status: filterState.status !== 'all' ? filterState.status : undefined,
                partner_id: filterState.partner_id !== 'all' ? filterState.partner_id : undefined,
                delivery_service_id: filterState.delivery_service_id !== 'all' ? filterState.delivery_service_id : undefined,
            },
            { replace: true, preserveState: true },
        );
    };

    const resetFilters = () => {
        setFilterState({ search: '', type: 'all', status: 'all', partner_id: 'all', delivery_service_id: 'all' });
        router.get('/produits', {}, { replace: true, preserveState: true });
    };

    useEffect(() => {
        if (filterTimerRef.current) {
            window.clearTimeout(filterTimerRef.current);
        }

        filterTimerRef.current = window.setTimeout(() => {
            applyFilters();
        }, 350);

        return () => {
            if (filterTimerRef.current) {
                window.clearTimeout(filterTimerRef.current);
            }
        };
    }, [filterState.search, filterState.type, filterState.status, filterState.partner_id, filterState.delivery_service_id]);

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Produits" />
            <div className="flex flex-col gap-6 p-4">
                <Card>
                    <CardHeader className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
                        <CardTitle>Catalogue produits</CardTitle>
                        {canAddProduct ? (
                            <Button
                                size="sm"
                                className="bg-blue-600 text-white shadow-sm transition duration-200 hover:-translate-y-0.5 hover:bg-blue-700 hover:shadow-md hover:brightness-105 active:translate-y-0 active:shadow"
                                onClick={() => setCreateOpen(true)}
                            >
                                Ajouter un produit
                            </Button>
                        ) : null}
                    </CardHeader>
                    <CardContent>
                        <div className="mb-5 rounded-xl border bg-muted/30 p-4 shadow-sm">
                            <div className="flex flex-wrap items-center justify-between gap-2">
                                <div>
                                    <p className="text-sm font-semibold">Filtres</p>
                                    <p className="text-xs text-muted-foreground">
                                        {isEcommerce
                                            ? 'Affinez la liste par mot-clé, type, statut ou prestataire de livraison.'
                                            : 'Affinez la liste par mot-clé, type, statut ou partenaire.'}
                                    </p>
                                </div>
                            </div>
                            <div className="mt-4 grid gap-3 md:grid-cols-12">
                                <div className="md:col-span-4">
                                    <Label className="text-xs text-muted-foreground">Recherche</Label>
                                    <Input
                                        value={filterState.search}
                                        onChange={(event) =>
                                            setFilterState((prev) => ({
                                                ...prev,
                                                search: event.target.value,
                                            }))
                                        }
                                        placeholder="Nom ou description"
                                    />
                                </div>
                                {isEcommerce && deliveryServices.length > 0 ? (
                                    <div className="md:col-span-3">
                                        <Label className="text-xs text-muted-foreground">Prestataire (service de livraison)</Label>
                                        <Select
                                            value={filterState.delivery_service_id}
                                            onValueChange={(value) =>
                                                setFilterState((prev) => ({
                                                    ...prev,
                                                    delivery_service_id: value,
                                                }))
                                            }
                                        >
                                            <SelectTrigger>
                                                <SelectValue placeholder="Tous" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="all">Tous les prestataires</SelectItem>
                                                {deliveryServices.map((ds) => (
                                                    <SelectItem key={ds.id} value={String(ds.id)}>
                                                        {ds.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                ) : null}
                                {!isEcommerce && partners.length > 0 ? (
                                    <div className="md:col-span-3">
                                        <Label className="text-xs text-muted-foreground">Partenaire (e-commerçant)</Label>
                                        <Select
                                            value={filterState.partner_id}
                                            onValueChange={(value) =>
                                                setFilterState((prev) => ({
                                                    ...prev,
                                                    partner_id: value,
                                                }))
                                            }
                                        >
                                            <SelectTrigger>
                                                <SelectValue placeholder="Tous" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="all">Tous les partenaires</SelectItem>
                                                {partners.map((partner) => (
                                                    <SelectItem
                                                        key={partner.id}
                                                        value={String(partner.id)}
                                                    >
                                                        {partner.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                ) : null}
                                <div className="md:col-span-2">
                                    <Label className="text-xs text-muted-foreground">Type</Label>
                                    <Select
                                        value={filterState.type}
                                        onValueChange={(value) =>
                                            setFilterState((prev) => ({
                                                ...prev,
                                                type: value,
                                            }))
                                        }
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder="Tous" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="all">Tous</SelectItem>
                                            <SelectItem value="physique">Physique</SelectItem>
                                            <SelectItem value="service">Service</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div className="md:col-span-2">
                                    <Label className="text-xs text-muted-foreground">Statut</Label>
                                    <Select
                                        value={filterState.status}
                                        onValueChange={(value) =>
                                            setFilterState((prev) => ({
                                                ...prev,
                                                status: value,
                                            }))
                                        }
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder="Tous" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="all">Tous</SelectItem>
                                            <SelectItem value="actif">Actif</SelectItem>
                                            <SelectItem value="inactif">Inactif</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>
                        </div>
                        {products.length === 0 ? (
                            <div className="rounded-xl border border-dashed p-6 text-center text-sm text-muted-foreground">
                                Aucun produit trouvé avec ces filtres.
                            </div>
                        ) : (
                            <div className="grid gap-4 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3">
                                {products.map((product) => (
                                    <div
                                        key={product.id}
                                        className="rounded-2xl border bg-white p-4 shadow-sm transition duration-200 hover:-translate-y-1 hover:shadow-md"
                                    >
                                        <div className="flex items-start justify-between gap-3">
                                            <div className="min-w-0 flex-1">
                                                <div className="flex items-center gap-3">
                                                {product.image_url ? (
                                                    <img
                                                        src={product.image_url}
                                                        alt={product.name}
                                                        loading="lazy"
                                                        onError={(event) => {
                                                            event.currentTarget.src = '/favicon.svg';
                                                        }}
                                                        className="h-12 w-12 rounded-xl object-cover bg-muted"
                                                    />
                                                ) : (
                                                    <div className="h-12 w-12 rounded-xl bg-muted" />
                                                )}
                                                <div className="min-w-0 flex-1">
                                                    <p className="break-words text-sm font-semibold text-slate-900">
                                                        {product.name}
                                                    </p>
                                                    {product.description != null && product.description !== '' && (
                                                        <p className="mt-0.5 line-clamp-2 break-words text-xs text-slate-500">
                                                            {product.description}
                                                        </p>
                                                    )}
                                                    <p className="mt-0.5 text-sm text-slate-600">
                                                        {(product.price?.toLocaleString?.('fr-FR') ?? product.price)} FCFA
                                                    </p>
                                                </div>
                                                </div>
                                            </div>
                                            <div className="flex flex-wrap items-center gap-2">
                                                <span
                                                    className={
                                                        product.is_active
                                                            ? 'rounded-full bg-emerald-50 px-2 py-0.5 text-xs font-medium text-emerald-700'
                                                            : 'rounded-full bg-rose-50 px-2 py-0.5 text-xs font-medium text-rose-700'
                                                    }
                                                >
                                                    {product.is_active ? 'Actif' : 'Inactif'}
                                                </span>
                                                {typeof product.stock_quantity_available === 'number' && product.stock_quantity_available === 0 && (
                                                    <span className="rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-800">
                                                        Rupture
                                                    </span>
                                                )}
                                                {typeof product.stock_quantity_available === 'number' && typeof product.stock_reorder_level === 'number' && product.stock_quantity_available > 0 && product.stock_quantity_available <= product.stock_reorder_level && (
                                                    <span className="rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-800">
                                                        Au seuil
                                                    </span>
                                                )}
                                                {showProductActions ? (
                                                    <DropdownMenu>
                                                        <DropdownMenuTrigger asChild>
                                                            <Button
                                                                size="icon"
                                                                variant="ghost"
                                                                className="h-8 w-8 text-slate-500 transition hover:bg-slate-100 hover:text-slate-700"
                                                            >
                                                                <MoreVertical className="h-4 w-4" />
                                                            </Button>
                                                        </DropdownMenuTrigger>
                                                        <DropdownMenuContent align="end">
                                                            {canEditProduct ? (
                                                                <DropdownMenuItem
                                                                    onClick={() =>
                                                                        openEdit(product)
                                                                    }
                                                                >
                                                                    <Pencil className="h-4 w-4" />
                                                                    Éditer
                                                                </DropdownMenuItem>
                                                            ) : null}
                                                            {canEditProduct && canDeleteProduct ? (
                                                                <DropdownMenuSeparator />
                                                            ) : null}
                                                            {canDeleteProduct ? (
                                                                <DropdownMenuItem
                                                                    variant="destructive"
                                                                    onClick={() =>
                                                                        destroyProduct(product)
                                                                    }
                                                                >
                                                                    <Trash2 className="h-4 w-4" />
                                                                    Supprimer
                                                                </DropdownMenuItem>
                                                            ) : null}
                                                        </DropdownMenuContent>
                                                    </DropdownMenu>
                                                ) : null}
                                            </div>
                                        </div>

                                        <div className="mt-4 grid grid-cols-2 gap-3 text-xs text-slate-600">
                                            <div>
                                                <p className="text-[11px] uppercase tracking-wide text-slate-400">
                                                    Type
                                                </p>
                                                <p className="font-medium text-slate-700">
                                                    {product.product_type}
                                                </p>
                                            </div>
                                            <div>
                                                <p className="text-[11px] uppercase tracking-wide text-slate-400">
                                                    Unité
                                                </p>
                                                <p className="font-medium text-slate-700">
                                                    {product.unit || '-'}
                                                </p>
                                            </div>
                                            {isEcommerce && (product.delivery_services?.length ?? 0) > 0 ? (
                                                <div className="col-span-2">
                                                    <p className="text-[11px] uppercase tracking-wide text-slate-400">
                                                        Prestataires livraison
                                                    </p>
                                                    <p className="font-medium text-slate-700">
                                                        {product.delivery_services!.map((d) => d.name).join(', ')}
                                                    </p>
                                                </div>
                                            ) : null}
                                            {(isAdmin || (partners.length > 1 && !isEcommerce)) ? (
                                                <div className="col-span-2">
                                                    <p className="text-[11px] uppercase tracking-wide text-slate-400">
                                                        Partenaire (e-commerçant)
                                                    </p>
                                                    <p className="font-medium text-slate-700">
                                                        {product.partner?.name ?? '-'}
                                                    </p>
                                                </div>
                                            ) : null}
                                        </div>

                                    </div>
                                ))}
                            </div>
                        )}
                    </CardContent>
                </Card>

                {canAddProduct ? (
                    <Dialog open={createOpen} onOpenChange={setCreateOpen}>
                    <DialogContent className="max-w-3xl max-h-[85vh] overflow-y-auto">
                        <DialogHeader>
                            <DialogTitle>Ajouter un produit</DialogTitle>
                            <DialogDescription>
                                Saisissez les informations du produit. L’image est optionnelle.
                            </DialogDescription>
                        </DialogHeader>
                        <form
                            className="grid gap-4 md:grid-cols-2"
                            onSubmit={submit}
                            encType="multipart/form-data"
                        >
                            {Object.keys(createErrors).length > 0 ? (
                                <div className="md:col-span-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                                    Veuillez corriger les erreurs du formulaire.
                                </div>
                            ) : null}
                            {(isAdmin || (partners.length > 0 && !isEcommerce)) ? (
                                <div className="space-y-2 md:col-span-2">
                                    <Label>Partenaire (e-commerçant)</Label>
                                    <Select
                                        value={
                                            data.partner_id
                                                ? String(data.partner_id)
                                                : undefined
                                        }
                                        onValueChange={(value) =>
                                            setData('partner_id', Number(value))
                                        }
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder="Choisir le partenaire" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {partners.map((partner) => (
                                                <SelectItem
                                                    key={partner.id}
                                                    value={String(partner.id)}
                                                >
                                                    {partner.name}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                    <InputError message={createErrors.partner_id} />
                                </div>
                            ) : null}
                            {isEcommerce && deliveryServices.length > 0 ? (
                                <div className="space-y-2 md:col-span-2">
                                    <Label>Prestataires qui livrent ce produit</Label>
                                    <p className="text-xs text-muted-foreground">
                                        Sélectionnez les services de livraison avec lesquels vous collaborez et qui pourront livrer ce produit.
                                    </p>
                                    <DropdownMenu>
                                        <DropdownMenuTrigger asChild>
                                            <Button
                                                type="button"
                                                variant="outline"
                                                className="w-full justify-between font-normal"
                                            >
                                                <span className="truncate">
                                                    {(data.delivery_service_ids as number[])?.length
                                                        ? `${(data.delivery_service_ids as number[]).length} prestataire(s) sélectionné(s)`
                                                        : 'Choisir les prestataires'}
                                                </span>
                                                <ChevronDown className="size-4 opacity-50 shrink-0" />
                                            </Button>
                                        </DropdownMenuTrigger>
                                        <DropdownMenuContent align="start" className="max-h-60 w-[var(--radix-dropdown-menu-trigger-width)] overflow-auto p-1">
                                            {deliveryServices.map((ds) => (
                                                <label
                                                    key={ds.id}
                                                    className="flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm hover:bg-accent"
                                                >
                                                    <Checkbox
                                                        checked={(data.delivery_service_ids as number[]).includes(ds.id)}
                                                        onCheckedChange={(checked) => {
                                                            const ids = (data.delivery_service_ids as number[]) ?? [];
                                                            setData(
                                                                'delivery_service_ids',
                                                                checked ? [...ids, ds.id] : ids.filter((id) => id !== ds.id),
                                                            );
                                                        }}
                                                    />
                                                    <span>{ds.name}</span>
                                                </label>
                                            ))}
                                        </DropdownMenuContent>
                                    </DropdownMenu>
                                    <InputError message={createErrors.delivery_service_ids as string} />
                                </div>
                            ) : null}
                            <div className="space-y-2">
                                <Label>Nom</Label>
                                <Input
                                    value={data.name}
                                    onChange={(e) =>
                                        setData('name', e.target.value)
                                    }
                                    required
                                />
                                <InputError message={createErrors.name} />
                            </div>
                            <div className="space-y-2">
                                <Label>Unité</Label>
                                <Input
                                    value={data.unit}
                                    onChange={(e) =>
                                        setData('unit', e.target.value)
                                    }
                                />
                                <InputError message={createErrors.unit} />
                            </div>
                            <div className="space-y-2">
                                <Label>Prix (FCFA)</Label>
                                <Input
                                    type="number"
                                    min="0"
                                    step="0.01"
                                    value={data.price}
                                    onChange={(e) =>
                                        setData('price', e.target.value)
                                    }
                                    required
                                />
                                <InputError message={createErrors.price} />
                            </div>
                            <div className="space-y-2 md:col-span-2">
                                <Label>Description</Label>
                                <Input
                                    value={data.description}
                                    onChange={(e) =>
                                        setData('description', e.target.value)
                                    }
                                />
                                <InputError message={createErrors.description} />
                            </div>
                            <div className="space-y-2">
                                <Label>Type</Label>
                                <Select
                                    value={data.product_type}
                                    onValueChange={(value) =>
                                        setData(
                                            'product_type',
                                            value as 'physique' | 'service',
                                        )
                                    }
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Type" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="physique">
                                            Physique
                                        </SelectItem>
                                        <SelectItem value="service">
                                            Service
                                        </SelectItem>
                                    </SelectContent>
                                </Select>
                                <InputError message={createErrors.product_type} />
                            </div>
                            <div className="space-y-2">
                                <Label>Statut</Label>
                                <Select
                                    value={data.is_active ? '1' : '0'}
                                    onValueChange={(value) =>
                                        setData('is_active', value === '1')
                                    }
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Statut" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="1">Actif</SelectItem>
                                        <SelectItem value="0">
                                            Inactif
                                        </SelectItem>
                                    </SelectContent>
                                </Select>
                                <InputError message={createErrors.is_active} />
                            </div>
                            <div className="space-y-2 md:col-span-2">
                                <Label>Image du produit (optionnel)</Label>
                                <Input
                                    type="file"
                                    accept="image/*"
                                    onChange={(event) =>
                                        setData(
                                            'image',
                                            event.target.files?.[0] ?? null,
                                        )
                                    }
                                />
                                <InputError message={createErrors.image} />
                            </div>
                            <DialogFooter className="md:col-span-2">
                                <Button
                                    type="submit"
                                    disabled={processing}
                                    className="bg-blue-600 text-white shadow-sm transition duration-200 hover:-translate-y-0.5 hover:bg-blue-700 hover:shadow-md hover:brightness-105 active:translate-y-0 active:shadow"
                                >
                                    Enregistrer
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                    </Dialog>
                ) : null}

                {canEditProduct ? (
                    <Dialog open={editOpen} onOpenChange={setEditOpen}>
                    <DialogContent className="max-w-3xl max-h-[85vh] overflow-y-auto">
                        <DialogHeader>
                            <DialogTitle>Modifier le produit</DialogTitle>
                            <DialogDescription>
                                Mettez à jour les informations et l’image du produit.
                            </DialogDescription>
                        </DialogHeader>
                        <form
                            className="grid gap-4 md:grid-cols-2"
                            onSubmit={submitEdit}
                            encType="multipart/form-data"
                        >
                            {Object.keys(editErrors).length > 0 ? (
                                <div className="md:col-span-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                                    Veuillez corriger les erreurs du formulaire.
                                </div>
                            ) : null}
                            <div className="space-y-2">
                                <Label>Nom</Label>
                                <Input
                                    value={editData.name}
                                    onChange={(e) =>
                                        setEditData('name', e.target.value)
                                    }
                                    required
                                />
                                <InputError message={editErrors.name} />
                            </div>
                            <div className="space-y-2">
                                <Label>Unité</Label>
                                <Input
                                    value={editData.unit}
                                    onChange={(e) =>
                                        setEditData('unit', e.target.value)
                                    }
                                />
                                <InputError message={editErrors.unit} />
                            </div>
                            <div className="space-y-2">
                                <Label>Prix (FCFA)</Label>
                                <Input
                                    type="number"
                                    min="0"
                                    step="0.01"
                                    value={editData.price}
                                    onChange={(e) =>
                                        setEditData('price', e.target.value)
                                    }
                                    required
                                />
                                <InputError message={editErrors.price} />
                            </div>
                            <div className="space-y-2 md:col-span-2">
                                <Label>Description</Label>
                                <Input
                                    value={editData.description}
                                    onChange={(e) =>
                                        setEditData('description', e.target.value)
                                    }
                                />
                                <InputError message={editErrors.description} />
                            </div>
                            <div className="space-y-2">
                                <Label>Type</Label>
                                <Select
                                    value={editData.product_type}
                                    onValueChange={(value) =>
                                        setEditData(
                                            'product_type',
                                            value as 'physique' | 'service',
                                        )
                                    }
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Type" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="physique">
                                            Physique
                                        </SelectItem>
                                        <SelectItem value="service">
                                            Service
                                        </SelectItem>
                                    </SelectContent>
                                </Select>
                                <InputError message={editErrors.product_type} />
                            </div>
                            <div className="space-y-2">
                                <Label>Statut</Label>
                                <Select
                                    value={editData.is_active ? '1' : '0'}
                                    onValueChange={(value) =>
                                        setEditData('is_active', value === '1')
                                    }
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Statut" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="1">Actif</SelectItem>
                                        <SelectItem value="0">
                                            Inactif
                                        </SelectItem>
                                    </SelectContent>
                                </Select>
                                <InputError message={editErrors.is_active} />
                            </div>
                            {isEcommerce && deliveryServices.length > 0 ? (
                                <div className="space-y-2 md:col-span-2">
                                    <Label>Prestataires qui livrent ce produit</Label>
                                    <p className="text-xs text-muted-foreground">
                                        Sélectionnez les services de livraison avec lesquels vous collaborez et qui pourront livrer ce produit.
                                    </p>
                                    <DropdownMenu>
                                        <DropdownMenuTrigger asChild>
                                            <Button
                                                type="button"
                                                variant="outline"
                                                className="w-full justify-between font-normal"
                                            >
                                                <span className="truncate">
                                                    {(editData.delivery_service_ids as number[])?.length
                                                        ? `${(editData.delivery_service_ids as number[]).length} prestataire(s) sélectionné(s)`
                                                        : 'Choisir les prestataires'}
                                                </span>
                                                <ChevronDown className="size-4 opacity-50 shrink-0" />
                                            </Button>
                                        </DropdownMenuTrigger>
                                        <DropdownMenuContent align="start" className="max-h-60 w-[var(--radix-dropdown-menu-trigger-width)] overflow-auto p-1">
                                            {deliveryServices.map((ds) => (
                                                <label
                                                    key={ds.id}
                                                    className="flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm hover:bg-accent"
                                                >
                                                    <Checkbox
                                                        checked={(editData.delivery_service_ids as number[]).includes(ds.id)}
                                                        onCheckedChange={(checked) => {
                                                            const ids = (editData.delivery_service_ids as number[]) ?? [];
                                                            setEditData(
                                                                'delivery_service_ids',
                                                                checked ? [...ids, ds.id] : ids.filter((id) => id !== ds.id),
                                                            );
                                                        }}
                                                    />
                                                    <span>{ds.name}</span>
                                                </label>
                                            ))}
                                        </DropdownMenuContent>
                                    </DropdownMenu>
                                    <InputError message={editErrors.delivery_service_ids as string} />
                                </div>
                            ) : null}
                            {selectedProduct?.image_url && !editData.remove_image ? (
                                <div className="space-y-2 md:col-span-2">
                                    <Label>Image actuelle</Label>
                                    <img
                                        src={selectedProduct.image_url}
                                        alt={selectedProduct.name}
                                        className="h-20 w-20 rounded-md object-cover"
                                    />
                                    <Button
                                        type="button"
                                        size="sm"
                                        className="bg-rose-600 text-white shadow-sm transition duration-200 hover:-translate-y-0.5 hover:bg-rose-700 hover:shadow-md hover:brightness-105 active:translate-y-0 active:shadow"
                                        onClick={() => setEditData('remove_image', true)}
                                    >
                                        Supprimer image
                                    </Button>
                                </div>
                            ) : null}
                            {editData.remove_image ? (
                                <div className="md:col-span-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700">
                                    L’image sera supprimée lors de la mise à jour.
                                    <div className="mt-2">
                                        <Button
                                            type="button"
                                            size="sm"
                                            className="bg-slate-100 text-slate-700 shadow-sm transition duration-200 hover:-translate-y-0.5 hover:bg-slate-200 hover:text-slate-900 hover:shadow-md active:translate-y-0 active:shadow"
                                            onClick={() => setEditData('remove_image', false)}
                                        >
                                            Annuler suppression
                                        </Button>
                                    </div>
                                </div>
                            ) : null}
                            <div className="space-y-2 md:col-span-2">
                                <Label>Changer l’image (optionnel)</Label>
                                <Input
                                    type="file"
                                    accept="image/*"
                                    onChange={(event) =>
                                        setEditData('image', event.target.files?.[0] ?? null)
                                    }
                                />
                                <InputError message={editErrors.image} />
                            </div>
                            <DialogFooter className="md:col-span-2">
                                <Button
                                    type="submit"
                                    disabled={editProcessing}
                                    className="bg-blue-600 text-white shadow-sm transition duration-200 hover:-translate-y-0.5 hover:bg-blue-700 hover:shadow-md hover:brightness-105 active:translate-y-0 active:shadow"
                                >
                                    Mettre à jour
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                    </Dialog>
                ) : null}
            </div>
        </AppLayout>
    );
}
