import { Head, useForm } from '@inertiajs/react';
import { CalendarDays, ChevronLeft, ImagePlus, Tag, 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 } from '@/types';

export default function AdminFragranceCreate({ brands }: { brands: Brand[] }) {
    const { data, setData, post, processing, errors } = useForm<any>({
        name: '',
        brand_id: '',
        sku: '',
        price: '',
        cost_price: '',
        compare_price: '',
        discount_type: 'none',
        discount_value: '',
        discount_label: '',
        discount_starts_at: '',
        discount_ends_at: '',
        stock_qty: '',
        low_stock_alert: '5',
        short_description: '',
        description: '',
        is_featured: false,
        is_best_seller: false,
        is_new_arrival: false,
        status: true,
        meta_title: '',
        meta_description: '',
        images: [] as File[],
    });

    const [previews, setPreviews] = 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]);
        setPreviews((p) => [...p, ...arr.map((f) => URL.createObjectURL(f))]);
    };

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

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

    return (
        <AdminLayout title="Add Fragrance">
            <Head title="Add Fragrance" />

            <div className="mb-4">
                <Button variant="ghost" size="sm" onClick={() => history.back()}>
                    <ChevronLeft size={16} /> Back
                </Button>
            </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 htmlFor="name">Product Name *</Label>
                                    <Input id="name" value={data.name} onChange={(e) => setData('name', e.target.value)} placeholder="e.g. Oud Al Anfar" />
                                    <InputError message={errors.name} />
                                </div>
                                <div className="grid gap-4 sm:grid-cols-2">
                                    <div className="space-y-1.5">
                                        <Label htmlFor="sku">SKU</Label>
                                        <Input id="sku" value={data.sku} onChange={(e) => setData('sku', e.target.value)} placeholder="Auto-generated if empty" />
                                        <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 (optional)" /></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 htmlFor="short_description">Short Description</Label>
                                    <textarea
                                        id="short_description"
                                        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 ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                                        placeholder="Scent notes, volume, occasion…"
                                    />
                                </div>
                                <div className="space-y-1.5">
                                    <Label htmlFor="description">Full Description</Label>
                                    <textarea
                                        id="description"
                                        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"
                                        placeholder="Full fragrance description, ingredients, how to use…"
                                    />
                                </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 htmlFor="price">
                                        Selling Price (৳) *
                                        {hasDiscount && <span className="ml-1 text-xs text-slate-400">(auto-calculated)</span>}
                                    </Label>
                                    <Input
                                        id="price"
                                        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 htmlFor="cost_price">Cost Price (৳)</Label>
                                    <Input id="cost_price" type="number" step="0.01" value={data.cost_price} onChange={(e) => setData('cost_price', e.target.value)} />
                                    <InputError message={errors.cost_price} />
                                </div>
                                <div className="space-y-1.5">
                                    <Label htmlFor="stock_qty">Stock Quantity</Label>
                                    <Input id="stock_qty" type="number" value={data.stock_qty} onChange={(e) => setData('stock_qty', e.target.value)} />
                                </div>
                                <div className="space-y-1.5">
                                    <Label htmlFor="low_stock_alert">Low Stock Alert</Label>
                                    <Input id="low_stock_alert" 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)} placeholder="e.g. 1200" />
                                            </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 dark:border-violet-800 dark:bg-violet-950/30">
                                                <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>
                                                <span className="ml-2 rounded bg-red-100 px-1.5 py-0.5 text-xs font-bold text-red-600">
                                                    -{data.discount_type === 'percent' ? data.discount_value + '%' : Math.round(((Number(data.compare_price) - computedPrice) / Number(data.compare_price)) * 100) + '% OFF'}
                                                </span>
                                            </div>
                                        )}
                                        <div className="space-y-1.5">
                                            <Label>Discount Label <span className="text-xs text-slate-400">(optional badge)</span></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">
                                <div
                                    className="flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-slate-300 p-6 text-slate-500 transition hover:border-violet-400 hover:bg-violet-50/40 dark:border-slate-600 dark:hover:border-violet-500"
                                    onClick={() => fileRef.current?.click()}
                                >
                                    <ImagePlus size={28} className="text-violet-400" />
                                    <p className="text-sm font-medium">Click to upload images</p>
                                    <p className="text-xs text-slate-400">PNG, JPG, WEBP — max 2 MB each</p>
                                    <input ref={fileRef} type="file" accept="image/*" multiple className="hidden" onChange={(e) => addImages(e.target.files)} />
                                </div>
                                {previews.length > 0 && (
                                    <div className="grid grid-cols-4 gap-3 sm:grid-cols-6">
                                        {previews.map((src, idx) => (
                                            <div key={idx} className="group relative">
                                                <img src={src} alt="" className="h-20 w-full rounded-lg border border-slate-200 object-cover" />
                                                {idx === 0 && <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={() => removeImage(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 [keyof typeof data, string][]).map(([field, label]) => (
                                    <div key={field} className="flex items-center gap-2">
                                        <Checkbox
                                            id={field}
                                            checked={Boolean(data[field])}
                                            onCheckedChange={(v) => setData(field, Boolean(v))}
                                        />
                                        <Label htmlFor={field}>{label}</Label>
                                    </div>
                                ))}
                            </CardContent>
                        </Card>

                        <div className="rounded-lg border border-violet-200 bg-violet-50 p-4 dark:border-violet-800 dark:bg-violet-950/20">
                            <p className="text-xs text-violet-700 dark:text-violet-300">
                                This product will appear <strong>only</strong> on the Fragrance page, not in the general Products listing.
                            </p>
                        </div>

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