'use client';

import { useState, useCallback, useEffect, useRef } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from '@/components/ui/tabs';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { useToast } from '@/hooks/use-toast';
import {
  ArrowLeft,
  Plus,
  ShoppingBag,
  Eye,
  EyeOff,
  Edit3,
  Trash2,
  Upload,
  BarChart3,
  Phone,
  Package,
  TrendingUp,
  AlertTriangle,
  ImagePlus,
  X,
} from 'lucide-react';

// ─── Interfaces ─────────────────────────────────────────────────
interface DbProduct {
  id: string;
  title: string;
  description: string;
  price: number;
  discount: number;
  category: string;
  subcategory: string | null;
  images: string;
  stock: number;
  unit: string | null;
  contactNumber: string | null;
  amenities: string;
  isAvailable: boolean;
  sellerId: string;
  createdAt: string;
  seller: { id: string; name: string; phone: string | null; avatar: string | null };
}

// ─── Category options ───────────────────────────────────────────
const categories = [
  { value: 'daily_needs', labelEn: 'Daily Needs', labelBn: 'দৈনন্দিন পণ্য' },
  { value: 'electronics', labelEn: 'Electronics', labelBn: 'ইলেকট্রনিক্স' },
  { value: 'fashion', labelEn: 'Fashion', labelBn: 'ফ্যাশন' },
  { value: 'food', labelEn: 'Food', labelBn: 'খাদ্য' },
  { value: 'health', labelEn: 'Health', labelBn: 'স্বাস্থ্য' },
  { value: 'education', labelEn: 'Education', labelBn: 'শিক্ষা' },
  { value: 'home', labelEn: 'Home & Living', labelBn: 'ঘর ও জীবন' },
  { value: 'others', labelEn: 'Others', labelBn: 'অন্যান্য' },
];

const units = [
  { value: 'piece', labelEn: 'Piece', labelBn: 'পিস' },
  { value: 'kg', labelEn: 'Kg', labelBn: 'কেজি' },
  { value: 'liter', labelEn: 'Liter', labelBn: 'লিটার' },
  { value: 'dozen', labelEn: 'Dozen', labelBn: 'ডজন' },
  { value: 'pack', labelEn: 'Pack', labelBn: 'প্যাক' },
];

// ─── Image Upload Component ─────────────────────────────────────
function ImageUploader({
  language,
  images,
  onImagesChange,
}: {
  language: 'en' | 'bn';
  images: string[];
  onImagesChange: (imgs: string[]) => void;
}) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [urlInput, setUrlInput] = useState('');
  const [isUploading, setIsUploading] = useState(false);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;
    setIsUploading(true);
    try {
      const newImages: string[] = [...images];
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        if (file.size > 5 * 1024 * 1024) continue;
        const reader = new FileReader();
        const dataUrl = await new Promise<string>((resolve) => {
          reader.onload = () => resolve(reader.result as string);
          reader.readAsDataURL(file);
        });
        newImages.push(dataUrl);
      }
      onImagesChange(newImages);
    } finally {
      setIsUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const handleAddUrl = () => {
    if (urlInput.trim()) {
      onImagesChange([...images, urlInput.trim()]);
      setUrlInput('');
    }
  };

  const handleRemoveImage = (index: number) => {
    onImagesChange(images.filter((_, i) => i !== index));
  };

  return (
    <div className="space-y-3">
      <Label className="text-xs font-medium">
        <span className="flex items-center gap-1">
          <ImagePlus className="h-3 w-3" />
          {language === 'en' ? 'Product Photos' : 'পণ্যের ছবি'}
        </span>
      </Label>
      {images.length > 0 && (
        <div className="grid grid-cols-3 gap-2">
          {images.map((img, idx) => (
            <div key={idx} className="group relative aspect-square rounded-lg border bg-muted overflow-hidden">
              <img src={img} alt={`Photo ${idx + 1}`} className="h-full w-full object-cover" />
              <button
                type="button"
                onClick={() => handleRemoveImage(idx)}
                className="absolute top-1 right-1 flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground opacity-0 transition-opacity group-hover:opacity-100"
              >
                <X className="h-3 w-3" />
              </button>
              {idx === 0 && (
                <span className="absolute bottom-1 left-1 rounded bg-primary px-1 py-0.5 text-[8px] font-semibold text-primary-foreground">
                  {language === 'en' ? 'Cover' : 'কভার'}
                </span>
              )}
            </div>
          ))}
        </div>
      )}
      <div className="flex gap-2">
        <Button type="button" variant="outline" size="sm" className="flex-1 text-xs" onClick={() => fileInputRef.current?.click()} disabled={isUploading}>
          {isUploading
            ? (language === 'en' ? 'Uploading...' : 'আপলোড হচ্ছে...')
            : (<><Upload className="mr-1 h-3 w-3" />{language === 'en' ? 'Choose Files' : 'ফাইল নির্বাচন'}</>)}
        </Button>
        <input ref={fileInputRef} type="file" accept="image/*" multiple className="hidden" onChange={handleFileChange} />
      </div>
      <div className="flex gap-2">
        <Input value={urlInput} onChange={(e) => setUrlInput(e.target.value)} placeholder={language === 'en' ? 'Or paste image URL...' : 'অথবা ছবির URL দিন...'} className="text-xs"
          onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleAddUrl(); } }} />
        <Button type="button" variant="outline" size="sm" className="shrink-0 text-xs" onClick={handleAddUrl} disabled={!urlInput.trim()}>
          {language === 'en' ? 'Add' : 'যোগ'}
        </Button>
      </div>
      <p className="text-[10px] text-muted-foreground">
        {language === 'en' ? 'Supports JPG, PNG, GIF, WebP, SVG, BMP. Max 5MB.' : 'JPG, PNG, GIF, WebP, SVG, BMP সাপোর্ট। সর্বোচ্চ ৫MB।'}
      </p>
    </div>
  );
}

