import React, { useState } from 'react';
import { Head, Link, router, usePage } from '@inertiajs/react';
import { toast } from 'sonner';
import UserLayout from '@/Layouts/UserLayout';
import { Card, CardContent } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { 
    Star, MessageSquare, MapPin, Building2, Package, 
    Users, PackageSearch, CalendarDays, Zap, TrendingUp, Camera, Loader2
} from "lucide-react";
import ContactModal from '@/Components/ContactModal';
import ImageCropper from '@/Components/ImageCropper';
import ProductCard from '@/Components/ProductCard'; // <-- REUSABLE COMPONENT IMPORTED
import { useTranslation } from '@/hooks/useTranslation';

export default function StoreView({ seller, products, reviewStats, currentTab, tabCounts }) {
    const { auth } = usePage().props;
    const { t } = useTranslation();
    const isOwner = auth.user?.id === seller?.id;

    const [isContactOpen, setIsContactOpen] = useState(false);
    
    // --- Image Cropper State ---
    const [cropperOpen, setCropperOpen] = useState(false);
    const [cropperConfig, setCropperConfig] = useState({ aspectRatio: 1, type: 'store_avatar' });
    const [loadingType, setLoadingType] = useState(null);

    // Fallback Logic: Tries to load specific store photo, if missing, falls back to User profile photo.
    const avatarUrl = seller.store_avatar_path 
        ? `/storage/${seller.store_avatar_path}?v=${new Date().getTime()}` 
        : seller.avatar_path 
            ? `/storage/${seller.avatar_path}?v=${new Date().getTime()}` 
            : null;

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

    const companyName = seller.company_name || seller.name;

    const changeTab = (tab) => {
        router.get(route('store.view', seller.store_slug || seller.username), { tab }, { preserveScroll: true });
    };

    // --- 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.'));
            }
        });
    };

    return (
        <UserLayout>
            <Head title={`${companyName} - ${t('Official Store')}`} />

            <ContactModal isOpen={isContactOpen} onClose={() => setIsContactOpen(false)} seller={seller} />
            
            <ImageCropper 
                open={cropperOpen}
                onOpenChange={setCropperOpen}
                onSave={handleSaveCrop}
                aspectRatio={cropperConfig.aspectRatio}
            />

            <div className="relative rounded-3xl mb-10 shadow-sm border border-border/50 bg-card overflow-hidden">
                {/* COVER PHOTO WITH HOVER UPLOAD STATE */}
                <div 
                    className="group/cover h-48 md:h-80 w-full bg-muted bg-cover bg-center relative transition-all" 
                    style={{ backgroundImage: coverUrl ? `url(${coverUrl})` : 'linear-gradient(to right, #0f172a, #334155)' }}
                >
                    {isOwner && (
                        <div className="absolute inset-0 bg-black/40 opacity-0 group-hover/cover:opacity-100 transition-opacity flex items-center justify-center">
                            <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 md:px-10 pb-8 pt-4 flex flex-col md:flex-row gap-6 md:items-end -mt-16 md:-mt-24 relative z-10">
                    <div className="relative group/avatar shrink-0 z-20">
                        <div className="w-32 h-32 md:w-44 md:h-44 rounded-3xl border-8 border-card bg-white shadow-2xl overflow-hidden flex items-center justify-center">
                            {avatarUrl ? <img src={avatarUrl} className="w-full h-full object-cover" alt={companyName} /> : <Building2 className="w-16 h-16 text-muted-foreground/20" />}
                        </div>
                        
                        {isOwner && (
                            <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-3xl border-8 border-transparent"
                                onClick={() => openCropper('store_avatar')}
                                disabled={loadingType === 'store_avatar'}
                            >
                                {loadingType === 'store_avatar' 
                                    ? <Loader2 className="w-8 h-8 text-white animate-spin" />
                                    : <Camera className="w-8 h-8 text-white" />
                                }
                            </button>
                        )}
                    </div>
                    
                    <div className="flex-1 pb-2">
                        <div className="flex flex-wrap items-center gap-3 mb-3">
                            <h1 className="text-3xl md:text-5xl font-black tracking-tight text-foreground">{companyName}</h1>
                        </div>
                        <div className="flex flex-wrap gap-6 text-sm font-bold text-muted-foreground">
                            {seller.country && (
                                <span className="flex items-center gap-1.5">
                                    <MapPin className="w-5 h-5 text-primary" /> {seller.country.name}
                                </span>
                            )}
                            <span className="flex items-center gap-1.5 text-amber-500">
                                <Star className="w-5 h-5 fill-amber-500" /> 
                                {reviewStats.avg} ({t(':total Reviews', { total: reviewStats.total })})
                            </span>
                        </div>
                    </div>

                    <div className="flex gap-3 pb-2 w-full md:w-auto">
                        {!isOwner && (
                            <Button size="xl" className="flex-1 md:flex-none rounded-full px-10 font-black gap-2 shadow-xl shadow-primary/20 text-base h-14 animate-in fade-in" onClick={() => setIsContactOpen(true)}>
                                <MessageSquare className="w-6 h-6" /> {t('Contact Supplier')}
                            </Button>
                        )}
                    </div>
                </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
                <div className="lg:col-span-8 space-y-12 order-2 lg:order-1">
                    <section>
                        <h3 className="text-2xl font-black flex items-center gap-3 mb-6">
                            <Package className="w-8 h-8 text-primary" /> {t('Product Showroom')}
                        </h3>
                        
                        <div className="flex items-center gap-6 mb-6 border-b border-border/60 overflow-x-auto no-scrollbar">
                            <button 
                                onClick={() => changeTab('latest')}
                                className={`pb-3 font-bold border-b-2 text-sm uppercase tracking-wider whitespace-nowrap transition-colors flex items-center gap-1.5 ${currentTab === 'latest' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}
                            >
                                <Zap className={`w-4 h-4 ${currentTab === 'latest' ? 'text-primary' : 'text-orange-500'}`} /> 
                                {t('New Arrivals')} ({tabCounts.latest})
                            </button>

                            <button 
                                onClick={() => changeTab('popular')}
                                className={`pb-3 font-bold border-b-2 text-sm uppercase tracking-wider whitespace-nowrap transition-colors flex items-center gap-1.5 ${currentTab === 'popular' ? 'border-blue-500 text-blue-500' : 'border-transparent text-muted-foreground hover:text-blue-500'}`}
                            >
                                <TrendingUp className={`w-4 h-4 ${currentTab === 'popular' ? 'text-blue-500' : 'text-muted-foreground'}`} /> 
                                {t('Popular')} ({tabCounts.popular})
                            </button>

                            <button 
                                onClick={() => changeTab('featured')}
                                className={`pb-3 font-bold border-b-2 text-sm uppercase tracking-wider whitespace-nowrap transition-colors flex items-center gap-1.5 ${currentTab === 'featured' ? 'border-amber-500 text-amber-500' : 'border-transparent text-muted-foreground hover:text-amber-500'}`}
                            >
                                <Star className={`w-4 h-4 ${currentTab === 'featured' ? 'fill-amber-500' : ''}`} /> 
                                {t('Featured')} ({tabCounts.featured})
                            </button>
                        </div>

                        {/* --- REUSABLE PRODUCT CARD GRID --- */}
                        <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-5">
                            {products.data.map((item) => (
                                <ProductCard key={item.id} product={item} />
                            ))}
                        </div>

                        {products.data.length === 0 && (
                            <div className="text-center py-20 bg-card border border-dashed rounded-xl text-muted-foreground">
                                <PackageSearch className="w-12 h-12 mx-auto mb-3 opacity-20" />
                                <p className="font-bold">{t('No products found in this category.')}</p>
                            </div>
                        )}

                        {products.links && products.links.length > 3 && (
                            <div className="flex justify-center items-center mt-10">
                                <div className="flex gap-1 overflow-x-auto no-scrollbar pb-2">
                                    {products.links.map((link, i) => (
                                        <Link
                                            key={i} href={link.url || '#'}
                                            className={`px-4 py-2 border rounded-lg text-sm font-bold transition-colors ${
                                                link.active 
                                                    ? 'bg-primary text-primary-foreground border-primary shadow-md' 
                                                    : 'bg-background hover:bg-muted text-foreground'
                                            } ${!link.url && 'opacity-50 cursor-not-allowed'}`}
                                            dangerouslySetInnerHTML={{ __html: link.label }}
                                        />
                                    ))}
                                </div>
                            </div>
                        )}
                    </section>
                </div>

                <div className="lg:col-span-4 space-y-8 order-1 lg:order-2">
                    <section className="sticky top-24">
                        <h3 className="text-2xl font-black mb-6 flex items-center gap-3">
                            <Building2 className="w-8 h-8 text-primary" /> {t('About the Company')}
                        </h3>
                        <Card className="border-border/50 shadow-sm bg-card overflow-hidden">
                            <CardContent className="p-6 md:p-8">
                                <p className="text-sm leading-relaxed text-foreground/80 whitespace-pre-wrap mb-8">
                                    {seller.company_overview || t('No overview provided.')}
                                </p>
                                
                                <div className="grid grid-cols-2 gap-6 pt-6 border-t border-border/50">
                                    <div className="space-y-1">
                                        <h4 className="text-[10px] uppercase tracking-widest font-black text-muted-foreground flex items-center gap-1.5"><PackageSearch className="w-3 h-3"/> {t('Main Products')}</h4>
                                        <p className="font-bold text-sm text-foreground">{seller.main_products || t('General')}</p>
                                    </div>
                                    <div className="space-y-1">
                                        <h4 className="text-[10px] uppercase tracking-widest font-black text-muted-foreground flex items-center gap-1.5"><Building2 className="w-3 h-3"/> {t('Business Type')}</h4>
                                        <p className="font-bold text-sm text-foreground">{seller.business_type || t('Manufacturer')}</p>
                                    </div>
                                    <div className="space-y-1">
                                        <h4 className="text-[10px] uppercase tracking-widest font-black text-muted-foreground flex items-center gap-1.5"><CalendarDays className="w-3 h-3"/> {t('Established')}</h4>
                                        <p className="font-bold text-sm text-foreground">{seller.established_year || 'N/A'}</p>
                                    </div>
                                    <div className="space-y-1">
                                        <h4 className="text-[10px] uppercase tracking-widest font-black text-muted-foreground flex items-center gap-1.5"><Users className="w-3 h-3"/> {t('Staff Size')}</h4>
                                        <p className="font-bold text-sm text-foreground">{seller.total_employees || 'N/A'}</p>
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    </section>
                </div>
            </div>
        </UserLayout>
    );
}