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 VariantBuilder, { type VariantRow } from '@/components/variant-builder';
import AdminLayout from '@/layouts/admin-layout';
import { type Brand, type Category } from '@/types';

interface Attribute {
    id: number;
    name: string;
    slug: string;
    values: { id: number; value: string; slug: string }[];
}

export default function AdminProductCreate({ categories, brands, attributes }: { categories: Category[]; brands: Brand[]; attributes: Attribute[] }) {
    const { data, setData, post, processing, errors } = useForm<any>({
        name: '',
        category_id: '',
        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_trending: false,
        is_new_arrival: false,
        status: true,
        meta_title: '',
        meta_description: '',
        images: [] as File[],
        variants: [] as VariantRow[],
    });

    const [hasVariants, setHasVariants] = useState(false);
    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.products.store'), { forceFormData: true });
    };

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

            <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">Product 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="Product name" />
                                    <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>Category *</Label>
                                        <Select value={data.category_id} onValueChange={(v) => setData('category_id', v)}>
                                            <SelectTrigger aria-label="Category"><SelectValue placeholder="Select category" /></SelectTrigger>
                                            <SelectContent>
                                                {categories.map((c) => <SelectItem key={c.id} value={String(c.id)}>{c.name}</SelectItem>)}
                                            </SelectContent>
                                        </Select>
                                        <InputError message={errors.category_id} />
                                    </div>
                                </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 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="Brief product summary…"
                                    />
                                </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 product description…"
                                    />
                                </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)} />
                                </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-indigo-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 htmlFor="compare_price">Original Price / MRP (৳)</Label>
                                                <Input
                                                    id="compare_price"
                                                    type="number"
                                                    step="0.01"
                                                    value={data.compare_price}
                                                    onChange={(e) => setData('compare_price', e.target.value)}
                                                    placeholder="e.g. 1200"
                                                />
                                                <InputError message={errors.compare_price} />
                                            </div>
                                            <div className="space-y-1.5">
                                                <Label htmlFor="discount_value">
                                                    Discount {data.discount_type === 'percent' ? '(%)' : '(৳)'}
                                                </Label>
                                                <Input
                                                    id="discount_value"
                                                    type="number"
                                                    step="0.01"
                                                    value={data.discount_value}
                                                    onChange={(e) => setData('discount_value', e.target.value)}
                                                    placeholder={data.discount_type === 'percent' ? 'e.g. 20' : 'e.g. 200'}
                                                />
                                                <InputError message={errors.discount_value} />
                                            </div>
                                        </div>

                                        {computedPrice !== null && (
                                            <div className="flex items-center gap-3 rounded-lg border border-green-200 bg-green-50 px-4 py-3 dark:border-green-800 dark:bg-green-950/30">
                                                <div className="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-green-700">৳{computedPrice.toLocaleString()}</span>
                                                    {data.discount_type === 'percent' ? (
                                                        <span className="ml-2 rounded bg-red-100 px-1.5 py-0.5 text-xs font-bold text-red-600">-{data.discount_value}%</span>
                                                    ) : (
                                                        <span className="ml-2 rounded bg-red-100 px-1.5 py-0.5 text-xs font-bold text-red-600">
                                                            -{Math.round(((Number(data.compare_price) - computedPrice) / Number(data.compare_price)) * 100)}% OFF
                                                        </span>
                                                    )}
                                                </div>
                                            </div>
                                        )}

                                        <div className="space-y-1.5">
                                            <Label htmlFor="discount_label">
                                                Discount Label <span className="text-xs text-slate-400">(optional — shown as badge)</span>
                                            </Label>
                                            <Input
                                                id="discount_label"
                                                value={data.discount_label}
                                                onChange={(e) => setData('discount_label', e.target.value)}
                                                placeholder="e.g. Eid Special, Summer Sale"
                                                maxLength={50}
                                            />
                                            <InputError message={errors.discount_label} />
                                        </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 htmlFor="discount_starts_at" className="text-xs text-slate-500">Start Date</Label>
                                                    <Input
                                                        id="discount_starts_at"
                                                        type="datetime-local"
                                                        value={data.discount_starts_at}
                                                        onChange={(e) => setData('discount_starts_at', e.target.value)}
                                                    />
                                                    <InputError message={errors.discount_starts_at} />
                                                </div>
                                                <div className="space-y-1">
                                                    <Label htmlFor="discount_ends_at" className="text-xs text-slate-500">End Date</Label>
                                                    <Input
                                                        id="discount_ends_at"
                                                        type="datetime-local"
                                                        value={data.discount_ends_at}
                                                        onChange={(e) => setData('discount_ends_at', e.target.value)}
                                                    />
                                                    <InputError message={errors.discount_ends_at} />
                                                </div>
                                            </div>
                                            {data.discount_starts_at && data.discount_ends_at && (
                                                <p className="text-xs text-slate-500">
                                                    Discount active from {new Date(data.discount_starts_at).toLocaleString()} to {new Date(data.discount_ends_at).toLocaleString()}
                                                </p>
                                            )}
                                        </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-indigo-400 hover:bg-indigo-50/40 dark:border-slate-600 dark:hover:border-indigo-500"
                                    onClick={() => fileRef.current?.click()}
                                >
                                    <ImagePlus size={28} className="text-indigo-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-indigo-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>

                        {/* Variants */}
                        <Card>
                            <CardHeader>
                                <div className="flex items-center justify-between">
                                    <CardTitle className="text-base">Product Variants</CardTitle>
                                    <div className="flex items-center gap-2">
                                        <Checkbox
                                            id="has_variants"
                                            checked={hasVariants}
                                            onCheckedChange={(v) => {
                                                setHasVariants(Boolean(v));
                                                if (!v) setData('variants', []);
                                            }}
                                        />
                                        <Label htmlFor="has_variants" className="cursor-pointer text-sm">
                                            Has Variants (size, color…)
                                        </Label>
                                    </div>
                                </div>
                            </CardHeader>
                            {hasVariants && (
                                <CardContent>
                                    <VariantBuilder
                                        attributes={attributes}
                                        variants={data.variants as VariantRow[]}
                                        onChange={(rows) => setData('variants', rows)}
                                        basePrice={data.price}
                                    />
                                </CardContent>
                            )}
                        </Card>

                        {/* SEO */}
                        <Card>
                            <CardHeader><CardTitle className="text-base">SEO</CardTitle></CardHeader>
                            <CardContent className="space-y-4">
                                <div className="space-y-1.5">
                                    <Label htmlFor="meta_title">Meta Title</Label>
                                    <Input id="meta_title" value={data.meta_title} onChange={(e) => setData('meta_title', e.target.value)} />
                                </div>
                                <div className="space-y-1.5">
                                    <Label htmlFor="meta_description">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">Status & Flags</CardTitle></CardHeader>
                            <CardContent className="space-y-3">
                                {([
                                    ['status', 'Active'],
                                    ['is_featured', 'Featured'],
                                    ['is_best_seller', 'Best Seller'],
                                    ['is_trending', 'Trending'],
                                    ['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>

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