import React, { useMemo, useState } from "react";
import { motion } from "framer-motion";
import {
  ShoppingCart,
  Search,
  Store,
  Star,
  Truck,
  ShieldCheck,
  Phone,
  Menu,
  X,
  Filter,
  ChevronDown,
} from "lucide-react";

// shadcn/ui components
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Sheet,
  SheetTrigger,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetFooter,
  SheetClose,
} from "@/components/ui/sheet";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
  SelectValue,
} from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";

// ————————— إعداد بيانات وهمية —————————
const CATEGORIES = [
  { id: "all", name: "الكل" },
  { id: "skins", name: "جلود" },
  { id: "accessories", name: "إكسسوارات" },
  { id: "care", name: "العناية" },
];

const PRODUCTS = [
  {
    id: 1,
    name: "حافظة جلد طبيعي للهاتف",
    price: 149,
    rating: 4.8,
    category: "skins",
    badge: "الأكثر مبيعًا",
    image:
      "https://images.unsplash.com/photo-1512496015851-a90fb38ba796?q=80&w=1200&auto=format&fit=crop",
  },
  {
    id: 2,
    name: "محفظة جلد يدوي",
    price: 199,
    rating: 4.6,
    category: "accessories",
    badge: "جديد",
    image:
      "https://images.unsplash.com/photo-1610394216011-2b9e19f0c1d7?q=80&w=1200&auto=format&fit=crop",
  },
  {
    id: 3,
    name: "سوار جلد طبيعي",
    price: 99,
    rating: 4.5,
    category: "accessories",
    image:
      "https://images.unsplash.com/photo-1542272604-787c3835535d?q=80&w=1200&auto=format&fit=crop",
  },
  {
    id: 4,
    name: "حقيبة كتف جلد فاخر",
    price: 449,
    rating: 4.9,
    category: "skins",
    badge: "مميز",
    image:
      "https://images.unsplash.com/photo-1604176354204-926873782c56?q=80&w=1200&auto=format&fit=crop",
  },
  {
    id: 5,
    name: "طقم عناية بالجلد",
    price: 129,
    rating: 4.3,
    category: "care",
    image:
      "https://images.unsplash.com/photo-1604335399105-a0d7b4b91a75?q=80&w=1200&auto=format&fit=crop",
  },
  {
    id: 6,
    name: "جراب لابتوب جلد",
    price: 279,
    rating: 4.7,
    category: "skins",
    image:
      "https://images.unsplash.com/photo-1498049794561-7780e7231661?q=80&w=1200&auto=format&fit=crop",
  },
];

function formatSAR(n) {
  return new Intl.NumberFormat("ar-SA", {
    style: "currency",
    currency: "SAR",
    maximumFractionDigits: 0,
  }).format(n);
}

function ProductCard({ product, onAdd }) {
  return (
    <motion.div
      layout
      whileHover={{ y: -4 }}
      className="h-full"
    >
      <Card className="h-full overflow-hidden rounded-2xl shadow-sm border border-neutral-200/60">
        <CardHeader className="p-0">
          <div className="relative aspect-[4/3] w-full overflow-hidden bg-neutral-100">
            <img
              src={product.image}
              alt={product.name}
              className="h-full w-full object-cover transition-transform duration-300 hover:scale-105"
              loading="lazy"
            />
            {product.badge && (
              <Badge className="absolute top-3 end-3 rounded-xl text-xs">
                {product.badge}
              </Badge>
            )}
          </div>
        </CardHeader>
        <CardContent className="p-4 space-y-3">
          <div className="flex items-start justify-between gap-3">
            <CardTitle className="text-base font-semibold leading-6">
              {product.name}
            </CardTitle>
            <div className="text-sm font-bold whitespace-nowrap">
              {formatSAR(product.price)}
            </div>
          </div>
          <div className="flex items-center gap-1 text-sm text-amber-600" aria-label={`التقييم ${product.rating}`}>
            <Star className="h-4 w-4 fill-current" />
            <span className="text-neutral-600">{product.rating}</span>
          </div>
          <Button onClick={() => onAdd(product)} className="w-full rounded-xl">
            <ShoppingCart className="ms-2 h-4 w-4" /> أضف إلى السلة
          </Button>
        </CardContent>
      </Card>
    </motion.div>
  );
}

