import { Head, router, useForm } from '@inertiajs/react';
import { CalendarDays, ChevronLeft, ImagePlus, Tag, Trash2, X } from 'lucide-react';
import { FormEventHandler, useEffect, useMemo, useRef, useState } from 'react';

import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import AdminLayout from '@/layouts/admin-layout';
import { type Brand, type Product, type ProductImage } from '@/types';

export default function AdminFragranceEdit({ product, brands }: { product: Product; brands: Brand[] }) {
    const { data, setData, post, processing, errors } = useForm<any>({
        _method: 'PATCH',
        name: product.name,
        brand_id: String(product.brand?.id ?? ''),
        sku: product.sku,
        price: product.price,
        cost_price: product.cost_price,
        compare_price: product.compare_price ?? '',
        discount_type: product.discount_type ?? 'none',
        discount_value: product.discount_value ?? '',
        discount_label: product.discount_label ?? '',
        discount_starts_at: product.discount_starts_at ? product.discount_starts_at.replace(' ', 'T').slice(0, 16) : '',
        discount_ends_at: product.discount_ends_at ? product.discount_ends_at.replace(' ', 'T').slice(0, 16) : '',
        stock_qty: String(product.stock_qty),
        low_stock_alert: String(product.low_stock_alert),
        short_description: product.short_description ?? '',
        description: product.description ?? '',
        is_featured: product.is_featured,
        is_best_seller: product.is_best_seller,
        is_new_arrival: product.is_new_arrival,
        status: product.status,
        meta_title: product.meta_title ?? '',
        meta_description: product.meta_description ?? '',
        images: [] as File[],
        remove_image_ids: [] as number[],
    });

    const [existingImages, setExistingImages] = useState<ProductImage[]>(product.images ?? []);
    const [newPreviews, setNewPreviews] = useState<string[]>([]);
    const fileRef = useRef<HTMLInputElement>(null);

    const hasDiscount = data.discount_type !== 'none';

    const computedPrice = useMemo(() => {
        const type = data.discount_type;
        const mrp = parseFloat(data.compare_price);
        const val = parseFloat(data.discount_value);
        if (isNaN(mrp) || mrp <= 0 || isNaN(val) || val <= 0) return null;
        if (type === 'percent') return Math.round(mrp * (1 - val / 100) * 100) / 100;
        if (type === 'fixed') return Math.max(0, Math.round((mrp - val) * 100) / 100);
        return null;
    }, [data.discount_type, data.compare_price, data.discount_value]);

    useEffect(() => {
        if (hasDiscount && computedPrice !== null) {
            setData('price', String(computedPrice));
        }
    }, [computedPrice, hasDiscount]);

    const addImages = (files: FileList | null) => {
        if (!files) return;
        const arr = Array.from(files);
        setData('images', [...(data.images as File[]), ...arr]);
        setNewPreviews((p) => [...p, ...arr.map((f) => URL.createObjectURL(f))]);
    };

    const removeNewImage = (idx: number) => {
        const newFiles = [...(data.images as File[])];
        newFiles.splice(idx, 1);
        setData('images', newFiles);
        setNewPreviews((p) => p.filter((_, i) => i !== idx));
    };

    const removeExistingImage = (img: ProductImage) => {
        setExistingImages((prev) => prev.filter((i) => i.id !== img.id));
        setData('remove_image_ids', [...(data.remove_image_ids as number[]), img.id]);
    };

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        post(route('admin.fragrances.update', product.id), { forceFormData: true });
    };

    return (
        <AdminLayout title={`Edit: ${product.name}`}>
            <Head title={`Edit ${product.name}`} />

            <div className="mb-4 flex items-center gap-3">
                <Button variant="ghost" size="sm" onClick={() => history.back()}><ChevronLeft size={16} /> Back</Button>
                <Button
                    type="button"
                    variant="destructive"
                    size="sm"
                    onClick={() => {
                        if (confirm('Delete this fragrance product?')) {
                            router.delete(route('admin.fragrances.destroy', product.id));
                        }
                    }}
                >
                    <Trash2 size={14} /> Delete
                </Button>
                {product.is_discount_active && (
                    <span className="ml-auto rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-700">Discount Active</span>
                )}
            </div>

            <form onSubmit={submit}>
                <div className="grid gap-4 lg:grid-cols-3">
                    <div className="space-y-4 lg:col-span-2">
                        {/* Product Info */}
                        <Card>
                            <CardHeader><CardTitle className="text-base">Fragrance Info</CardTitle></CardHeader>
                            <CardContent className="space-y-4">
                                <div className="space-y-1.5">
                                    <Label>Product Name *</Label>
                                    <Input value={data.name} onChange={(e) => setData('name', e.target.value)} />
                                    <InputError message={errors.name} />
                                </div>
                                <div className="grid gap-4 sm:grid-cols-2">
                                    <div className="space-y-1.5">
                                        <Label>SKU</Label>
                                        <Input value={data.sku} onChange={(e) => setData('sku', e.target.value)} />
                                        <InputError message={errors.sku} />
                                    </div>
                                    <div className="space-y-1.5">
                                        <Label>Brand</Label>
                                        <Select value={data.brand_id} onValueChange={(v) => setData('brand_id', v)}>
                                            <SelectTrigger aria-label="Brand"><SelectValue placeholder="Select brand" /></SelectTrigger>
                                            <SelectContent>
                                                {brands.map((b) => <SelectItem key={b.id} value={String(b.id)}>{b.name}</SelectItem>)}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                </div>
                                <div className="space-y-1.5">
                                    <Label>Short Description</Label>
                                    <textarea rows={2} value={data.short_description} onChange={(e) => setData('short_description', e.target.value)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" />
                                </div>
                                <div className="space-y-1.5">
                                    <Label>Full Description</Label>
                                    <textarea rows={5} value={data.description} onChange={(e) => setData('description', e.target.value)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" />
                                </div>
                            </CardContent>
                        </Card>

                        {/* Pricing & Stock */}
                        <Card>
                            <CardHeader><CardTitle className="text-base">Pricing & Stock</CardTitle></CardHeader>
                            <CardContent className="grid gap-4 sm:grid-cols-2">
                                <div className="space-y-1.5">
                                    <Label>
                                        Selling Price (৳) *
                                        {hasDiscount && <span className="ml-1 text-xs text-slate-400">(auto-calculated)</span>}
                                    </Label>
                                    <Input
                                        type="number"
                                        step="0.01"
                                        value={data.price}
                                        onChange={(e) => setData('price', e.target.value)}
                                        readOnly={hasDiscount && computedPrice !== null}
                                        className={hasDiscount && computedPrice !== null ? 'bg-slate-50 text-slate-500' : ''}
                                    />
                                    <InputError message={errors.price} />
                                </div>
                                <div className="space-y-1.5">
                                    <Label>Cost Price (৳)</Label>
                                    <Input type="number" step="0.01" value={data.cost_price} onChange={(e) => setData('cost_price', e.target.value)} />
                                </div>
                                <div className="space-y-1.5">
                                    <Label>Stock Quantity</Label>
                                    <Input type="number" value={data.stock_qty} onChange={(e) => setData('stock_qty', e.target.value)} />
                                </div>
                                <div className="space-y-1.5">
                                    <Label>Low Stock Alert</Label>
                                    <Input type="number" value={data.low_stock_alert} onChange={(e) => setData('low_stock_alert', e.target.value)} />
                                </div>
                            </CardContent>
                        </Card>

                        {/* Discount */}
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2 text-base">
                                    <Tag size={16} className="text-violet-500" /> Discount
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                <div className="space-y-1.5">
                                    <Label>Discount Type</Label>
                                    <Select
                                        value={data.discount_type}
                                        onValueChange={(v) => {
                                            setData('discount_type', v);
                                            if (v === 'none') {
                                                setData('compare_price', '');
                                                setData('discount_value', '');
                                                setData('discount_label', '');
                                                setData('discount_starts_at', '');
                                                setData('discount_ends_at', '');
                                            }
                                        }}
                                    >
                                        <SelectTrigger aria-label="Discount type"><SelectValue /></SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="none">No Discount</SelectItem>
                                            <SelectItem value="percent">Percentage Off (%)</SelectItem>
                                            <SelectItem value="fixed">Fixed Amount Off (৳)</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                                {hasDiscount && (
                                    <>
                                        <div className="grid gap-4 sm:grid-cols-2">
                                            <div className="space-y-1.5">
                                                <Label>Original Price / MRP (৳)</Label>
                                                <Input type="number" step="0.01" value={data.compare_price} onChange={(e) => setData('compare_price', e.target.value)} />
                                            </div>
                                            <div className="space-y-1.5">
                                                <Label>Discount {data.discount_type === 'percent' ? '(%)' : '(৳)'}</Label>
                                                <Input type="number" step="0.01" value={data.discount_value} onChange={(e) => setData('discount_value', e.target.value)} />
                                            </div>
                                        </div>
                                        {computedPrice !== null && (
                                            <div className="rounded-lg border border-violet-200 bg-violet-50 px-4 py-3 text-sm">
                                                <span className="text-slate-500 line-through">৳{Number(data.compare_price).toLocaleString()}</span>
                                                <span className="mx-2 text-slate-400">→</span>
                                                <span className="font-bold text-violet-700">৳{computedPrice.toLocaleString()}</span>
                                            </div>
                                        )}
                                        <div className="space-y-1.5">
                                            <Label>Discount Label</Label>
                                            <Input value={data.discount_label} onChange={(e) => setData('discount_label', e.target.value)} placeholder="e.g. Eid Special" maxLength={50} />
                                        </div>
                                        <div className="space-y-2">
                                            <Label className="flex items-center gap-1.5"><CalendarDays size={14} className="text-slate-400" /> Schedule (optional)</Label>
                                            <div className="grid gap-3 sm:grid-cols-2">
                                                <div className="space-y-1">
                                                    <Label className="text-xs text-slate-500">Start Date</Label>
                                                    <Input type="datetime-local" value={data.discount_starts_at} onChange={(e) => setData('discount_starts_at', e.target.value)} />
                                                </div>
                                                <div className="space-y-1">
                                                    <Label className="text-xs text-slate-500">End Date</Label>
                                                    <Input type="datetime-local" value={data.discount_ends_at} onChange={(e) => setData('discount_ends_at', e.target.value)} />
                                                </div>
                                            </div>
                                        </div>
                                    </>
                                )}
                            </CardContent>
                        </Card>

                        {/* Images */}
                        <Card>
                            <CardHeader><CardTitle className="text-base">Product Images</CardTitle></CardHeader>
                            <CardContent className="space-y-3">
                                {existingImages.length > 0 && (
                                    <div>
                                        <p className="mb-2 text-xs font-medium text-slate-500">Current Images</p>
                                        <div className="grid grid-cols-4 gap-3 sm:grid-cols-6">
                                            {existingImages.map((img) => (
                                                <div key={img.id} className="group relative">
                                                    <img src={`/storage/${img.image}`} alt="" className="h-20 w-full rounded-lg border border-slate-200 object-cover" />
                                                    {img.is_primary && <span className="absolute bottom-1 left-1 rounded bg-violet-600 px-1 py-0.5 text-[10px] font-bold text-white">Primary</span>}
                                                    <button type="button" onClick={() => removeExistingImage(img)} className="absolute -right-1.5 -top-1.5 hidden rounded-full bg-red-500 p-0.5 text-white group-hover:flex">
                                                        <X size={12} />
                                                    </button>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}
                                <div
                                    className="flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-slate-300 p-5 text-slate-500 transition hover:border-violet-400 hover:bg-violet-50/40 dark:border-slate-600"
                                    onClick={() => fileRef.current?.click()}
                                >
                                    <ImagePlus size={24} className="text-violet-400" />
                                    <p className="text-sm font-medium">Add more images</p>
                                    <input ref={fileRef} type="file" accept="image/*" multiple className="hidden" onChange={(e) => addImages(e.target.files)} />
                                </div>
                                {newPreviews.length > 0 && (
                                    <div className="grid grid-cols-4 gap-3 sm:grid-cols-6">
                                        {newPreviews.map((src, idx) => (
                                            <div key={idx} className="group relative">
                                                <img src={src} alt="" className="h-20 w-full rounded-lg border border-violet-200 object-cover ring-1 ring-violet-300" />
                                                <button type="button" onClick={() => removeNewImage(idx)} className="absolute -right-1.5 -top-1.5 hidden rounded-full bg-red-500 p-0.5 text-white group-hover:flex">
                                                    <X size={12} />
                                                </button>
                                            </div>
                                        ))}
                                    </div>
                                )}
                                <InputError message={errors.images} />
                            </CardContent>
                        </Card>

                        {/* SEO */}
                        <Card>
                            <CardHeader><CardTitle className="text-base">SEO</CardTitle></CardHeader>
                            <CardContent className="space-y-4">
                                <div className="space-y-1.5">
                                    <Label>Meta Title</Label>
                                    <Input value={data.meta_title} onChange={(e) => setData('meta_title', e.target.value)} />
                                </div>
                                <div className="space-y-1.5">
                                    <Label>Meta Description</Label>
                                    <textarea rows={2} value={data.meta_description} onChange={(e) => setData('meta_description', e.target.value)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" />
                                </div>
                            </CardContent>
                        </Card>
                    </div>

                    {/* Sidebar */}
                    <div className="space-y-4">
                        <Card>
                            <CardHeader><CardTitle className="text-base">Visibility</CardTitle></CardHeader>
                            <CardContent className="space-y-3">
                                {([
                                    ['status', 'Visible on Fragrance Page'],
                                    ['is_featured', 'Featured'],
                                    ['is_best_seller', 'Best Seller'],
                                    ['is_new_arrival', 'New Arrival'],
                                ] as [string, string][]).map(([field, label]) => (
                                    <div key={field} className="flex items-center gap-2">
                                        <Checkbox
                                            id={field}
                                            checked={Boolean(data[field])}
                                            onCheckedChange={(v) => setData(field as any, Boolean(v))}
                                        />
                                        <Label htmlFor={field}>{label}</Label>
                                    </div>
                                ))}
                            </CardContent>
                        </Card>

                        <Button type="submit" className="w-full bg-violet-600 hover:bg-violet-700" disabled={processing}>
                            {processing ? 'Saving…' : 'Update Fragrance'}
                        </Button>
                    </div>
                </div>
            </form>
        </AdminLayout>
    );
}
