'use client';

import { useState } from 'react';
import { useAppStore, type AppSection } from '@/lib/store';
import { t } from '@/lib/i18n';
import { mockHouses, mockProducts, categoryColors } from '@/lib/mock-data';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useToast } from '@/hooks/use-toast';
import {
  ArrowLeft,
  Search,
  Building2,
  Store,
  ShoppingBag,
  Pill,
  GraduationCap,
  BookOpen,
  Sparkles,
  MapPin,
  BedDouble,
  Bath,
  Star,
  TrendingUp,
  ShoppingBasket,
  Laptop,
  Shirt,
  Heart,
  Milk,
  X,
  ShoppingCart,
  Check,
} from 'lucide-react';

// ─── Category Grid Config ────────────────────────────────────────────
interface ExploreCategory {
  id: AppSection;
  icon: React.ElementType;
  labelKey: string;
  bgColor: string;
}

const exploreCategories: ExploreCategory[] = [
  {
    id: 'house-rental',
    icon: Building2,
    labelKey: 'sidebar.houseRental',
    bgColor: 'bg-orange-100 dark:bg-orange-900/30',
  },
  {
    id: 'shop-rental',
    icon: Store,
    labelKey: 'sidebar.shopRental',
    bgColor: 'bg-rose-100 dark:bg-rose-900/30',
  },
  {
    id: 'marketplace',
    icon: ShoppingBasket,
    labelKey: 'market.grocery',
    bgColor: 'bg-emerald-100 dark:bg-emerald-900/30',
  },
  {
    id: 'marketplace',
    icon: Laptop,
    labelKey: 'market.electronics',
    bgColor: 'bg-orange-100 dark:bg-orange-900/30',
  },
  {
    id: 'marketplace',
    icon: Shirt,
    labelKey: 'market.fashion',
    bgColor: 'bg-pink-100 dark:bg-pink-900/30',
  },
  {
    id: 'medicine',
    icon: Pill,
    labelKey: 'sidebar.medicine',
    bgColor: 'bg-red-100 dark:bg-red-900/30',
  },
  {
    id: 'marketplace',
    icon: BookOpen,
    labelKey: 'market.books',
    bgColor: 'bg-amber-100 dark:bg-amber-900/30',
  },
  {
    id: 'marketplace',
    icon: Milk,
    labelKey: 'market.dailyNeeds',
    bgColor: 'bg-orange-100 dark:bg-orange-900/30',
  },
];

// ─── Trending Searches ───────────────────────────────────────────────
const trendingSearches = [
  '3BHK Dhanmondi',
  'SSC MCQ',
  'Napa Extra',
  'Basmati Rice',
  'Flat Uttara',
  'HSC Physics',
  'Wireless Earbuds',
  'Cotton Saree',
];

