'use client';

import { useState, useMemo } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { mockProducts, categoryIcons, categoryColors } from '@/lib/mock-data';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import {
  ArrowLeft,
  ShoppingCart,
  Search,
  Heart,
  Star,
  Plus,
  Minus,
  X,
  ShoppingBag,
  Truck,
} from 'lucide-react';

const categories = [
  { key: 'all', labelKey: 'common.filter', icon: '🏷️' },
  { key: 'grocery', labelKey: 'market.grocery', icon: categoryIcons.grocery },
  { key: 'electronics', labelKey: 'market.electronics', icon: categoryIcons.electronics },
  { key: 'fashion', labelKey: 'market.fashion', icon: categoryIcons.fashion },
  { key: 'medicine', labelKey: 'market.medicine', icon: categoryIcons.medicine },
  { key: 'books', labelKey: 'market.books', icon: categoryIcons.books },
  { key: 'daily_needs', labelKey: 'market.dailyNeeds', icon: categoryIcons.daily_needs },
] as const;

const categoryGradients: Record<string, string> = {
  grocery: 'from-green-400 to-emerald-500',
  electronics: 'from-orange-400 to-amber-500',
  fashion: 'from-pink-400 to-rose-500',
  medicine: 'from-red-400 to-rose-500',
  books: 'from-amber-400 to-yellow-500',
  daily_needs: 'from-orange-400 to-amber-500',
};