// ─── Product Upload Form ────────────────────────────────────────
function ProductUploadForm({
  language,
  sellerId,
  onSaved,
  editProduct,
  onCancelEdit,
}: {
  language: 'en' | 'bn';
  sellerId: string;
  onSaved: () => void;
  editProduct: DbProduct | null;
  onCancelEdit: () => void;
}) {
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);

  const [form, setForm] = useState({
    title: editProduct?.title || '',
    description: editProduct?.description || '',
    price: editProduct?.price?.toString() || '',
    discount: editProduct?.discount?.toString() || '0',
    category: editProduct?.category || 'daily_needs',
    subcategory: editProduct?.subcategory || '',
    stock: editProduct?.stock?.toString() || '1',
    unit: editProduct?.unit || 'piece',
    contactNumber: editProduct?.contactNumber || '',
  });

  const [images, setImages] = useState<string[]>(() => {
    if (editProduct?.images) { try { return JSON.parse(editProduct.images); } catch { return []; } } return [];
  });

  useEffect(() => {
    if (editProduct) {
      setForm({
        title: editProduct.title,
        description: editProduct.description,
        price: editProduct.price.toString(),
        discount: editProduct.discount.toString(),
        category: editProduct.category,
        subcategory: editProduct.subcategory || '',
        stock: editProduct.stock.toString(),
        unit: editProduct.unit || 'piece',
        contactNumber: editProduct.contactNumber || '',
      });
      try { setImages(JSON.parse(editProduct.images)); } catch { setImages([]); }
    }
  }, [editProduct]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.title || !form.description || !form.price) {
      toast({ title: language === 'en' ? 'Please fill all required fields' : 'সকল প্রয়োজনীয় ক্ষেত্র পূরণ করুন', variant: 'destructive' });
      return;
    }
    setIsLoading(true);
    try {
      const payload = {
        ...form,
        price: parseFloat(form.price),
        discount: parseFloat(form.discount) || 0,
        stock: parseInt(form.stock) || 1,
        images,
        ...(editProduct ? {} : { sellerId }),
      };
      if (editProduct) {
        const res = await fetch('/api/products', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id: editProduct.id, ...payload }),
        });
        const data = await res.json();
        if (res.ok) {
          toast({ title: language === 'en' ? 'Product updated!' : 'পণ্য আপডেট হয়েছে!' });
          onSaved(); onCancelEdit();
        } else {
          toast({ title: data.error || 'Failed', variant: 'destructive' });
        }
      } else {
        const res = await fetch('/api/products', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        const data = await res.json();
        if (res.ok) {
          toast({ title: language === 'en' ? 'Product posted!' : 'পণ্য পোস্ট হয়েছে!' });
          onSaved();
          setForm({ title: '', description: '', price: '', discount: '0', category: 'daily_needs', subcategory: '', stock: '1', unit: 'piece', contactNumber: '' });
          setImages([]);
        } else {
          toast({ title: data.error || 'Failed', variant: 'destructive' });
        }
      }
    } catch {
      toast({ title: language === 'en' ? 'Network error' : 'নেটওয়ার্ক ত্রুটি', variant: 'destructive' });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {editProduct && (
        <div className="rounded-lg border border-primary/20 bg-primary/5 p-3 text-center text-xs font-medium text-primary">
          {language === 'en' ? 'Editing' : 'সম্পাদনা করছেন'}: {editProduct.title}
        </div>
      )}
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">{language === 'en' ? 'Product Title' : 'পণ্যের নাম'} *</Label>
        <Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder={language === 'en' ? 'e.g. Rice 5kg' : 'যেমন: চাল ৫ কেজি'} className="text-sm" required />
      </div>
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">{language === 'en' ? 'Description' : 'বিবরণ'} *</Label>
        <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder={language === 'en' ? 'Describe your product...' : 'পণ্যের বিবরণ...'} className="min-h-[80px] text-sm" required />
      </div>
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{language === 'en' ? 'Category' : 'ক্যাটেগরি'} *</Label>
          <select value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
            {categories.map((c) => (<option key={c.value} value={c.value}>{language === 'en' ? c.labelEn : c.labelBn}</option>))}
          </select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{language === 'en' ? 'Subcategory' : 'সাব-ক্যাটেগরি'}</Label>
          <Input value={form.subcategory} onChange={(e) => setForm({ ...form, subcategory: e.target.value })} placeholder={language === 'en' ? 'e.g. Basmati' : 'যেমন: বাসমতি'} className="text-sm" />
        </div>
      </div>
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{language === 'en' ? 'Price (৳)' : 'মূল্য (৳)'} *</Label>
          <Input type="number" value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} placeholder="500" className="text-sm" required />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{language === 'en' ? 'Discount (%)' : 'ডিসকাউন্ট (%)'}</Label>
          <Input type="number" value={form.discount} onChange={(e) => setForm({ ...form, discount: e.target.value })} placeholder="0" className="text-sm" min="0" max="100" />
        </div>
      </div>
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{language === 'en' ? 'Stock' : 'স্টক'}</Label>
          <Input type="number" value={form.stock} onChange={(e) => setForm({ ...form, stock: e.target.value })} placeholder="1" className="text-sm" min="0" />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{language === 'en' ? 'Unit' : 'একক'}</Label>
          <select value={form.unit} onChange={(e) => setForm({ ...form, unit: e.target.value })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
            {units.map((u) => (<option key={u.value} value={u.value}>{language === 'en' ? u.labelEn : u.labelBn}</option>))}
          </select>
        </div>
      </div>
      <Separator />
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">
          <span className="flex items-center gap-1"><Phone className="h-3 w-3" />{language === 'en' ? 'Contact Number' : 'যোগাযোগ নম্বর'} *</span>
        </Label>
        <Input type="tel" value={form.contactNumber} onChange={(e) => setForm({ ...form, contactNumber: e.target.value })} placeholder="+8801XXXXXXXXX" className="text-sm" required />
      </div>
      <Separator />
      <ImageUploader language={language} images={images} onImagesChange={setImages} />
      <div className="flex gap-3 pt-2">
        {editProduct && (
          <Button type="button" variant="outline" className="flex-1" onClick={onCancelEdit}>{t('common.cancel', language)}</Button>
        )}
        <Button type="submit" className="flex-1 bg-gradient-to-r from-primary to-primary/90 font-semibold" disabled={isLoading}>
          {isLoading ? t('common.loading', language) : editProduct ? t('common.save', language) : (language === 'en' ? 'Post Product' : 'পণ্য পোস্ট করুন')}
        </Button>
      </div>
    </form>
  );
}