function CartItem({ item, onChangeQty, onRemove }) {
  return (
    <div className="flex items-center gap-3 py-3">
      <img
        src={item.image}
        alt={item.name}
        className="h-16 w-16 rounded-xl object-cover"
      />
      <div className="flex-1 space-y-1">
        <div className="flex items-center justify-between">
          <span className="font-medium">{item.name}</span>
          <Button variant="ghost" size="icon" onClick={() => onRemove(item.id)}>
            <X className="h-4 w-4" />
          </Button>
        </div>
        <div className="text-sm text-neutral-500">{formatSAR(item.price)}</div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={() => onChangeQty(item.id, Math.max(1, item.qty - 1))}>-</Button>
          <span className="text-sm w-6 text-center">{item.qty}</span>
          <Button variant="outline" size="sm" onClick={() => onChangeQty(item.id, item.qty + 1)}>+</Button>
        </div>
      </div>
    </div>
  );
}

export default function Storefront() {
  const [query, setQuery] = useState("");
  const [category, setCategory] = useState("all");
  const [sort, setSort] = useState("popular");
  const [cartOpen, setCartOpen] = useState(false);
  const [filterOpen, setFilterOpen] = useState(false);
  const [priceRange, setPriceRange] = useState([0, 500]);
  const [cart, setCart] = useState([]);

  const filtered = useMemo(() => {
    let items = PRODUCTS.filter((p) =>
      (category === "all" || p.category === category) &&
      p.price >= priceRange[0] && p.price <= priceRange[1] &&
      p.name.toLowerCase().includes(query.toLowerCase())
    );

    if (sort === "price_low") items.sort((a, b) => a.price - b.price);
    if (sort === "price_high") items.sort((a, b) => b.price - a.price);
    if (sort === "rating") items.sort((a, b) => b.rating - a.rating);

    return items;
  }, [query, category, sort, priceRange]);

  const total = cart.reduce((s, i) => s + i.price * i.qty, 0);

  function addToCart(p) {
    setCart((prev) => {
      const ex = prev.find((x) => x.id === p.id);
      if (ex) return prev.map((x) => (x.id === p.id ? { ...x, qty: x.qty + 1 } : x));
      return [...prev, { ...p, qty: 1 }];
    });
    setCartOpen(true);
  }

  function changeQty(id, qty) {
    setCart((prev) => prev.map((x) => (x.id === id ? { ...x, qty } : x)));
  }

  function removeFromCart(id) {
    setCart((prev) => prev.filter((x) => x.id !== id));
  }

  return (
    <div dir="rtl" lang="ar" className="min-h-screen bg-neutral-50">
      {/* شريط علوي */}
      <header className="sticky top-0 z-40 border-b bg-white/80 backdrop-blur">
        <div className="mx-auto max-w-7xl px-4 py-3">
          <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-2">
              <Store className="h-6 w-6" />
              <span className="font-extrabold text-lg">متجر الجلود</span>
            </div>

            <div className="hidden md:flex items-center gap-2 max-w-xl flex-1">
              <div className="relative w-full">
                <Search className="absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-neutral-400" />
                <Input
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  placeholder="ابحث عن منتج…"
                  className="ps-9 rounded-xl"
                />
              </div>
              <Select value={sort} onValueChange={setSort}>
                <SelectTrigger className="w-40 rounded-xl">
                  <SelectValue placeholder="الترتيب" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="popular">الأكثر شيوعًا</SelectItem>
                  <SelectItem value="price_low">السعر: من الأقل للأعلى</SelectItem>
                  <SelectItem value="price_high">السعر: من الأعلى للأقل</SelectItem>
                  <SelectItem value="rating">الأعلى تقييمًا</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center gap-2">
              <Button variant="outline" className="rounded-xl md:hidden" onClick={() => setFilterOpen(true)}>
                <Filter className="ms-2 h-4 w-4" /> تصفية
              </Button>

              <Sheet open={cartOpen} onOpenChange={setCartOpen}>
                <SheetTrigger asChild>
                  <Button className="rounded-xl">
                    <ShoppingCart className="ms-2 h-4 w-4" /> السلة ({cart.reduce((s,i)=>s+i.qty,0)})
                  </Button>
                </SheetTrigger>
                <SheetContent side="left" className="w-full sm:max-w-md">
                  <SheetHeader>
                    <SheetTitle>سلة التسوق</SheetTitle>
                  </SheetHeader>
                  <div className="mt-4 space-y-2">
                    {cart.length === 0 && (
                      <div className="text-neutral-500">لا توجد منتجات في السلة.</div>
                    )}
                    {cart.map((item) => (
                      <CartItem
                        key={item.id}
                        item={item}
                        onChangeQty={changeQty}
                        onRemove={removeFromCart}
                      />
                    ))}
                  </div>
                  <div className="mt-6 border-t pt-4 flex items-center justify-between">
                    <span className="font-semibold">الإجمالي</span>
                    <span className="text-lg font-bold">{formatSAR(total)}</span>
                  </div>
                  <SheetFooter className="mt-4">
                    <Button className="w-full rounded-xl">إتمام الشراء</Button>
                    <SheetClose asChild>
                      <Button variant="ghost" className="w-full rounded-xl">متابعة التسوق</Button>
                    </SheetClose>
                  </SheetFooter>
                </SheetContent>
              </Sheet>
            </div>
          </div>

          {/* شريط أدوات للجوال */}
          <div className="mt-3 grid grid-cols-2 gap-2 md:hidden">
            <div className="relative">
              <Search className="absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-neutral-400" />
              <Input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="ابحث عن منتج…"
                className="ps-9 rounded-xl"
              />
            </div>
            <Select value={sort} onValueChange={setSort}>
              <SelectTrigger className="rounded-xl">
                <SelectValue placeholder="الترتيب" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="popular">الأكثر شيوعًا</SelectItem>
                <SelectItem value="price_low">السعر: من الأقل للأعلى</SelectItem>
                <SelectItem value="price_high">السعر: من الأعلى للأقل</SelectItem>
                <SelectItem value="rating">الأعلى تقييمًا</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </header>

      {/* بطل الصفحة */}
      <section className="relative overflow-hidden bg-gradient-to-b from-amber-50 to-white">
        <div className="mx-auto max-w-7xl px-4 py-12 sm:py-16">
          <div className="grid items-center gap-10 md:grid-cols-2">
            <motion.div
              initial={{ opacity: 0, y: 16 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
              className="space-y-4"
            >
              <Badge className="rounded-xl">جلود طبيعية مختارة بعناية</Badge>
              <h1 className="text-3xl sm:text-4xl font-extrabold leading-tight">
                ارتقِ بإطلالتك مع منتجات جلدية فاخرة
              </h1>
              <p className="text-neutral-600">
                متجر متخصص في الجلود والإكسسوارات المصنوعة بإتقان. جودة عالية، شحن سريع، وضمان استرجاع.
              </p>
              <div className="flex flex-wrap items-center gap-3">
                <Button className="rounded-xl" onClick={() => document.getElementById('grid')?.scrollIntoView({behavior: 'smooth'})}>
                  تسوق الآن
                </Button>
                <Button variant="outline" className="rounded-xl">تواصل معنا</Button>
              </div>
              <div className="mt-6 grid grid-cols-3 gap-3 text-sm">
                <Feature icon={Truck} title="شحن سريع" />
                <Feature icon={ShieldCheck} title="ضمان أصلي" />
                <Feature icon={Phone} title="دعم فوري" />
              </div>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, scale: 0.98 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.6, delay: 0.1 }}
              className="relative"
            >
              <div className="aspect-square w-full rounded-3xl bg-[url('https://images.unsplash.com/photo-1553062407-98eeb64c6a62?q=80&w=1200&auto=format&fit=crop')] bg-cover bg-center shadow-2xl" />
            </motion.div>
          </div>
        </div>
      </section>

      {/* تصفية جانبية لسطح المكتب */}
      <div className="mx-auto max-w-7xl px-4 py-10 grid grid-cols-12 gap-6">
        <aside className="hidden md:block md:col-span-3 lg:col-span-2">
          <Filters
            category={category}
            onCategory={setCategory}
            priceRange={priceRange}
            onPrice={setPriceRange}
          />
        </aside>

        <main className="col-span-12 md:col-span-9 lg:col-span-10">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="text-xl font-bold">المنتجات</h2>
            <div className="hidden md:flex items-center gap-2">
              {CATEGORIES.map((c) => (
                <Button
                  key={c.id}
                  variant={category === c.id ? "default" : "outline"}
                  className="rounded-xl"
                  onClick={() => setCategory(c.id)}
                >
                  {c.name}
                </Button>
              ))}
            </div>

            {/* زر تصفية للجوال */}
            <Button className="md:hidden rounded-xl" variant="outline" onClick={() => setFilterOpen(true)}>
              <Filter className="ms-2 h-4 w-4" /> عوامل التصفية
            </Button>
          </div>

          {/* شبكة المنتجات */}
          <div id="grid" className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
            {filtered.map((p) => (
              <ProductCard key={p.id} product={p} onAdd={addToCart} />
            ))}
          </div>
        </main>
      </div>

      {/* نافذة التصفية للجوال */}
      <Dialog open={filterOpen} onOpenChange