// ─── Main Component ──────────────────────────────────────────────────
export default function ExploreModule() {
  const { language, searchQuery, setSearchQuery, setCurrentSection, addToCart } = useAppStore();
  const { toast } = useToast();
  const [addedToCart, setAddedToCart] = useState<Set<string>>(new Set());

  const popularHouses = mockHouses.slice(0, 3);
  const popularProducts = mockProducts.slice(0, 4);

  const handleTrendingClick = (term: string) => {
    setSearchQuery(term);
  };

  const handleAddToCart = (product: typeof mockProducts[0], e: React.MouseEvent) => {
    e.stopPropagation();
    const discountedPrice = product.discount > 0
      ? Math.round(product.price * (1 - product.discount / 100))
      : product.price;
    addToCart({
      productId: product.id,
      title: product.title,
      price: discountedPrice,
      quantity: 1,
      image: product.images[0],
      unit: product.unit,
    });
    setAddedToCart((prev) => new Set(prev).add(product.id));
    toast({
      title: language === 'en' ? 'Added to Cart' : 'কার্টে যোগ হয়েছে',
      description: `${product.title} — ৳${discountedPrice}`,
      duration: 2000,
    });
    setTimeout(() => {
      setAddedToCart((prev) => {
        const next = new Set(prev);
        next.delete(product.id);
        return next;
      });
    }, 1500);
  };

  return (
    <div className="flex flex-1 flex-col overflow-y-auto pb-4">
      {/* ── Header with Back Button ──────────────────────── */}
      <div className="sticky top-0 z-10 bg-background/95 backdrop-blur px-4 py-3">
        <div className="flex items-center gap-3 mb-2">
          <Button variant="ghost" size="icon" onClick={() => setCurrentSection('home')} className="shrink-0">
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <h1 className="text-lg font-bold text-foreground">
            {language === 'bn' ? 'এক্সপ্লোর' : 'Explore'}
          </h1>
        </div>
        <div className="relative">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            type="text"
            placeholder={t('home.search', language)}
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="h-11 rounded-xl border-border/50 bg-muted/30 pl-10 pr-10 text-sm shadow-none focus-visible:bg-background"
          />
          {searchQuery && (
            <button
              className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
              onClick={() => setSearchQuery('')}
              aria-label="Clear search"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
      </div>

      {/* ── Category Grid ──────────────────────────────────── */}
      <section className="px-4 py-3">
        <h2 className="mb-3 text-base font-bold text-foreground">
          {language === 'bn' ? 'ক্যাটাগরি' : 'Categories'}
        </h2>
        <div className="grid grid-cols-4 gap-2.5">
          {exploreCategories.map((category, idx) => {
            const Icon = category.icon;
            return (
              <button
                key={idx}
                onClick={() => setCurrentSection(category.id)}
                className="flex flex-col items-center gap-1.5 rounded-xl p-2.5 transition-all hover:shadow-sm active:scale-95"
              >
                <div
                  className={`flex h-12 w-12 items-center justify-center rounded-2xl ${category.bgColor}`}
                >
                  <Icon className="h-6 w-6 text-foreground/70" strokeWidth={1.8} />
                </div>
                <span className="text-[10px] font-medium text-muted-foreground leading-tight text-center">
                  {t(category.labelKey, language)}
                </span>
              </button>
            );
          })}
        </div>
      </section>

      {/* ── Trending Searches ──────────────────────────────── */}
      <section className="px-4 py-3">
        <div className="flex items-center gap-1.5 pb-2">
          <TrendingUp className="h-4 w-4 text-primary" />
          <h2 className="text-base font-bold text-foreground">
            {language === 'bn' ? 'ট্রেন্ডিং সার্চ' : 'Trending Searches'}
          </h2>
        </div>
        <div className="flex flex-wrap gap-2">
          {trendingSearches.map((term, idx) => (
            <Badge
              key={idx}
              variant="outline"
              className="cursor-pointer rounded-full px-3 py-1 text-xs font-medium transition-colors hover:bg-primary/10 hover:text-primary hover:border-primary/30"
              onClick={() => handleTrendingClick(term)}
            >
              {term}
            </Badge>
          ))}
        </div>
      </section>

      {/* ── Popular in Your Area ───────────────────────────── */}
      <section className="py-3">
        <div className="flex items-center justify-between px-4 pb-2">
          <div className="flex items-center gap-1.5">
            <MapPin className="h-4 w-4 text-primary" />
            <h2 className="text-base font-bold text-foreground">
              {language === 'bn' ? 'আপনার এলাকায় জনপ্রিয়' : 'Popular in Your Area'}
            </h2>
          </div>
          <Button
            variant="ghost"
            size="sm"
            className="h-7 gap-0.5 text-xs font-semibold text-primary"
            onClick={() => setCurrentSection('explore')}
          >
            {t('home.seeAll', language)}
          </Button>
        </div>

        {/* Houses */}
        <div className="mb-3">
          <p className="px-4 pb-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
            {t('home.featured', language)}
          </p>
          <div className="flex gap-3 overflow-x-auto scrollbar-hide px-4 pb-1">
            {popularHouses.map((house) => (
              <Card
                key={house.id}
                className="min-w-[14rem] max-w-[14rem] cursor-pointer overflow-hidden border-border/40 py-0 shadow-sm transition-shadow hover:shadow-md"
                onClick={() => setCurrentSection('house-rental')}
              >
                <div className="relative h-24 w-full bg-gradient-to-br from-orange-400 to-amber-300">
                  <div className="absolute inset-0 flex items-center justify-center">
                    <Building2 className="h-8 w-8 text-white/50" strokeWidth={1.2} />
                  </div>
                  {house.isAvailable && (
                    <Badge className="absolute left-2 top-2 bg-emerald-500 text-white text-[9px] px-1.5 py-0 border-0">
                      {t('house.available', language)}
                    </Badge>
                  )}
                </div>
                <CardContent className="p-3">
                  <h3 className="truncate text-sm font-semibold text-foreground">
                    {house.title}
                  </h3>
                  <div className="mt-0.5 flex items-center gap-1 text-muted-foreground">
                    <MapPin className="h-3 w-3 shrink-0" />
                    <span className="truncate text-[10px]">{house.upazila}</span>
                  </div>
                  <div className="mt-1.5 flex items-baseline gap-0.5">
                    <span className="text-sm font-bold text-primary">
                      ৳{house.price.toLocaleString()}
                    </span>
                    <span className="text-[10px] text-muted-foreground">
                      {t('house.perMonth', language)}
                    </span>
                  </div>
                  <div className="mt-1 flex items-center gap-2 text-[10px] text-muted-foreground">
                    <span className="flex items-center gap-0.5">
                      <BedDouble className="h-2.5 w-2.5" />
                      {house.rooms}
                    </span>
                    <span className="flex items-center gap-0.5">
                      <Bath className="h-2.5 w-2.5" />
                      {house.bathrooms}
                    </span>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>

        {/* Products */}
        <div>
          <p className="px-4 pb-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
            {t('home.popularProducts', language)}
          </p>
          <div className="flex gap-3 overflow-x-auto scrollbar-hide px-4 pb-1">
            {popularProducts.map((product) => {
              const catColor = categoryColors[product.category as keyof typeof categoryColors] || 'bg-gray-100 text-gray-700';
              return (
                <Card
                  key={product.id}
                  className="min-w-[11rem] max-w-[11rem] cursor-pointer overflow-hidden border-border/40 py-0 shadow-sm transition-shadow hover:shadow-md"
                  onClick={() => setCurrentSection('marketplace')}
                >
                  <div className="relative h-20 w-full bg-gradient-to-br from-amber-100 to-orange-100 dark:from-amber-900/30 dark:to-orange-900/30">
                    <div className="absolute inset-0 flex items-center justify-center">
                      <ShoppingBag className="h-7 w-7 text-orange-300/60 dark:text-orange-500/30" strokeWidth={1.2} />
                    </div>
                    {product.discount > 0 && (
                      <Badge className="absolute right-2 top-2 bg-red-500 text-white text-[9px] px-1.5 py-0 border-0">
                        -{product.discount}%
                      </Badge>
                    )}
                  </div>
                  <CardContent className="p-2.5">
                    <h3 className="truncate text-xs font-semibold text-foreground">
                      {product.title}
                    </h3>
                    <div className="mt-0.5 flex items-center gap-0.5">
                      <Star className="h-2.5 w-2.5 fill-amber-400 text-amber-400" />
                      <span className="text-[10px] font-medium text-foreground">{product.rating}</span>
                    </div>
                    <div className="mt-1 flex items-baseline gap-1">
                      <span className="text-sm font-bold text-primary">
                        ৳{(product.discount > 0 ? Math.round(product.price * (1 - product.discount / 100)) : product.price).toLocaleString()}
                      </span>
                      {product.discount > 0 && (
                        <span className="text-[10px] text-muted-foreground line-through">
                          ৳{product.price.toLocaleString()}
                        </span>
                      )}
                    </div>
                    <Badge variant="secondary" className={`mt-1 text-[9px] px-1.5 py-0 border-0 ${catColor}`}>
                      {product.category}
                    </Badge>
                    <Button
                      size="sm"
                      className={`mt-1.5 h-6 w-full rounded-md text-[10px] font-semibold transition-all duration-300 ${
                        addedToCart.has(product.id)
                          ? 'bg-green-500 text-white hover:bg-green-600'
                          : 'bg-primary text-primary-foreground hover:bg-primary/90'
                      }`}
                      onClick={(e) => handleAddToCart(product, e)}
                    >
                      {addedToCart.has(product.id) ? (
                        <>
                          <Check className="mr-1 h-2.5 w-2.5" />
                          {language === 'en' ? 'Added' : 'যোগ হয়েছে'}
                        </>
                      ) : (
                        <>
                          <ShoppingCart className="mr-1 h-2.5 w-2.5" />
                          {t('market.addToCart', language)}
                        </>
                      )}
                    </Button>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </div>
      </section>

      {/* ── Quick Links ────────────────────────────────────── */}
      <section className="px-4 py-3">
        <h2 className="mb-2 text-base font-bold text-foreground">
          {language === 'bn' ? 'দ্রুত লিংক' : 'Quick Links'}
        </h2>
        <div className="grid grid-cols-2 gap-2">
          <Card
            className="cursor-pointer border-border/40 py-0 shadow-sm transition-shadow hover:shadow-md"
            onClick={() => setCurrentSection('education')}
          >
            <CardContent className="flex items-center gap-3 p-3">
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-100 dark:bg-amber-900/30">
                <GraduationCap className="h-5 w-5 text-amber-600 dark:text-amber-400" strokeWidth={1.8} />
              </div>
              <div>
                <h4 className="text-xs font-semibold text-foreground">{t('edu.title', language)}</h4>
                <p className="text-[10px] text-muted-foreground">SSC, HSC, GK</p>
              </div>
            </CardContent>
          </Card>
          <Card
            className="cursor-pointer border-border/40 py-0 shadow-sm transition-shadow hover:shadow-md"
            onClick={() => setCurrentSection('favourites')}
          >
            <CardContent className="flex items-center gap-3 p-3">
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-rose-100 dark:bg-rose-900/30">
                <Heart className="h-5 w-5 text-rose-600 dark:text-rose-400" strokeWidth={1.8} />
              </div>
              <div>
                <h4 className="text-xs font-semibold text-foreground">{t('fav.title', language)}</h4>
                <p className="text-[10px] text-muted-foreground">{t('fav.empty', language)}</p>
              </div>
            </CardContent>
          </Card>
          <Card
            className="cursor-pointer border-border/40 py-0 shadow-sm transition-shadow hover:shadow-md"
            onClick={() => setCurrentSection('community')}
          >
            <CardContent className="flex items-center gap-3 p-3">
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-orange-100 dark:bg-orange-900/30">
                <Sparkles className="h-5 w-5 text-orange-600 dark:text-orange-400" strokeWidth={1.8} />
              </div>
              <div>
                <h4 className="text-xs font-semibold text-foreground">{t('community.title', language)}</h4>
                <p className="text-[10px] text-muted-foreground">{t('community.discussions', language)}</p>
              </div>
            </CardContent>
          </Card>
          <Card
            className="cursor-pointer border-border/40 py-0 shadow-sm transition-shadow hover:shadow-md"
            onClick={() => setCurrentSection('orders')}
          >
            <CardContent className="flex items-center gap-3 p-3">
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-100 dark:bg-emerald-900/30">
                <ShoppingBag className="h-5 w-5 text-emerald-600 dark:text-emerald-400" strokeWidth={1.8} />
              </div>
              <div>
                <h4 className="text-xs font-semibold text-foreground">{t('order.title', language)}</h4>
                <p className="text-[10px] text-muted-foreground">{t('order.pending', language)}</p>
              </div>
            </CardContent>
          </Card>
        </div>
      </section>
    </div>
  );
}
