import React, { useEffect, useState } from 'react';
import { Head, useForm, usePage, router } from '@inertiajs/react';
import { toast } from 'sonner';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { Card, CardContent, CardHeader, CardTitle } from "@/Components/ui/card";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { Button } from "@/Components/ui/button";
import { Switch } from "@/Components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Save, Loader2, Building2, MessageSquareHeart, Globe, PackageSearch, Users, CalendarDays, Link as LinkIcon, Camera, Tag } from "lucide-react";
import { useTranslation } from '@/hooks/useTranslation';
import ImageCropper from '@/Components/ImageCropper';

export default function StoreProfile() {
    const { auth, flash } = usePage().props;
    const { t } = useTranslation();
    const user = auth.user;
    
    const baseUrl = typeof window !== 'undefined' ? window.location.origin : '';

    const defaultOptions = {
        web_chat: true, email: true, phone: false, whatsapp: false, messenger: false
    };

    const { data, setData, post, processing, errors } = useForm({
        _method: 'PUT', // Spoofed for ModSecurity
        store_slug: user.store_slug || user.username || '', 
        company_name: user.company_name || '',
        main_products: user.main_products || '', 
        business_type: user.business_type || '',
        established_year: user.established_year || '',
        total_employees: user.total_employees || '', 
        company_overview: user.company_overview || '',
        flash_sale_percentage: user.flash_sale_percentage || '', // <-- ADDED FLASH SALE PERCENTAGE
        contact_email: user.contact_email || user.email || '',
        contact_phone: user.contact_phone || '',
        contact_whatsapp: user.contact_whatsapp || '',
        contact_messenger: user.contact_messenger || '',
        contact_options: user.contact_options || defaultOptions,
    });

    const [cropperOpen, setCropperOpen] = useState(false);
    const [cropperConfig, setCropperConfig] = useState({ aspectRatio: 1, type: 'store_avatar' });
    const [loadingType, setLoadingType] = useState(null);

    useEffect(() => {
        if (flash?.success) toast.success(t(flash.success));
    }, [flash]);

    const handleSubmit = (e) => {
        e.preventDefault();
        post(route('seller.store-profile.update'), { 
            preserveScroll: true,
            onSuccess: () => toast.success(t("Store profile updated successfully!"))
        });
    };

    const toggleOption = (key) => {
        setData('contact_options', { ...data.contact_options, [key]: !data.contact_options[key] });
    };

    // --- Handlers for Cropper ---
    const openCropper = (type) => {
        const config = type === 'store_avatar' 
            ? { aspectRatio: 1, type: 'store_avatar' }
            : { aspectRatio: 16 / 5, type: 'store_cover' };
        setCropperConfig(config);
        setCropperOpen(true);
    };

    const handleSaveCrop = (blob) => {
        const formData = new FormData();
        formData.append('photo', blob, `${cropperConfig.type}.jpg`);
        formData.append('type', cropperConfig.type);

        setLoadingType(cropperConfig.type);

        router.post(route('seller.store-profile.photo'), formData, {
            preserveScroll: true,
            onFinish: () => setLoadingType(null),
            forceFormData: true,
            onSuccess: (page) => {
                toast.success(t(page.props.flash?.success || "Store photo updated successfully!"));
            },
            onError: () => {
                toast.error(t('Failed to upload image. Please try again.'));
            }
        });
    };

    const avatarUrl = user.store_avatar_path 
        ? `/storage/${user.store_avatar_path}?v=${new Date().getTime()}` 
        : user.avatar_path 
            ? `/storage/${user.avatar_path}?v=${new Date().getTime()}` 
            : null;

    const coverUrl = user.store_cover_path 
        ? `/storage/${user.store_cover_path}?v=${new Date().getTime()}` 
        : user.cover_path 
            ? `/storage/${user.cover_path}?v=${new Date().getTime()}` 
            : null;

    return (
        <DashboardLayout mode="seller">
            <Head title={t('Store Profile Settings')} />

            <ImageCropper 
                open={cropperOpen}
                onOpenChange={setCropperOpen}
                onSave={handleSaveCrop}
                aspectRatio={cropperConfig.aspectRatio}
            />

            <div className="max-w-5xl mx-auto pb-12 space-y-6">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight text-foreground">{t('Official Store Profile')}</h1>
                        <p className="text-muted-foreground text-sm">{t('Manage your business identity and store URL.')}</p>
                    </div>
                    <Button variant="outline" asChild className="rounded-full shadow-sm">
                        <a href={route('store.view', user.store_slug || user.username || '')} target="_blank" rel="noreferrer">
                            <Globe className="w-4 h-4 mr-2" /> {t('View Public Store')}
                        </a>
                    </Button>
                </div>

                <form onSubmit={handleSubmit} className="space-y-6">
                    
                    {/* PHOTO UPLOAD CARD */}
                    <div className="relative rounded-3xl mb-6 shadow-sm border border-border/50 bg-card overflow-hidden">
                        <div 
                            className="group/cover h-40 sm:h-64 w-full bg-muted bg-cover bg-center relative transition-all" 
                            style={{ backgroundImage: coverUrl ? `url(${coverUrl})` : 'linear-gradient(to right, #0f172a, #334155)' }}
                        >
                            <div className="absolute inset-0 bg-black/40 opacity-0 group-hover/cover:opacity-100 transition-opacity flex items-center justify-center">
                                <Button 
                                    type="button"
                                    variant="secondary" 
                                    size="sm" 
                                    className="gap-2 shadow-lg rounded-full"
                                    onClick={() => openCropper('store_cover')}
                                    disabled={loadingType === 'store_cover'}
                                >
                                    {loadingType === 'store_cover' 
                                        ? <Loader2 className="w-4 h-4 animate-spin" /> 
                                        : <><Camera className="w-4 h-4" /> <span>{t('Change Store Cover')}</span></>
                                    }
                                </Button>
                            </div>
                        </div>
                        
                        <div className="px-6 pb-6 pt-0 flex gap-6 -mt-12 sm:-mt-16 relative z-10">
                            <div className="relative group/avatar shrink-0 z-20">
                                <div className="w-24 h-24 sm:w-32 sm:h-32 rounded-2xl border-4 border-card bg-white shadow-xl overflow-hidden flex items-center justify-center">
                                    {avatarUrl ? <img src={avatarUrl} className="w-full h-full object-cover" alt="Store Avatar" /> : <Building2 className="w-10 h-10 text-muted-foreground/30" />}
                                </div>
                                <button 
                                    type="button"
                                    className="absolute inset-0 bg-black/60 flex items-center justify-center opacity-0 group-hover/avatar:opacity-100 transition-opacity cursor-pointer rounded-2xl border-4 border-transparent"
                                    onClick={() => openCropper('store_avatar')}
                                    disabled={loadingType === 'store_avatar'}
                                >
                                    {loadingType === 'store_avatar' 
                                        ? <Loader2 className="w-6 h-6 text-white animate-spin" />
                                        : <Camera className="w-6 h-6 text-white" />
                                    }
                                </button>
                            </div>
                        </div>
                    </div>

                    <Card className="shadow-sm border-border/50">
                        <CardHeader className="border-b bg-muted/10">
                            <CardTitle className="flex items-center gap-2 text-lg text-primary">
                                <Building2 className="w-5 h-5" /> {t('Basic Company Information')}
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-6 pt-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div className="space-y-2 md:col-span-2">
                                    <Label className="font-bold flex items-center gap-2">
                                        <LinkIcon className="w-4 h-4 text-muted-foreground" /> {t('Store Profile URL')} <span className="text-red-500">*</span>
                                    </Label>
                                    <div className="flex flex-col sm:flex-row sm:items-center rounded-md border border-input bg-muted/30 overflow-hidden focus-within:ring-1 focus-within:ring-primary focus-within:border-primary transition-all">
                                        <span className="px-3 py-2 sm:py-0 text-muted-foreground text-sm border-b sm:border-b-0 sm:border-r select-none shrink-0">
                                            {baseUrl}/store/
                                        </span>
                                        <Input 
                                            value={data.store_slug} 
                                            onChange={e => setData('store_slug', e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, ''))} 
                                            placeholder={t('your-brand-name')}
                                            className="border-0 focus-visible:ring-0 rounded-none bg-background shadow-none h-10 font-mono font-medium"
                                        />
                                    </div>
                                    {errors.store_slug ? (
                                        <p className="text-xs text-red-500 font-medium">{t(errors.store_slug)}</p>
                                    ) : (
                                        <p className="text-xs text-muted-foreground">{t('This is your unique store link. Letters, numbers, hyphens (-), and underscores (_) only.')}</p>
                                    )}
                                </div>

                                <div className="space-y-2">
                                    <Label className="font-bold flex items-center gap-2">{t('Company Display Name')} <span className="text-red-500">*</span></Label>
                                    <Input 
                                        value={data.company_name} 
                                        onChange={e => setData('company_name', e.target.value)} 
                                        placeholder={t('Legal Company Name')} 
                                    />
                                    {errors.company_name && <p className="text-xs text-red-500">{t(errors.company_name)}</p>}
                                </div>

                                <div className="space-y-2">
                                    <Label className="font-bold flex items-center gap-2"><PackageSearch className="w-4 h-4 text-muted-foreground" /> {t('Main Products')}</Label>
                                    <Input 
                                        value={data.main_products} 
                                        onChange={e => setData('main_products', e.target.value)} 
                                        placeholder={t('e.g. Wireless Audio, Smart Home devices')} 
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label className="font-bold">{t('Business Type')}</Label>
                                    <Input 
                                        value={data.business_type} 
                                        onChange={e => setData('business_type', e.target.value)} 
                                        placeholder={t('e.g. Manufacturer, Trading Company')} 
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label className="font-bold flex items-center gap-2"><CalendarDays className="w-4 h-4 text-muted-foreground" /> {t('Year Established')}</Label>
                                    <Input 
                                        type="number" 
                                        value={data.established_year} 
                                        onChange={e => setData('established_year', e.target.value)} 
                                        placeholder={t('e.g. 2010')} 
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label className="font-bold flex items-center gap-2"><Users className="w-4 h-4 text-muted-foreground" /> {t('Total Employees')}</Label>
                                    <Select value={data.total_employees} onValueChange={(val) => setData('total_employees', val)}>
                                        <SelectTrigger>
                                            <SelectValue placeholder={t('Select staff count')} />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="1-10 People">{t('1-10 People')}</SelectItem>
                                            <SelectItem value="11-50 People">{t('11-50 People')}</SelectItem>
                                            <SelectItem value="51-200 People">{t('51-200 People')}</SelectItem>
                                            <SelectItem value="201-500 People">{t('201-500 People')}</SelectItem>
                                            <SelectItem value="500+ People">{t('500+ People')}</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>

                            <div className="space-y-2 pt-2">
                                <Label className="font-bold">{t('Company Overview (Detailed Description)')}</Label>
                                <Textarea 
                                    value={data.company_overview} 
                                    onChange={e => setData('company_overview', e.target.value)} 
                                    placeholder={t('Tell buyers about your history, production lines, and quality certifications...')} 
                                    className="min-h-[180px] resize-y" 
                                />
                            </div>
                        </CardContent>
                    </Card>

                    {/* --- NEW: GLOBAL FLASH SALE CARD --- */}
                    <Card className="shadow-sm border-red-500/20 bg-red-500/5">
                        <CardHeader className="border-b border-red-500/10 pb-4">
                            <CardTitle className="flex items-center gap-2 text-lg text-red-600">
                                <Tag className="w-5 h-5" /> {t('Store-Wide Flash Sale')}
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="pt-6">
                            <div className="space-y-2 max-w-sm">
                                <Label className="font-bold text-red-700">{t('Global Discount Percentage (%)')}</Label>
                                <Input 
                                    type="number"
                                    min="0"
                                    max="100"
                                    value={data.flash_sale_percentage} 
                                    onChange={e => setData('flash_sale_percentage', e.target.value)} 
                                    placeholder={t('e.g., 20')} 
                                    className="bg-background border-red-500/30"
                                />
                                <p className="text-xs text-red-600/80 mt-1">
                                    {t('Set to 0 to disable. This will securely apply this discount to ALL your products globally.')}
                                </p>
                            </div>
                            {errors.flash_sale_percentage && <p className="text-xs text-red-500 mt-1">{t(errors.flash_sale_percentage)}</p>}
                        </CardContent>
                    </Card>

                    <Card className="shadow-sm border-border/50">
                        <CardHeader className="border-b bg-muted/10">
                            <CardTitle className="flex items-center gap-2 text-lg text-primary">
                                <MessageSquareHeart className="w-5 h-5" /> {t('Communication Channels')}
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-6 pt-6">
                            <div className="flex items-center justify-between p-4 border rounded-xl bg-primary/5 border-primary/20">
                                <div>
                                    <Label className="text-base font-bold">{t('Platform Web Chat')}</Label>
                                    <p className="text-xs text-muted-foreground">{t('Allow buyers to send instant messages via this website.')}</p>
                                </div>
                                <Switch checked={data.contact_options.web_chat} onCheckedChange={() => toggleOption('web_chat')} />
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div className="space-y-3 p-4 border rounded-xl bg-card">
                                    <div className="flex items-center justify-between mb-2">
                                        <Label className="font-bold">{t('Public Email')}</Label>
                                        <Switch checked={data.contact_options.email} onCheckedChange={() => toggleOption('email')} />
                                    </div>
                                    <Input 
                                        type="email" 
                                        value={data.contact_email} 
                                        onChange={e => setData('contact_email', e.target.value)} 
                                        disabled={!data.contact_options.email}
                                    />
                                </div>

                                <div className="space-y-3 p-4 border rounded-xl bg-card">
                                    <div className="flex items-center justify-between mb-2">
                                        <Label className="font-bold">{t('Phone Number')}</Label>
                                        <Switch checked={data.contact_options.phone} onCheckedChange={() => toggleOption('phone')} />
                                    </div>
                                    <Input 
                                        type="tel" 
                                        value={data.contact_phone} 
                                        onChange={e => setData('contact_phone', e.target.value)} 
                                        placeholder="+1..."
                                        disabled={!data.contact_options.phone}
                                    />
                                </div>

                                <div className="space-y-3 p-4 border rounded-xl bg-card border-green-500/10">
                                    <div className="flex items-center justify-between mb-2">
                                        <Label className="font-bold text-green-600">{t('WhatsApp')}</Label>
                                        <Switch checked={data.contact_options.whatsapp} onCheckedChange={() => toggleOption('whatsapp')} />
                                    </div>
                                    <Input 
                                        value={data.contact_whatsapp} 
                                        onChange={e => setData('contact_whatsapp', e.target.value)} 
                                        placeholder={t('Format: 88017000...')} 
                                        disabled={!data.contact_options.whatsapp}
                                    />
                                </div>

                                <div className="space-y-3 p-4 border rounded-xl bg-card border-blue-500/10">
                                    <div className="flex items-center justify-between mb-2">
                                        <Label className="font-bold text-blue-600">{t('Messenger')}</Label>
                                        <Switch checked={data.contact_options.messenger} onCheckedChange={() => toggleOption('messenger')} />
                                    </div>
                                    <Input 
                                        value={data.contact_messenger} 
                                        onChange={e => setData('contact_messenger', e.target.value)} 
                                        placeholder="https://m.me/..." 
                                        disabled={!data.contact_options.messenger}
                                    />
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Button 
                        type="submit" 
                        disabled={processing} 
                        size="lg"
                        className="w-full sm:w-auto gap-2 px-10 font-bold shadow-lg"
                    >
                        {processing ? <Loader2 className="w-5 h-5 animate-spin" /> : <Save className="w-5 h-5" />}
                        {t('Save Official Profile')}
                    </Button>
                </form>
            </div>
        </DashboardLayout>
    );
}