'use client';

import { useState, useRef, useEffect } 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 {
  Search,
  Building2,
  Store,
  ShoppingBag,
  Pill,
  GraduationCap,
  Users,
  Package,
  Heart,
  MapPin,
  BedDouble,
  Bath,
  Star,
  ChevronRight,
  Sparkles,
  BookOpen,
  Stethoscope,
  Wrench,
  Zap,
  ShoppingCart,
  Plus,
  Check,
} from 'lucide-react';

// ─── Quick Service Icons Config ──────────────────────────────────────
interface QuickService {
  id: AppSection;
  icon: React.ElementType;
  labelKey: string;
}

const quickServices: QuickService[] = [
  { id: 'house-rental', icon: Building2, labelKey: 'sidebar.houseRental' },
  { id: 'shop-rental', icon: Store, labelKey: 'sidebar.shopRental' },
  { id: 'marketplace', icon: ShoppingBag, labelKey: 'sidebar.marketplace' },
  { id: 'medicine', icon: Pill, labelKey: 'sidebar.medicine' },
  { id: 'education', icon: GraduationCap, labelKey: 'sidebar.mcqExam' },
  { id: 'community', icon: Users, labelKey: 'sidebar.community' },
  { id: 'orders', icon: Package, labelKey: 'sidebar.orders' },
  { id: 'favourites', icon: Heart, labelKey: 'nav.favourites' },
];

// ─── Ad Banner Data ──────────────────────────────────────────────────
const adBanners = [
  {
    id: 'b1',
    gradient: 'from-orange-500 via-orange-400 to-amber-400',
    titleKey: 'home.banner.dreamHome',
    titleFallback: 'Find Your Dream Home',
    subtitleKey: 'home.banner.dreamHomeSub',
    subtitleFallback: 'Affordable houses across Bangladesh',
    icon: Building2,
  },
  {
    id: 'b2',
    gradient: 'from-rose-500 via-pink-500 to-orange-400',
    titleKey: 'home.banner.mcqExam',
    titleFallback: 'MCQ Exam - Practice Now!',
    subtitleKey: 'home.banner.mcqExamSub',
    subtitleFallback: 'SSC, HSC, Admission & GK quizzes',
    icon: GraduationCap,
  },
  {
    id: 'b3',
    gradient: 'from-amber-500 via-orange-500 to-red-400',
    titleKey: 'home.banner.dailyEssentials',
    titleFallback: 'Shop Daily Essentials',
    subtitleKey: 'home.banner.dailyEssentialsSub',
    subtitleFallback: 'Grocery, medicine & more delivered',
    icon: ShoppingBag,
  },
  {
    id: 'b4',
    gradient: 'from-orange-600 via-red-500 to-rose-400',
    titleKey: 'home.banner.medicineDelivery',
    titleFallback: 'Medicine at Your Door',
    subtitleKey: 'home.banner.medicineDeliverySub',
    subtitleFallback: 'Upload prescription & order easily',
    icon: Pill,
  },
];