export default function MarketplaceModule() {
  const { language, cart, addToCart, setCurrentSection } = useAppStore();

  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedProduct, setSelectedProduct] = useState<typeof mockProducts[0] | null>(null);
  const [dialogQuantity, setDialogQuantity] = useState(1);

  const [wishlist, setWishlist] = useState<Set<string>>(new Set());

  // Filter products
  const filteredProducts = useMemo(() => {
    return mockProducts.filter((product) => {
      const matchesCategory = selectedCategory === 'all' || product.category === selectedCategory;
      const matchesSearch =
        searchQuery === '' ||
        product.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        product.description.toLowerCase().includes(searchQuery.toLowerCase());
      return matchesCategory && matchesSearch;
    });
  }, [selectedCategory, searchQuery]);


  const cartItemCount = useMemo(() => {
    return cart.reduce((sum, item) => sum + item.quantity, 0);
  }, [cart]);

  const handleAddToCart = (product: typeof mockProducts[0], quantity: number = 1) => {
    addToCart({
      productId: product.id,
      title: product.title,
      price: product.discount > 0
        ? Math.round(product.price * (1 - product.discount / 100))
        : product.price,
      quantity,
      image: product.images[0],
      unit: product.unit,
    });
  };

  const handleOpenProduct = (product: typeof mockProducts[0]) => {
    setSelectedProduct(product);
    setDialogQuantity(1);
  };

  const toggleWishlist = (productId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    setWishlist((prev) => {
      const next = new Set(prev);
      if (next.has(productId)) {
        next.delete(productId);
      } else {
        next.add(productId);
      }
      return next;
    });
  };

  const renderStars = (rating: number) => {
    const full = Math.floor(rating);
    const half = rating % 1 >= 0.5;
    const stars = [];

    for (let i = 0; i < 5; i++) {
      if (i < full) {
        stars.push(
          <Star key={i} className="h-3 w-3 fill-amber-400 text-amber-400" />
        );
      } else if (i === full && half) {
        stars.push(
          <Star key={i} className="h-3 w-3 fill-amber-400/50 text-amber-400" />
        );
      } else {
        stars.push(
          <Star key={i} className="h-3 w-3 text-muted-foreground/30" />
        );
      }
    }
    return stars;
  };

  const getDiscountedPrice = (product: typeof mockProducts[0]) => {
    if (product.discount > 0) {
      return Math.round(product.price * (1 - product.discount / 100));
    }
    return product.price;
  };

  return (
    <div className="flex flex-col gap-4 px-4 py-4 pb-24">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => setCurrentSection('home')}
            className="h-9 w-9 shrink-0"
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-foreground">
              {t('market.title', language)}
            </h1>
            <p className="text-xs text-muted-foreground">
              {filteredProducts.length} {language === 'en' ? 'products' : 'পণ্য'}
            </p>
          </div>
        </div>
        <Button
          variant="outline"
          size="icon"
          className="relative h-10 w-10 rounded-full border-primary/20 hover:bg-primary/10"
          onClick={() => setCurrentSection('checkout')}
        >
          <ShoppingCart className="h-5 w-5 text-primary" />
          {cart.length > 0 && (
            <Badge className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-primary p-0 text-[10px] font-bold text-primary-foreground">
              {cartItemCount}
            </Badge>
          )}
        </Button>
      </div>

      {/* Search Bar */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        <Input
          placeholder={t('market.search', language)}
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="pl-9 pr-9 h-10 rounded-xl border-primary/10 bg-card focus:border-primary/30"
        />
        {searchQuery && (
          <button
            onClick={() => setSearchQuery('')}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
          >
            <X className="h-4 w-4" />
          </button>
        )}
      </div>

      {/* Category Pills */}
      <div className="flex gap-2 overflow-x-auto pb-1 hide-scrollbar">
        {categories.map((cat) => {
          const isActive = selectedCategory === cat.key;
          return (
            <button
              key={cat.key}
              onClick={() => setSelectedCategory(cat.key)}
              className={`flex shrink-0 items-center gap-1.5 rounded-full px-4 py-2 text-xs font-medium transition-all duration-200 ${
                isActive
                  ? 'bg-primary text-primary-foreground shadow-md shadow-primary/25'
                  : 'bg-card text-muted-foreground border border-border hover:border-primary/30 hover:bg-primary/5'
              }`}
            >
              <span className="text-sm">{cat.icon}</span>
              {t(cat.labelKey, language)}
            </button>
          );
        })}
      </div>

      {/* Product Grid */}
      {filteredProducts.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <ShoppingBag className="h-12 w-12 text-muted-foreground/40" />
          <p className="mt-3 text-sm font-medium text-muted-foreground">
            {t('common.noResults', language)}
          </p>
          <p className="text-xs text-muted-foreground/60">
            {language === 'en' ? 'Try a different category or search' : 'ভিন্ন ক্যাটাগরি বা সার্চ চেষ্টা করুন'}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
          {filteredProducts.map((product) => {
            const discountedPrice = getDiscountedPrice(product);
            const isWishlisted = wishlist.has(product.id);
            const gradient = categoryGradients[product.category] || 'from-gray-400 to-gray-500';

            return (
              <Card
                key={product.id}
                className="group cursor-pointer overflow-hidden border-border/50 bg-card transition-all duration-200 hover:border-primary/20 hover:shadow-md"
                onClick={() => handleOpenProduct(product)}
              >
                <CardContent className="p-0">
                  {/* Image Area */}
                  <div className={`relative aspect-square bg-gradient-to-br ${gradient} overflow-hidden`}>
                    {product.images && product.images.length > 0 ? (
                      <img src={product.images[0]} alt={product.title} className="h-full w-full object-cover" loading="lazy" />
                    ) : (
                      <div className="flex h-full items-center justify-center">
                        <span className="text-4xl opacity-60">
                          {categoryIcons[product.category as keyof typeof categoryIcons] || '📦'}
                        </span>
                      </div>
                    )}

                    {/* Discount Badge */}
                    {product.discount > 0 && (
                      <Badge className="absolute left-2 top-2 bg-destructive text-destructive-foreground text-[10px] font-bold px-1.5 py-0.5">
                        -{product.discount}%
                      </Badge>
                    )}

                    {/* Wishlist Button */}
                    <button
                      onClick={(e) => toggleWishlist(product.id, e)}
                      className="absolute right-2 top-2 flex h-7 w-7 items-center justify-center rounded-full bg-background/80 backdrop-blur-sm transition-colors hover:bg-background"
                    >
                      <Heart
                        className={`h-3.5 w-3.5 transition-colors ${
                          isWishlisted
                            ? 'fill-red-500 text-red-500'
                            : 'text-muted-foreground'
                        }`}
                      />
                    </button>
                  </div>

                  {/* Product Info */}
                  <div className="p-2.5">
                    <h3 className="line-clamp-2 text-xs font-semibold leading-tight text-foreground min-h-[2rem]">
                      {product.title}
                    </h3>

                    <div className="mt-1.5 flex items-baseline gap-1.5">
                      <span className="text-sm font-bold text-primary">
                        ৳{discountedPrice}
                      </span>
                      {product.discount > 0 && (
                        <span className="text-[10px] text-muted-foreground line-through">
                          ৳{product.price}
                        </span>
                      )}
                    </div>

                    <div className="mt-0.5 flex items-center gap-1">
                      <span className="text-[10px] text-muted-foreground">
                        {product.unit}
                      </span>
                      <span className="text-muted-foreground/40">·</span>
                      <div className="flex items-center gap-0.5">
                        {renderStars(product.rating)}
                        <span className="text-[10px] text-muted-foreground ml-0.5">
                          ({product.reviewCount})
                        </span>
                      </div>
                    </div>

                    {/* Add to Cart */}
                    <Button
                      size="sm"
                      className="mt-2 h-7 w-full rounded-lg bg-primary text-[11px] font-semibold text-primary-foreground hover:bg-primary/90"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleAddToCart(product);
                      }}
                    >
                      <Plus className="mr-1 h-3 w-3" />
                      {t('market.addToCart', language)}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {/* Product Detail Dialog */}
      <Dialog open={!!selectedProduct} onOpenChange={(open) => !open && setSelectedProduct(null)}>
        <DialogContent className="max-w-md max-h-[90vh] overflow-y-auto custom-scrollbar p-0">
          <DialogTitle className="sr-only">{selectedProduct?.title || 'Product Details'}</DialogTitle>
          <DialogDescription className="sr-only">{selectedProduct?.description || 'Product details dialog'}</DialogDescription>
          {selectedProduct && (
            <div>
              {/* Image Area */}
              <div
                className={`relative aspect-[4/3] w-full overflow-hidden bg-gradient-to-br ${
                  categoryGradients[selectedProduct.category] || 'from-gray-400 to-gray-500'
                }`}
              >
                {selectedProduct.images && selectedProduct.images.length > 0 ? (
                  <img src={selectedProduct.images[0]} alt={selectedProduct.title} className="h-full w-full object-cover" loading="lazy" />
                ) : (
                  <div className="flex h-full items-center justify-center">
                    <span className="text-6xl opacity-50">
                      {categoryIcons[selectedProduct.category as keyof typeof categoryIcons] || '📦'}
                    </span>
                  </div>
                )}
                {selectedProduct.discount > 0 && (
                  <Badge className="absolute left-4 top-4 bg-destructive text-destructive-foreground text-sm font-bold px-2 py-1">
                    -{selectedProduct.discount}%
                  </Badge>
                )}
                <button
                  onClick={() => setSelectedProduct(null)}
                  className="absolute left-3 top-3 flex h-8 w-8 items-center justify-center rounded-full bg-black/30 text-white backdrop-blur-sm transition-colors hover:bg-black/50"
                  aria-label="Back to products"
                >
                  <ArrowLeft className="h-4 w-4" />
                </button>
              </div>

              <div className="p-5">
                {/* Category Badge */}
                <Badge
                  variant="secondary"
                  className={`text-[10px] ${categoryColors[selectedProduct.category as keyof typeof categoryColors] || ''}`}
                >
                  {categoryIcons[selectedProduct.category as keyof typeof categoryIcons]}{' '}
                  {t(`market.${selectedProduct.category === 'daily_needs' ? 'dailyNeeds' : selectedProduct.category}`, language)}
                </Badge>

                {/* Title */}
                <h2 className="mt-2 text-lg font-bold text-foreground">
                  {selectedProduct.title}
                </h2>

                {/* Rating */}
                <div className="mt-1.5 flex items-center gap-2">
                  <div className="flex items-center gap-0.5">
                    {renderStars(selectedProduct.rating)}
                  </div>
                  <span className="text-sm font-medium text-foreground">
                    {selectedProduct.rating}
                  </span>
                  <span className="text-xs text-muted-foreground">
                    ({selectedProduct.reviewCount} {language === 'en' ? 'reviews' : 'রিভিউ'})
                  </span>
                </div>

                {/* Price */}
                <div className="mt-3 flex items-baseline gap-2">
                  <span className="text-2xl font-bold text-primary">
                    ৳{getDiscountedPrice(selectedProduct)}
                  </span>
                  {selectedProduct.discount > 0 && (
                    <span className="text-sm text-muted-foreground line-through">
                      ৳{selectedProduct.price}
                    </span>
                  )}
                  <span className="text-xs text-muted-foreground">
                    / {selectedProduct.unit}
                  </span>
                </div>

                {selectedProduct.discount > 0 && (
                  <p className="mt-1 text-xs font-medium text-green-600 dark:text-green-400">
                    {language === 'en' ? 'You save' : 'আপনি বাঁচান'} ৳{selectedProduct.price - getDiscountedPrice(selectedProduct)}
                  </p>
                )}

                <Separator className="my-4" />

                {/* Description */}
                <div>
                  <h3 className="text-sm font-semibold text-foreground">
                    {language === 'en' ? 'Description' : 'বিবরণ'}
                  </h3>
                  <p className="mt-1 text-sm text-muted-foreground leading-relaxed">
                    {selectedProduct.description}
                  </p>
                </div>

                <Separator className="my-4" />

                {/* Seller Info */}
                <div className="flex items-center gap-2">
                  <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10">
                    <ShoppingBag className="h-4 w-4 text-primary" />
                  </div>
                  <div>
                    <p className="text-xs font-medium text-foreground">{selectedProduct.sellerName}</p>
                    <p className="text-[10px] text-muted-foreground">
                      {language === 'en' ? 'Verified Seller' : 'যাচাইকৃত বিক্রেতা'}
                    </p>
                  </div>
                </div>

                <Separator className="my-4" />

                {/* Quantity Selector */}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-foreground">
                    {language === 'en' ? 'Quantity' : 'পরিমাণ'}
                  </span>
                  <div className="flex items-center gap-3">
                    <Button
                      variant="outline"
                      size="icon"
                      className="h-8 w-8 rounded-lg"
                      onClick={() => setDialogQuantity(Math.max(1, dialogQuantity - 1))}
                    >
                      <Minus className="h-3 w-3" />
                    </Button>
                    <span className="w-8 text-center text-sm font-bold">{dialogQuantity}</span>
                    <Button
                      variant="outline"
                      size="icon"
                      className="h-8 w-8 rounded-lg"
                      onClick={() => setDialogQuantity(dialogQuantity + 1)}
                    >
                      <Plus className="h-3 w-3" />
                    </Button>
                  </div>
                </div>

                {/* Stock Info */}
                <p className="mt-2 text-xs text-muted-foreground">
                  <Truck className="mr-1 inline h-3 w-3 text-primary" />
                  {selectedProduct.stock > 0
                    ? language === 'en'
                      ? `${selectedProduct.stock} in stock`
                      : `${selectedProduct.stock} স্টকে আছে`
                    : language === 'en'
                    ? 'Out of stock'
                    : 'স্টকে নেই'}
                </p>

                {/* Action Buttons */}
                <div className="mt-4 flex gap-3">
                  <Button
                    className="flex-1 bg-primary font-semibold text-primary-foreground hover:bg-primary/90"
                    onClick={() => {
                      handleAddToCart(selectedProduct, dialogQuantity);
                      setSelectedProduct(null);
                    }}
                  >
                    <ShoppingCart className="mr-2 h-4 w-4" />
                    {t('market.addToCart', language)}
                  </Button>
                  <Button
                    variant="outline"
                    className="flex-1 border-primary text-primary font-semibold hover:bg-primary/10"
                    onClick={() => {
                      handleAddToCart(selectedProduct, dialogQuantity);
                      setSelectedProduct(null);
                      setCurrentSection('checkout');
                    }}
                  >
                    {t('market.buyNow', language)}
                  </Button>
                </div>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>


    </div>
  );
}