// ─── Main Seller Dashboard ──────────────────────────────────────
export default function SellerDashboardModule() {
  const { language, isLoggedIn, user, setCurrentSection } = useAppStore();
  const { toast } = useToast();

  const [products, setProducts] = useState<DbProduct[]>([]);
  const [loading, setLoading] = useState(true);
  const [formOpen, setFormOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<DbProduct | null>(null);
  const [activeTab, setActiveTab] = useState('products');

  const fetchMyProducts = useCallback(async () => {
    if (!user?.id) return;
    try {
      setLoading(true);
      const res = await fetch(`/api/products/my?sellerId=${user.id}`);
      const data = await res.json();
      if (data.products) setProducts(data.products);
    } catch (err) {
      console.error('Failed to fetch my products:', err);
    } finally {
      setLoading(false);
    }
  }, [user?.id]);

  useEffect(() => {
    if (isLoggedIn && user?.id) fetchMyProducts();
  }, [isLoggedIn, user?.id, fetchMyProducts]);

  const handleToggleAvailable = async (id: string, current: boolean) => {
    try {
      const res = await fetch('/api/products', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, isAvailable: !current }),
      });
      if (res.ok) {
        toast({ title: current ? (language === 'en' ? 'Marked as unavailable' : 'অনুপলব্ধ চিহ্নিত') : (language === 'en' ? 'Available Now' : 'এখন পাওয়া যাচ্ছে') });
        fetchMyProducts();
      }
    } catch (err) { console.error(err); }
  };

  const handleDelete = async (id: string) => {
    try {
      const res = await fetch('/api/products', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id }),
      });
      if (res.ok) {
        toast({ title: language === 'en' ? 'Product deleted!' : 'পণ্য মুছে ফেলা হয়েছে!' });
        fetchMyProducts();
      }
    } catch (err) { console.error(err); }
  };

  const parseImages = (imagesStr: string): string[] => {
    try { return JSON.parse(imagesStr); } catch { return []; }
  };

  const activeCount = products.filter((p) => p.isAvailable).length;
  const lowStockCount = products.filter((p) => p.stock < 5 && p.isAvailable).length;
  const categoryStats = products.reduce<Record<string, number>>((acc, p) => {
    acc[p.category] = (acc[p.category] || 0) + 1;
    return acc;
  }, {});

  // ─── Not logged in
  if (!isLoggedIn || !user) {
    return (
      <div className="flex min-h-full flex-col">
        <div className="sticky top-0 z-30 border-b border-border/40 bg-background/95 backdrop-blur-xl">
          <div className="flex items-center gap-3 px-4 py-3">
            <Button variant="ghost" size="icon" onClick={() => setCurrentSection('home')} className="shrink-0"><ArrowLeft className="h-5 w-5" /></Button>
            <h1 className="text-lg font-bold">{language === 'en' ? 'Seller Dashboard' : 'সেলার ড্যাশবোর্ড'}</h1>
          </div>
        </div>
        <div className="flex flex-1 flex-col items-center justify-center gap-4 px-4 py-16">
          <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-primary/10"><ShoppingBag className="h-10 w-10 text-primary/40" /></div>
          <p className="text-center text-sm text-muted-foreground">{language === 'en' ? 'Please login as a seller' : 'সেলার হিসেবে লগইন করুন'}</p>
          <Button className="bg-gradient-to-r from-primary to-primary/90 font-semibold" onClick={() => setCurrentSection('auth')}>{language === 'en' ? 'Login Now' : 'এখন লগইন করুন'}</Button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-full flex-col">
      {/* Header */}
      <div className="sticky top-0 z-30 border-b border-border/40 bg-background/95 backdrop-blur-xl">
        <div className="flex items-center gap-3 px-4 py-3">
          <Button variant="ghost" size="icon" onClick={() => setCurrentSection('home')} className="shrink-0"><ArrowLeft className="h-5 w-5" /></Button>
          <h1 className="text-lg font-bold">{language === 'en' ? 'Seller Dashboard' : 'সেলার ড্যাশবোর্ড'}</h1>
          <Badge variant="outline" className="ml-auto text-[10px]">{language === 'en' ? 'Seller' : 'সেলার'}</Badge>
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 px-4 py-4 space-y-4">
        {/* Stats */}
        <div className="grid grid-cols-2 gap-3">
          <Card className="overflow-hidden border-0 bg-gradient-to-br from-primary to-primary/80 text-primary-foreground">
            <CardContent className="p-4">
              <div className="flex items-center gap-2">
                <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/20"><Package className="h-5 w-5" /></div>
                <div>
                  <p className="text-[10px] font-medium opacity-80">{language === 'en' ? 'Total Products' : 'মোট পণ্য'}</p>
                  <p className="text-xl font-bold">{products.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="overflow-hidden border-0 bg-gradient-to-br from-emerald-500 to-emerald-600/80 text-white">
            <CardContent className="p-4">
              <div className="flex items-center gap-2">
                <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/20"><Eye className="h-5 w-5" /></div>
                <div>
                  <p className="text-[10px] font-medium opacity-80">{language === 'en' ? 'Active' : 'সক্রিয়'}</p>
                  <p className="text-xl font-bold">{activeCount}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="overflow-hidden border-0 bg-gradient-to-br from-amber-500 to-amber-600/80 text-white">
            <CardContent className="p-4">
              <div className="flex items-center gap-2">
                <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/20"><AlertTriangle className="h-5 w-5" /></div>
                <div>
                  <p className="text-[10px] font-medium opacity-80">{language === 'en' ? 'Low Stock' : 'স্টক কম'}</p>
                  <p className="text-xl font-bold">{lowStockCount}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="overflow-hidden border-0 bg-gradient-to-br from-primary/80 to-primary/60 text-primary-foreground">
            <CardContent className="p-4">
              <div className="flex items-center gap-2">
                <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/20"><TrendingUp className="h-5 w-5" /></div>
                <div>
                  <p className="text-[10px] font-medium opacity-80">{language === 'en' ? 'Categories' : 'ক্যাটেগরি'}</p>
                  <p className="text-xl font-bold">{Object.keys(categoryStats).length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Upload Product Button */}
        <Button className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold py-5 text-sm" size="lg" onClick={() => { setEditingProduct(null); setFormOpen(true); }}>
          <Plus className="mr-2 h-5 w-5" />
          {language === 'en' ? 'Upload New Product' : 'নতুন পণ্য আপলোড করুন'}
        </Button>

        {/* Tabs */}
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="w-full">
            <TabsTrigger value="products" className="flex-1 gap-1.5">
              <Package className="h-3.5 w-3.5" />
              {language === 'en' ? 'My Products' : 'আমার পণ্য'} ({products.length})
            </TabsTrigger>
            <TabsTrigger value="analytics" className="flex-1 gap-1.5">
              <BarChart3 className="h-3.5 w-3.5" />
              {language === 'en' ? 'Analytics' : 'বিশ্লেষণ'}
            </TabsTrigger>
          </TabsList>

          {/* Products Tab */}
          <TabsContent value="products" className="mt-3 space-y-3">
            {loading ? (
              <div className="flex items-center justify-center py-8"><div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" /></div>
            ) : products.length === 0 ? (
              <Card className="border-dashed">
                <CardContent className="flex flex-col items-center justify-center py-8">
                  <ShoppingBag className="h-8 w-8 text-muted-foreground/40 mb-2" />
                  <p className="text-sm text-muted-foreground">{language === 'en' ? 'No products yet' : 'এখনো কোনো পণ্য নেই'}</p>
                  <Button variant="outline" size="sm" className="mt-3 text-xs" onClick={() => { setEditingProduct(null); setFormOpen(true); }}>
                    <Plus className="mr-1 h-3 w-3" />{language === 'en' ? 'Add Product' : 'পণ্য যোগ করুন'}
                  </Button>
                </CardContent>
              </Card>
            ) : (
              products.map((product) => {
                const productImages = parseImages(product.images);
                const cat = categories.find((c) => c.value === product.category);
                return (
                  <Card key={product.id} className="overflow-hidden">
                    <div className="flex">
                      <div className="flex h-24 w-24 shrink-0 items-center justify-center bg-gradient-to-br from-orange-400 to-amber-500">
                        {productImages.length > 0 ? (
                          <img src={productImages[0]} alt={product.title} className="h-full w-full object-cover" />
                        ) : (
                          <ShoppingBag className="h-8 w-8 text-white/80" />
                        )}
                      </div>
                      <div className="flex-1 p-3 min-w-0">
                        <div className="flex items-start justify-between gap-2">
                          <div className="min-w-0">
                            <h3 className="text-sm font-semibold truncate">{product.title}</h3>
                            <p className="text-xs text-muted-foreground truncate">{cat ? (language === 'en' ? cat.labelEn : cat.labelBn) : product.category}</p>
                          </div>
                          <Badge className={`shrink-0 text-[9px] px-1.5 py-0 ${product.isAvailable ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400'}`}>
                            {product.isAvailable ? (language === 'en' ? 'Active' : 'সক্রিয়') : (language === 'en' ? 'Inactive' : 'নিষ্ক্রিয়')}
                          </Badge>
                        </div>
                        <div className="mt-1.5 flex items-center gap-3 text-[11px] text-muted-foreground">
                          <span>Stock: {product.stock}</span>
                          {product.discount > 0 && <span className="text-emerald-600">-{product.discount}%</span>}
                          {product.contactNumber && <span className="flex items-center gap-0.5"><Phone className="h-3 w-3" />{product.contactNumber}</span>}
                        </div>
                        <div className="mt-1 flex items-center justify-between">
                          <p className="text-sm font-bold text-primary">৳{product.price.toLocaleString()}{product.unit ? `/${product.unit}` : ''}</p>
                          <div className="flex gap-1">
                            <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleToggleAvailable(product.id, product.isAvailable)}>
                              {product.isAvailable ? <EyeOff className="h-3.5 w-3.5 text-amber-500" /> : <Eye className="h-3.5 w-3.5 text-emerald-500" />}
                            </Button>
                            <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => { setEditingProduct(product); setFormOpen(true); }}>
                              <Edit3 className="h-3.5 w-3.5 text-primary" />
                            </Button>
                            <AlertDialog>
                              <AlertDialogTrigger asChild>
                                <Button variant="ghost" size="icon" className="h-7 w-7"><Trash2 className="h-3.5 w-3.5 text-destructive" /></Button>
                              </AlertDialogTrigger>
                              <AlertDialogContent>
                                <AlertDialogHeader>
                                  <AlertDialogTitle>{language === 'en' ? 'Delete Product?' : 'পণ্য মুছে ফেলবেন?'}</AlertDialogTitle>
                                  <AlertDialogDescription>{language === 'en' ? `Delete "${product.title}"? This cannot be undone.` : `"${product.title}" মুছে ফেলবেন? এটি পূর্বাবস্থায় ফেরানো যাবে না।`}</AlertDialogDescription>
                                </AlertDialogHeader>
                                <AlertDialogFooter>
                                  <AlertDialogCancel>{t('common.cancel', language)}</AlertDialogCancel>
                                  <AlertDialogAction onClick={() => handleDelete(product.id)} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">{language === 'en' ? 'Delete' : 'মুছুন'}</AlertDialogAction>
                                </AlertDialogFooter>
                              </AlertDialogContent>
                            </AlertDialog>
                          </div>
                        </div>
                      </div>
                    </div>
                  </Card>
                );
              })
            )}
          </TabsContent>

          {/* Analytics Tab */}
          <TabsContent value="analytics" className="mt-3 space-y-4">
            {/* Category Breakdown */}
            <Card>
              <CardContent className="p-4">
                <h3 className="text-sm font-semibold mb-3 flex items-center gap-2"><BarChart3 className="h-4 w-4 text-primary" />{language === 'en' ? 'Products by Category' : 'ক্যাটেগরি অনুযায়ী পণ্য'}</h3>
                {Object.keys(categoryStats).length === 0 ? (
                  <p className="text-xs text-muted-foreground">{language === 'en' ? 'No data yet' : 'এখনো কোনো ডেটা নেই'}</p>
                ) : (
                  <div className="space-y-2">
                    {Object.entries(categoryStats).map(([cat, count]) => {
                      const catInfo = categories.find((c) => c.value === cat);
                      const pct = Math.round((count / products.length) * 100);
                      return (
                        <div key={cat} className="space-y-1">
                          <div className="flex justify-between text-xs">
                            <span>{catInfo ? (language === 'en' ? catInfo.labelEn : catInfo.labelBn) : cat}</span>
                            <span className="font-medium">{count} ({pct}%)</span>
                          </div>
                          <div className="h-2 rounded-full bg-muted overflow-hidden">
                            <div className="h-full rounded-full bg-primary" style={{ width: `${pct}%` }} />
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Stock Alert */}
            {lowStockCount > 0 && (
              <Card className="border-amber-200 dark:border-amber-800">
                <CardContent className="p-4">
                  <h3 className="text-sm font-semibold mb-3 flex items-center gap-2"><AlertTriangle className="h-4 w-4 text-amber-500" />{language === 'en' ? 'Low Stock Alert' : 'স্টক কম সতর্কতা'}</h3>
                  <div className="space-y-2">
                    {products.filter((p) => p.stock < 5 && p.isAvailable).map((p) => (
                      <div key={p.id} className="flex items-center justify-between rounded-lg border border-amber-200 dark:border-amber-800 p-2">
                        <div>
                          <p className="text-xs font-medium">{p.title}</p>
                          <p className="text-[10px] text-muted-foreground">{language === 'en' ? 'Stock' : 'স্টক'}: {p.stock}</p>
                        </div>
                        <Badge variant="outline" className="text-amber-600 text-[9px]">{language === 'en' ? 'Restock' : 'রিস্টক'}</Badge>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Top Products */}
            <Card>
              <CardContent className="p-4">
                <h3 className="text-sm font-semibold mb-3 flex items-center gap-2"><TrendingUp className="h-4 w-4 text-emerald-500" />{language === 'en' ? 'Product Summary' : 'পণ্যের সারসংক্ষেপ'}</h3>
                <div className="space-y-2">
                  {products.slice(0, 5).map((p, i) => (
                    <div key={p.id} className="flex items-center justify-between rounded-lg bg-muted/50 p-2">
                      <div className="flex items-center gap-2">
                        <span className="flex h-6 w-6 items-center justify-center rounded-full bg-primary/10 text-[10px] font-bold text-primary">#{i + 1}</span>
                        <span className="text-xs font-medium truncate max-w-[150px]">{p.title}</span>
                      </div>
                      <div className="text-right">
                        <p className="text-xs font-bold">৳{p.price.toLocaleString()}</p>
                        <p className="text-[10px] text-muted-foreground">{language === 'en' ? 'Stock' : 'স্টক'}: {p.stock}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>

      {/* Product Form Dialog */}
      <Dialog open={formOpen} onOpenChange={setFormOpen}>
        <DialogContent className="sm:max-w-[500px] max-h-[85vh] overflow-y-auto">
          <DialogHeader className="flex-row items-center gap-2 space-y-0">
            <Button variant="ghost" size="sm" onClick={() => setFormOpen(false)} className="gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30 -ml-2">
              <ArrowLeft className="h-4 w-4" />
              <span>{language === 'en' ? 'Back' : 'ফিরুন'}</span>
            </Button>
            <DialogTitle className="flex items-center gap-2">
              <ShoppingBag className="h-5 w-5 text-primary" />
              {editingProduct ? (language === 'en' ? 'Edit Product' : 'পণ্য সম্পাদনা') : (language === 'en' ? 'Upload New Product' : 'নতুন পণ্য আপলোড')}
            </DialogTitle>
          </DialogHeader>
          <ProductUploadForm
            language={language}
            sellerId={user?.id || ''}
            onSaved={() => { fetchMyProducts(); setFormOpen(false); }}
            editProduct={editingProduct}
            onCancelEdit={() => { setEditingProduct(null); setFormOpen(false); }}
          />
        </DialogContent>
      </Dialog>
    </div>
  );
}
