import React from 'react';
import { Head, useForm, Link, usePage } from '@inertiajs/react';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { Button } from "@/Components/ui/button";
import { Save, ArrowLeft, Loader2 } from "lucide-react";
import { toast } from 'sonner';
import { useTranslation } from '@/hooks/useTranslation';
import { PRODUCT_SECTIONS_REGISTRY } from './Registry';
import AiAssistantWindow from '@/Components/Ai/AiAssistantWindow';

export default function EditProduct({ product, categories, currencies }) {
    const { t } = useTranslation();
    const { appSettings } = usePage().props;

    const defaultCurrency = product.currency_code || currencies?.find(c => c.is_default)?.code || 'USD';

    const slashCommands = PRODUCT_SECTIONS_REGISTRY.map(sec => ({
        id: sec.id,
        label: t(sec.label),
        icon: sec.icon
    }));

    const mappedVariations = (product.variations || []).map(v => ({
        ...v,
        options: v.options.map(opt => ({
            ...opt,
            existing_image: opt.image_path || null,
            image: null,
            preview: null
        }))
    }));

    const { data, setData, post, processing, errors } = useForm({
        _method: 'POST',
        title: product.title,
        category_id: product.category_id.toString(),
        subcategory_id: product.subcategory_id ? product.subcategory_id.toString() : '',
        description: product.description || '',
        currency_code: defaultCurrency,
        price: product.original_price || product.price,
        stock: product.stock,
        moq: product.moq,
        existing_images: product.images ? product.images.map(img => img.id) : [], 
        images: [], 
        shipping_time: product.shipping_time || '', 
        delivery_via: product.delivery_via || '',
        refund_policy: product.refund_policy || '',
        customization_options: product.customization_options || [],
        specifications: product.specifications || [],
        variations: mappedVariations, 
        coupon_code: product.coupon_code || '',
        discount_percentage: product.discount_percentage || '',
        max_discount_percentage: product.max_discount_percentage || '',
        min_order_amount_for_discount: product.original_min_order_amount || product.min_order_amount_for_discount || '', 
        is_free_shipping: product.is_free_shipping || false,
        shipping_charge: product.original_shipping_charge || product.shipping_charge || '',
        shipping_charge_type: product.shipping_charge_type || 'flat_rate'
    });

    const handleAiUpdate = (updates) => {
        setData(prevData => ({
            ...prevData,
            ...updates
        }));
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        
        if (!data.title || !data.category_id || !data.price || !data.shipping_time) {
            toast.error(t("Please fill all required fields marked with *"));
            return;
        }

        if (data.existing_images.length === 0 && data.images.length === 0) {
            toast.error(t("Please have at least one product image."));
            return;
        }

        post(route('seller.products.update', product.id), {
            preserveScroll: true,
            onSuccess: () => toast.success(t("Product updated successfully!")),
            onError: () => toast.error(t("Failed to update product. Please check the form for errors."))
        });
    };

    return (
        <DashboardLayout mode="seller">
            <Head title={`${t('Edit')}: ${product.title}`} />

            {appSettings?.ai_product_assistant && (
                <AiAssistantWindow 
                    apiEndpoint={route('seller.ai.product_form')}
                    contextData={data} 
                    onDataUpdate={handleAiUpdate}
                    categories={categories}
                    currencies={currencies} 
                    slashCommands={slashCommands}
                    title={t("Product Co-Pilot")}
                    placeholder={t("Type '/' for commands...")}
                />
            )}

            <div className="max-w-5xl mx-auto pb-12 flex flex-col lg:flex-row gap-8 items-start">
                
                <div className="flex-1 w-full space-y-6">
                    <div className="flex items-center gap-3 mb-2">
                        <Button variant="ghost" size="icon" asChild className="rounded-full">
                            <Link href={route('seller.products.index')}>
                                <ArrowLeft className="w-5 h-5 rtl:rotate-180" />
                            </Link>
                        </Button>
                        <div>
                            <h1 className="text-2xl font-bold tracking-tight">{t('Edit Product')}</h1>
                            <p className="text-muted-foreground text-sm">
                                {t('Update details for')} {product.title}
                            </p>
                        </div>
                    </div>

                    <form id="product-edit-form" onSubmit={handleSubmit} className="space-y-6">
                        {PRODUCT_SECTIONS_REGISTRY.map((section) => {
                            const Component = section.Component;
                            return (
                                <div key={section.id} id={`section-${section.id}`} className="scroll-mt-24">
                                    <Component 
                                        data={data} 
                                        setData={setData} 
                                        errors={errors} 
                                        categories={categories}
                                        currencies={currencies}
                                        existingImages={product.images}
                                    />
                                </div>
                            );
                        })}
                    </form>
                </div>

                <div className="w-full lg:w-64 shrink-0 lg:sticky lg:top-24 hidden md:block">
                    <div className="p-4 border rounded-xl bg-card shadow-sm space-y-4">
                        <h3 className="font-bold text-sm uppercase tracking-wider text-muted-foreground mb-2">
                            {t('Navigation')}
                        </h3>
                        <nav className="flex flex-col gap-1">
                            {PRODUCT_SECTIONS_REGISTRY.map((section) => (
                                <button 
                                    key={section.id}
                                    type="button"
                                    onClick={() => document.getElementById(`section-${section.id}`)?.scrollIntoView({ behavior: 'smooth' })}
                                    className="flex items-center gap-3 px-3 py-2 text-sm font-medium rounded-md hover:bg-muted text-left text-muted-foreground hover:text-foreground transition-colors"
                                >
                                    <section.icon className="w-4 h-4" />
                                    {t(section.label)}
                                </button>
                            ))}
                        </nav>

                        <div className="pt-4 border-t mt-4">
                            <Button 
                                type="submit" 
                                form="product-edit-form" 
                                disabled={processing} 
                                className="w-full gap-2 bg-blue-600 hover:bg-blue-700 text-white"
                            >
                                {processing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                                {t('Save Changes')}
                            </Button>
                        </div>
                    </div>
                </div>
                
                <div className="fixed bottom-4 right-4 left-4 md:hidden z-40">
                     <Button 
                        type="submit" 
                        form="product-edit-form" 
                        disabled={processing} 
                        size="lg"
                        className="w-full gap-2 bg-blue-600 hover:bg-blue-700 text-white shadow-xl"
                    >
                        {processing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                        {t('Save Changes')}
                    </Button>
                </div>

            </div>
        </DashboardLayout>
    );
}