// ─── MCQ Categories ──────────────────────────────────────────────────
const mcqCategories = [
  { id: 'ssc', labelKey: 'edu.ssc', color: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' },
  { id: 'hsc', labelKey: 'edu.hsc', color: 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400' },
  { id: 'gk', labelKey: 'edu.gk', color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400' },
  { id: 'admission', labelKey: 'edu.admission', color: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' },
];

// ─── Nearby Services ─────────────────────────────────────────────────
const nearbyServices = [
  { id: 'ns1', name: 'HealthPlus Pharmacy', distance: '0.5 km', icon: Stethoscope, section: 'medicine' as AppSection },
  { id: 'ns2', name: 'Home Repair Service', distance: '1.2 km', icon: Wrench, section: 'marketplace' as AppSection },
  { id: 'ns3', name: 'Electrician Available', distance: '0.8 km', icon: Zap, section: 'marketplace' as AppSection },
  { id: 'ns4', name: 'BookLand BD', distance: '2.1 km', icon: BookOpen, section: 'marketplace' as AppSection },
];

// ─── Main Component ──────────────────────────────────────────────────
export default function HomeModule() {
  const { language, searchQuery, setSearchQuery, setCurrentSection, addToCart } = useAppStore();
  const { toast } = useToast();
  const [activeBanner, setActiveBanner] = useState(0);
  const [addedToCart, setAddedToCart] = useState<Set<string>>(new Set());
  const bannerScrollRef = useRef<HTMLDivElement>(null);

  // Auto-scroll banner
  useEffect(() => {
    const interval = setInterval(() => {
      setActiveBanner((prev) => {
        const next = (prev + 1) % adBanners.length;
        if (bannerScrollRef.current) {
          const child = bannerScrollRef.current.children[next] as HTMLElement;
          if (child) {
            bannerScrollRef.current.scrollTo({
              left: child.offsetLeft,
              behavior: 'smooth',
            });
          }
        }
        return next;
      });
    }, 4000);
    return () => clearInterval(interval);
  }, []);

  // Handle manual banner scroll
  const handleBannerScroll = () => {
    if (!bannerScrollRef.current) return;
    const scrollLeft = bannerScrollRef.current.scrollLeft;
    const width = bannerScrollRef.current.offsetWidth;
    const index = Math.round(scrollLeft / width);
    setActiveBanner(index);
  };

  const featuredHouses = mockHouses.slice(0, 4);
  const popularProducts = mockProducts.slice(0, 5);

  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">
      {/* ── Search Bar ─────────────────────────────────────── */}
      <div className="sticky top-0 z-10 bg-background/95 backdrop-blur px-4 py-3">
        <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-4 text-sm shadow-none focus-visible:bg-background"
          />
        </div>
      </div>

      {/* ── Ad Banner Carousel ─────────────────────────────── */}
      <div className="px-4 pb-2">
        <div
          ref={bannerScrollRef}
          onScroll={handleBannerScroll}
          className="flex snap-x snap-mandatory gap-3 overflow-x-auto scrollbar-hide -mx-1 px-1"
        >
          {adBanners.map((banner, idx) => {
            const Icon = banner.icon;
            return (
              <div
                key={banner.id}
                className={`flex min-w-[calc(100%-0.5rem)] snap-center items-center justify-between rounded-2xl bg-gradient-to-r ${banner.gradient} p-5 text-white shadow-md`}
              >
                <div className="flex-1 pr-3">
                  <h3 className="text-lg font-bold leading-tight">
                    {banner.titleFallback}
                  </h3>
                  <p className="mt-1 text-xs text-white/80">
                    {banner.subtitleFallback}
                  </p>
                  <Button
                    size="sm"
                    variant="secondary"
                    className="mt-3 h-8 rounded-full bg-white/20 text-xs font-semibold text-white backdrop-blur-sm hover:bg-white/30"
                    onClick={() => {
                      const sectionMap: Record<string, AppSection> = {
                        b1: 'house-rental',
                        b2: 'education',
                        b3: 'marketplace',
                        b4: 'medicine',
                      };
                      setCurrentSection(sectionMap[banner.id] || 'home');
                    }}
                  >
                    Explore
                    <ChevronRight className="ml-1 h-3 w-3" />
                  </Button>
                </div>
                <div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm">
                  <Icon className="h-8 w-8 text-white" strokeWidth={1.5} />
                </div>
              </div>
            );
          })}
        </div>
        {/* Banner Dots */}
        <div className="mt-2 flex justify-center gap-1.5">
          {adBanners.map((_, idx) => (
            <button
              key={idx}
              className={`h-1.5 rounded-full transition-all duration-300 ${
                idx === activeBanner
                  ? 'w-6 bg-primary'
                  : 'w-1.5 bg-muted-foreground/20'
              }`}
              onClick={() => {
                setActiveBanner(idx);
                if (bannerScrollRef.current) {
                  const child = bannerScrollRef.current.children[idx] as HTMLElement;
                  if (child) {
                    bannerScrollRef.current.scrollTo({
                      left: child.offsetLeft,
                      behavior: 'smooth',
                    });
                  }
                }
              }}
              aria-label={`Go to banner ${idx + 1}`}
            />
          ))}
        </div>
      </div>

      {/* ── Quick Service Icons ────────────────────────────── */}
      <div className="px-4 py-3">
        <div className="flex gap-3 overflow-x-auto scrollbar-hide pb-1">
          {quickServices.map((service) => {
            const Icon = service.icon;
            return (
              <button
                key={service.id}
                onClick={() => setCurrentSection(service.id)}
                className="flex flex-col items-center gap-1.5 min-w-[4.2rem] group"
              >
                <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground shadow-sm transition-transform group-hover:scale-105 group-active:scale-95">
                  <Icon className="h-6 w-6" strokeWidth={1.8} />
                </div>
                <span className="text-[10px] font-medium text-muted-foreground leading-tight text-center max-w-[4.2rem] truncate">
                  {t(service.labelKey, language)}
                </span>
              </button>
            );
          })}
        </div>
      </div>

      {/* ── Featured Listings ──────────────────────────────── */}
      <section className="py-3">
        <div className="flex items-center justify-between px-4 pb-2">
          <h2 className="text-base font-bold text-foreground">
            {t('home.featured', language)}
          </h2>
          <Button
            variant="ghost"
            size="sm"
            className="h-7 gap-0.5 text-xs font-semibold text-primary"
            onClick={() => setCurrentSection('house-rental')}
          >
            {t('home.seeAll', language)}
            <ChevronRight className="h-3.5 w-3.5" />
          </Button>
        </div>
        <div className="flex gap-3 overflow-x-auto scrollbar-hide px-4 pb-1">
          {featuredHouses.map((house) => (
            <Card
              key={house.id}
              className="min-w-[15rem] max-w-[15rem] cursor-pointer overflow-hidden border-border/40 py-0 shadow-sm transition-shadow hover:shadow-md"
              onClick={() => setCurrentSection('house-rental')}
            >
              {/* Image Placeholder */}
              <div className="relative h-28 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-10 w-10 text-white/50" strokeWidth={1.2} />
                </div>
                {house.rentType === 'family' && (
                  <Badge className="absolute left-2 top-2 bg-emerald-500 text-white text-[9px] px-1.5 py-0 border-0">
                    {t('house.family', language)}
                  </Badge>
                )}
                {house.rentType === 'bachelor' && (
                  <Badge className="absolute left-2 top-2 bg-orange-500 text-white text-[9px] px-1.5 py-0 border-0">
                    {t('house.bachelor', language)}
                  </Badge>
                )}
              </div>
              <CardContent className="p-3">
                <h3 className="truncate text-sm font-semibold text-foreground leading-tight">
                  {house.title}
                </h3>
                <div className="mt-1 flex items-center gap-1 text-muted-foreground">
                  <MapPin className="h-3 w-3 shrink-0" />
                  <span className="truncate text-[10px]">{house.upazila}, {house.district}</span>
                </div>
                <div className="mt-1.5 flex items-center gap-2 text-[10px] text-muted-foreground">
                  <span className="flex items-center gap-0.5">
                    <BedDouble className="h-3 w-3" />
                    {house.rooms}
                  </span>
                  <span className="flex items-center gap-0.5">
                    <Bath className="h-3 w-3" />
                    {house.bathrooms}
                  </span>
                  <span>{house.area} sqft</span>
                </div>
                <div className="mt-2 flex items-baseline gap-0.5">
                  <span className="text-base font-bold text-primary">
                    ৳{house.price.toLocaleString()}
                  </span>
                  <span className="text-[10px] text-muted-foreground">
                    {t('house.perMonth', language)}
                  </span>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </section>

      {/* ── Popular Products ───────────────────────────────── */}
      <section className="py-3">
        <div className="flex items-center justify-between px-4 pb-2">
          <h2 className="text-base font-bold text-foreground">
            {t('home.popularProducts', language)}
          </h2>
          <Button
            variant="ghost"
            size="sm"
            className="h-7 gap-0.5 text-xs font-semibold text-primary"
            onClick={() => setCurrentSection('marketplace')}
          >
            {t('home.seeAll', language)}
            <ChevronRight className="h-3.5 w-3.5" />
          </Button>
        </div>
        <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-[12rem] max-w-[12rem] cursor-pointer overflow-hidden border-border/40 py-0 shadow-sm transition-shadow hover:shadow-md"
                onClick={() => setCurrentSection('marketplace')}
              >
                {/* Image Placeholder */}
                <div className="relative h-24 w-full bg-gradient-to-br from-amber-200 to-orange-200">
                  <div className="absolute inset-0 flex items-center justify-center">
                    <ShoppingBag className="h-8 w-8 text-orange-400/50" 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-3">
                  <h3 className="truncate text-sm font-semibold text-foreground leading-tight">
                    {product.title}
                  </h3>
                  <div className="mt-1 flex items-center gap-1">
                    <Star className="h-3 w-3 fill-amber-400 text-amber-400" />
                    <span className="text-[10px] font-medium text-foreground">
                      {product.rating}
                    </span>
                    <span className="text-[10px] text-muted-foreground">
                      ({product.reviewCount})
                    </span>
                  </div>
                  <div className="mt-1.5 flex items-baseline gap-1.5">
                    <span className="text-base 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.5 text-[9px] px-1.5 border-0 ${catColor}`}>
                    {product.category}
                  </Badge>
                  <Button
                    size="sm"
                    className={`mt-2 h-7 w-full rounded-lg text-[11px] 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-3 w-3" />
                        {language === 'en' ? 'Added' : 'যোগ হয়েছে'}
                      </>
                    ) : (
                      <>
                        <ShoppingCart className="mr-1 h-3 w-3" />
                        {t('market.addToCart', language)}
                      </>
                    )}
                  </Button>
                </CardContent>
              </Card>
            );
          })}
        </div>
      </section>

      {/* ── Trending MCQ ───────────────────────────────────── */}
      <section className="px-4 py-3">
        <div className="flex items-center justify-between pb-2">
          <h2 className="text-base font-bold text-foreground">
            {t('home.trendingMcq', language)}
          </h2>
        </div>
        <Card className="overflow-hidden border-border/40 shadow-sm">
          <div className="bg-gradient-to-r from-orange-50 to-amber-50 p-4 dark:from-orange-950/20 dark:to-amber-950/20">
            <div className="flex items-start gap-3">
              <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-primary/10">
                <Sparkles className="h-6 w-6 text-primary" strokeWidth={1.8} />
              </div>
              <div className="flex-1">
                <h3 className="text-sm font-bold text-foreground">
                  {t('home.trendingMcq', language)}
                </h3>
                <p className="mt-0.5 text-[10px] text-muted-foreground">
                  Practice & improve your scores
                </p>
                <div className="mt-2 flex flex-wrap gap-1.5">
                  {mcqCategories.map((cat) => (
                    <Badge
                      key={cat.id}
                      variant="secondary"
                      className={`cursor-pointer text-[10px] border-0 ${catColorHandler(cat.color)}`}
                    >
                      {t(cat.labelKey, language)}
                    </Badge>
                  ))}
                </div>
                <Button
                  size="sm"
                  className="mt-3 h-8 rounded-full bg-gradient-to-r from-primary to-primary/90 text-xs font-semibold"
                  onClick={() => setCurrentSection('education')}
                >
                  <GraduationCap className="mr-1 h-3.5 w-3.5" />
                  Start Quiz
                </Button>
              </div>
            </div>
          </div>
        </Card>
      </section>

      {/* ── Nearby Services ────────────────────────────────── */}
      <section className="px-4 py-3">
        <div className="flex items-center justify-between pb-2">
          <h2 className="text-base font-bold text-foreground">
            {t('home.nearbyServices', language)}
          </h2>
        </div>
        <div className="grid grid-cols-2 gap-2">
          {nearbyServices.map((service) => {
            const Icon = service.icon;
            return (
              <Card
                key={service.id}
                className="cursor-pointer border-border/40 py-0 shadow-sm transition-shadow hover:shadow-md"
                onClick={() => setCurrentSection(service.section)}
              >
                <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-primary/10">
                    <Icon className="h-5 w-5 text-primary" strokeWidth={1.8} />
                  </div>
                  <div className="min-w-0 flex-1">
                    <h4 className="truncate text-xs font-semibold text-foreground">
                      {service.name}
                    </h4>
                    <span className="text-[10px] text-muted-foreground">
                      {service.distance}
                    </span>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      </section>
    </div>
  );
}

// ─── Helper ──────────────────────────────────────────────────────────
function catColorHandler(color: string): string {
  return color;
}
