'use client';

import { useMemo, useState } from 'react';
import { ShoppingCart, Search, Phone, Minus, Plus, Trash2, ShoppingBag, X, CheckCircle2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { Textarea } from '@/components/ui/textarea';

type StoreItem = {
  id: string;
  name: string;
  nameEn?: string;
  salePrice: number;
  storeSectionId?: string;
  barcode?: string;
  primaryUnit?: string;
  description?: string;
  stockQuantity?: number | null; // null = no inventory data (treat as unlimited)
};

type ItemGroup = {
  id: string;
  name: string;
};

type CartEntry = {
  item: StoreItem;
  quantity: number;
};

type Props = {
  items: StoreItem[];
  itemGroups: ItemGroup[];
  storeName: string;
  storeDescription: string;
  storeContactPhone: string;
  currencySymbol: string;
};

export default function StorePageClient({
  items,
  itemGroups,
  storeName,
  storeDescription,
  storeContactPhone,
  currencySymbol,
}: Props) {
  const normalizeSearchText = (value: string) =>
    String(value || '')
      .toLowerCase()
      .replace(/[\u064B-\u0652]/g, '')
      .replace(/[أإآ]/g, 'ا')
      .replace(/ة/g, 'ه')
      .replace(/ى/g, 'ي')
      .replace(/\s+/g, ' ')
      .trim();

  const toArabicDigits = (value: string) =>
    String(value || '').replace(/\d/g, (digit) => String.fromCharCode(digit.charCodeAt(0) + 1584));

  const [searchQuery, setSearchQuery] = useState('');
  const [selectedSection, setSelectedSection] = useState('all');
  const [cart, setCart] = useState<CartEntry[]>([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [successOpen, setSuccessOpen] = useState(false);
  const [submittedInvoiceNumber, setSubmittedInvoiceNumber] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Checkout form
  const [customerName, setCustomerName] = useState('');
  const [customerAddress, setCustomerAddress] = useState('');
  const [customerPhone, setCustomerPhone] = useState('');
  const [customerNote, setCustomerNote] = useState('');
  const [formError, setFormError] = useState('');

  const cartCount = cart.reduce((sum, e) => sum + e.quantity, 0);
  const cartTotal = cart.reduce((sum, e) => sum + e.quantity * Number(e.item.salePrice || 0), 0);

  const filteredItems = useMemo(() => {
    const q = normalizeSearchText(searchQuery);
    const terms = q.split(' ').filter(Boolean);

    return items.filter((item) => {
      if (selectedSection !== 'all' && item.storeSectionId !== selectedSection) return false;
      if (terms.length > 0) {
        const stockQty = item.stockQuantity !== null && item.stockQuantity !== undefined ? Number(item.stockQuantity) : null;
        const stockLabel = stockQty === null ? 'غير متتبع' : stockQty > 0 ? `الرصيد ${stockQty}` : 'الرصيد 0 نفذ';
        const priceValue = Number(item.salePrice || 0);
        const priceEn = priceValue.toFixed(2);
        const priceAr = toArabicDigits(priceEn);

        // Search across all visible product-card parts and related metadata.
        const searchableText = normalizeSearchText([
          item.name,
          item.nameEn,
          item.barcode,
          item.description,
          item.primaryUnit,
          item.id,
          stockLabel,
          String(stockQty ?? ''),
          priceEn,
          priceAr,
          formatPrice(priceValue),
          currencySymbol,
        ].join(' '));

        const matchesAllTerms = terms.every((term) => searchableText.includes(term));
        if (!matchesAllTerms) return false;
      }
      return true;
    });
  }, [items, searchQuery, selectedSection, currencySymbol]);

  const addToCart = (item: StoreItem) => {
    const stock = Number(item.stockQuantity ?? Infinity);
    setCart((prev) => {
      const existing = prev.find((e) => e.item.id === item.id);
      if (existing) {
        if (existing.quantity >= stock) return prev;
        return prev.map((e) => e.item.id === item.id ? { ...e, quantity: e.quantity + 1 } : e);
      }
      if (stock <= 0) return prev;
      return [...prev, { item, quantity: 1 }];
    });
  };

  const updateQty = (itemId: string, delta: number) => {
    setCart((prev) =>
      prev
        .map((e) => {
          if (e.item.id !== itemId) return e;
          const stock = Number(e.item.stockQuantity ?? Infinity);
          const next = e.quantity + delta;
          return { ...e, quantity: Math.min(next, stock) };
        })
        .filter((e) => e.quantity > 0)
    );
  };

  const removeFromCart = (itemId: string) => {
    setCart((prev) => prev.filter((e) => e.item.id !== itemId));
  };

  const openCheckout = () => {
    setCartOpen(false);
    setFormError('');
    setCheckoutOpen(true);
  };

  const submitOrder = async () => {
    const name = customerName.trim();
    const address = customerAddress.trim();
    const phone = customerPhone.trim();

    if (!name || !address || !phone) {
      setFormError('يرجى تعبئة الاسم والعنوان ورقم الجوال');
      return;
    }

    setIsSubmitting(true);
    setFormError('');

    try {
      const response = await fetch('/api/store/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          customerName: name,
          customerAddress: address,
          customerPhone: phone,
          customerNote: customerNote.trim() || undefined,
          items: cart.map((e) => ({
            materialId: e.item.id,
            quantity: e.quantity,
            unitPrice: Number(e.item.salePrice || 0),
          })),
        }),
      });

      const data = await response.json().catch(() => ({}));

      if (!response.ok) {
        setFormError(data?.error || 'حدث خطأ أثناء إرسال الطلب، يرجى المحاولة مرة أخرى');
        return;
      }

      setSubmittedInvoiceNumber(data.invoiceNumber || '');
      setCheckoutOpen(false);
      setSuccessOpen(true);
      setCart([]);
      setCustomerName('');
      setCustomerAddress('');
      setCustomerPhone('');
      setCustomerNote('');
    } catch {
      setFormError('تعذر الاتصال بالخادم، يرجى التحقق من الإنترنت والمحاولة مرة أخرى');
    } finally {
      setIsSubmitting(false);
    }
  };

  // Sections that actually have items
  const activeSections = useMemo(() => {
    const usedIds = new Set(items.map((i) => i.storeSectionId).filter(Boolean));
    return itemGroups.filter((g) => usedIds.has(g.id));
  }, [items, itemGroups]);

  function formatPrice(price: number) {
    return `${Number(price || 0).toLocaleString('ar-SA', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} ${currencySymbol}`;
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* ===== Header ===== */}
      <header className="sticky top-0 z-40 border-b bg-white dark:bg-gray-950 shadow-sm">
        <div className="mx-auto max-w-6xl flex items-center justify-between gap-4 px-4 py-3">
          <div className="flex items-center gap-3">
            <ShoppingBag className="h-7 w-7 text-primary" />
            <div>
              <h1 className="text-lg font-bold leading-tight">{storeName}</h1>
              {storeDescription && (
                <p className="text-xs text-muted-foreground hidden sm:block">{storeDescription}</p>
              )}
            </div>
          </div>

          <div className="flex items-center gap-2">
            {storeContactPhone && (
              <a
                href={`tel:${storeContactPhone}`}
                className="hidden sm:flex items-center gap-1 text-sm text-muted-foreground hover:text-primary"
              >
                <Phone className="h-4 w-4" />
                {storeContactPhone}
              </a>
            )}
            <div className="relative hidden md:flex items-center">
              <Search className="absolute right-3 h-4 w-4 text-muted-foreground pointer-events-none" />
              <Input
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="بحث في المنتجات..."
                className="w-80 pr-9 text-sm"
              />
            </div>
            <Button
              variant="outline"
              size="sm"
              className="relative"
              onClick={() => setCartOpen(true)}
            >
              <ShoppingCart className="h-4 w-4" />
              {cartCount > 0 && (
                <Badge className="absolute -top-2 -left-2 h-5 w-5 flex items-center justify-center p-0 text-xs">
                  {cartCount}
                </Badge>
              )}
            </Button>
          </div>
        </div>

        {/* Mobile search */}
        <div className="md:hidden px-4 pb-2">
          <div className="relative flex items-center">
            <Search className="absolute right-3 h-4 w-4 text-muted-foreground pointer-events-none" />
            <Input
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="بحث في المنتجات..."
              className="w-full pr-9 text-sm"
            />
          </div>
        </div>
      </header>

      {/* ===== Category Filter ===== */}
      {activeSections.length > 0 && (
        <div className="sticky top-[73px] z-30 border-b bg-white dark:bg-gray-950 overflow-x-auto">
          <div className="mx-auto max-w-6xl flex gap-2 px-4 py-2">
            <button
              onClick={() => setSelectedSection('all')}
              className={`whitespace-nowrap rounded-full px-4 py-1.5 text-sm font-medium transition-colors ${
                selectedSection === 'all'
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-muted hover:bg-muted/80'
              }`}
            >
              الكل ({items.length})
            </button>
            {activeSections.map((section) => {
              const count = items.filter((i) => i.storeSectionId === section.id).length;
              return (
                <button
                  key={section.id}
                  onClick={() => setSelectedSection(section.id)}
                  className={`whitespace-nowrap rounded-full px-4 py-1.5 text-sm font-medium transition-colors ${
                    selectedSection === section.id
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-muted hover:bg-muted/80'
                  }`}
                >
                  {section.name} ({count})
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* ===== Products Grid ===== */}
      <main className="mx-auto max-w-6xl px-4 py-6">
        {filteredItems.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-center text-muted-foreground gap-3">
            <ShoppingBag className="h-12 w-12 opacity-30" />
            <p className="text-lg font-medium">لا توجد منتجات متاحة حالياً</p>
            {searchQuery && (
              <Button variant="outline" size="sm" onClick={() => setSearchQuery('')}>
                مسح البحث
              </Button>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
            {filteredItems.map((item) => {
              const cartEntry = cart.find((e) => e.item.id === item.id);
              return (
                <div
                  key={item.id}
                  className="flex flex-col rounded-xl border bg-white dark:bg-gray-950 shadow-sm hover:shadow-md transition-shadow overflow-hidden"
                >
                  {/* Placeholder image */}
                  <div className="flex h-36 items-center justify-center bg-gradient-to-br from-primary/5 to-primary/15">
                    <ShoppingBag className="h-12 w-12 text-primary/30" />
                  </div>

                  <div className="flex flex-col flex-1 p-3 gap-2">
                    <h3 className="text-sm font-semibold leading-snug line-clamp-2">{item.name}</h3>
                    {item.primaryUnit && (
                      <p className="text-xs text-muted-foreground">{item.primaryUnit}</p>
                    )}
                    <div className="flex items-center justify-between gap-1 mt-auto">
                      <p className="text-base font-bold text-primary">{formatPrice(Number(item.salePrice || 0))}</p>
                      {item.stockQuantity !== null && item.stockQuantity !== undefined && (
                        <span className={`text-xs px-1.5 py-0.5 rounded-full font-medium ${
                          item.stockQuantity > 5
                            ? 'bg-green-50 text-green-700 border border-green-200'
                            : item.stockQuantity > 0
                            ? 'bg-amber-50 text-amber-700 border border-amber-200'
                            : 'bg-red-50 text-red-600 border border-red-200'
                        }`}>
                          {item.stockQuantity > 0
                            ? `الرصيد ${Number(item.stockQuantity).toLocaleString('ar-SA')}`
                            : 'الرصيد 0 (نفذ)'}
                        </span>
                      )}
                    </div>

                    {item.stockQuantity === 0 ? (
                      <Button size="sm" className="w-full" disabled variant="outline">
                        نفذت الكمية
                      </Button>
                    ) : cartEntry ? (
                      <div className="flex items-center justify-between rounded-md border px-2 py-1 gap-2">
                        <button
                          onClick={() => updateQty(item.id, -1)}
                          className="flex h-6 w-6 items-center justify-center rounded hover:bg-muted"
                        >
                          <Minus className="h-3 w-3" />
                        </button>
                        <span className="text-sm font-bold min-w-[20px] text-center">{cartEntry.quantity}</span>
                        <button
                          onClick={() => updateQty(item.id, 1)}
                          disabled={item.stockQuantity !== null && item.stockQuantity !== undefined && cartEntry.quantity >= item.stockQuantity}
                          className="flex h-6 w-6 items-center justify-center rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed"
                        >
                          <Plus className="h-3 w-3" />
                        </button>
                      </div>
                    ) : (
                      <Button size="sm" className="w-full" onClick={() => addToCart(item)}>
                        أضف للسلة
                      </Button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </main>

      {/* ===== Cart Drawer ===== */}
      <Sheet open={cartOpen} onOpenChange={setCartOpen}>
        <SheetContent side="left" className="w-full sm:max-w-md flex flex-col gap-0 p-0">
          <SheetHeader className="px-4 py-4 border-b">
            <SheetTitle className="flex items-center gap-2">
              <ShoppingCart className="h-5 w-5" />
              سلة التسوق
              {cartCount > 0 && <Badge>{cartCount}</Badge>}
            </SheetTitle>
          </SheetHeader>

          {cart.length === 0 ? (
            <div className="flex flex-1 flex-col items-center justify-center gap-3 text-muted-foreground p-8">
              <ShoppingCart className="h-12 w-12 opacity-30" />
              <p>السلة فارغة</p>
            </div>
          ) : (
            <>
              <div className="flex-1 overflow-y-auto p-4 space-y-3">
                {cart.map((entry) => (
                  <div key={entry.item.id} className="flex items-center gap-3 rounded-lg border p-3">
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium truncate">{entry.item.name}</p>
                      <p className="text-xs text-muted-foreground">{formatPrice(Number(entry.item.salePrice || 0))}</p>
                    </div>
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => updateQty(entry.item.id, -1)}
                        className="flex h-7 w-7 items-center justify-center rounded border hover:bg-muted"
                      >
                        <Minus className="h-3 w-3" />
                      </button>
                      <span className="w-8 text-center text-sm font-bold">{entry.quantity}</span>
                      <button
                        onClick={() => updateQty(entry.item.id, 1)}
                        className="flex h-7 w-7 items-center justify-center rounded border hover:bg-muted"
                      >
                        <Plus className="h-3 w-3" />
                      </button>
                    </div>
                    <button
                      onClick={() => removeFromCart(entry.item.id)}
                      className="text-muted-foreground hover:text-destructive"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                ))}
              </div>

              <div className="border-t p-4 space-y-3">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">
                    {cartCount} منتج
                  </span>
                  <span className="text-lg font-bold">{formatPrice(cartTotal)}</span>
                </div>
                <Button className="w-full" size="lg" onClick={openCheckout}>
                  إتمام الشراء
                </Button>
              </div>
            </>
          )}
        </SheetContent>
      </Sheet>

      {/* ===== Checkout Dialog ===== */}
      <Dialog open={checkoutOpen} onOpenChange={setCheckoutOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>بيانات التوصيل</DialogTitle>
            <DialogDescription>
              أدخل بياناتك لإتمام الطلب وسيتم التواصل معك في أقرب وقت
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="c-name">الاسم الكامل *</Label>
              <Input
                id="c-name"
                value={customerName}
                onChange={(e) => setCustomerName(e.target.value)}
                placeholder="أدخل اسمك الكامل"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="c-address">العنوان / المنطقة *</Label>
              <Input
                id="c-address"
                value={customerAddress}
                onChange={(e) => setCustomerAddress(e.target.value)}
                placeholder="المدينة - الحي - الشارع"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="c-phone">رقم الجوال *</Label>
              <Input
                id="c-phone"
                type="tel"
                value={customerPhone}
                onChange={(e) => setCustomerPhone(e.target.value)}
                placeholder="05xxxxxxxx"
                dir="ltr"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="c-note">ملاحظة (اختياري)</Label>
              <Textarea
                id="c-note"
                value={customerNote}
                onChange={(e) => setCustomerNote(e.target.value)}
                placeholder="أي تعليمات خاصة للتوصيل..."
                rows={2}
              />
            </div>

            {/* Order summary */}
            <div className="rounded-md bg-muted/50 p-3 space-y-1">
              {cart.map((entry) => (
                <div key={entry.item.id} className="flex justify-between text-sm">
                  <span className="truncate">{entry.item.name} × {entry.quantity}</span>
                  <span>{formatPrice(Number(entry.item.salePrice || 0) * entry.quantity)}</span>
                </div>
              ))}
              <div className="flex justify-between font-bold border-t pt-1 mt-1">
                <span>الإجمالي</span>
                <span>{formatPrice(cartTotal)}</span>
              </div>
            </div>

            {formError && (
              <p className="text-sm text-destructive rounded-md bg-destructive/10 px-3 py-2">{formError}</p>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setCheckoutOpen(false)} disabled={isSubmitting}>
              إلغاء
            </Button>
            <Button onClick={submitOrder} disabled={isSubmitting}>
              {isSubmitting ? 'جاري الإرسال...' : 'تأكيد الطلب'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* ===== Success Dialog ===== */}
      <Dialog open={successOpen} onOpenChange={setSuccessOpen}>
        <DialogContent className="max-w-sm text-center">
          <DialogHeader>
            <DialogTitle>تم استلام طلبك</DialogTitle>
            <DialogDescription>
              تم إنشاء الطلب بنجاح وسيتم التواصل معك قريباً لتأكيد التوصيل.
            </DialogDescription>
          </DialogHeader>
          <div className="flex flex-col items-center gap-4 py-4">
            <CheckCircle2 className="h-16 w-16 text-green-500" />
            <div>
              <h2 className="text-xl font-bold">تم استلام طلبك!</h2>
              <p className="text-sm text-muted-foreground mt-1">
                سيتم التواصل معك قريباً لتأكيد التوصيل
              </p>
              {submittedInvoiceNumber && (
                <p className="text-sm font-medium mt-2">
                  رقم الطلب: <span className="font-bold text-primary">{submittedInvoiceNumber}</span>
                </p>
              )}
              {storeContactPhone && (
                <p className="text-xs text-muted-foreground mt-1">
                  للاستفسار: {storeContactPhone}
                </p>
              )}
            </div>
            <Button className="w-full" onClick={() => setSuccessOpen(false)}>
              العودة للتسوق
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Floating cart button on mobile when cart has items */}
      {cartCount > 0 && !cartOpen && (
        <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-30 md:hidden">
          <Button size="lg" className="shadow-lg gap-2 px-6" onClick={() => setCartOpen(true)}>
            <ShoppingCart className="h-5 w-5" />
            السلة ({cartCount}) — {formatPrice(cartTotal)}
          </Button>
        </div>
      )}
    </div>
  );
}
