"use client";
import React, { useState, useEffect, useRef, useCallback } from "react";
import { PageHeader } from "@/components/page-header";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { toast } from "sonner";
import { Search, Plus, Minus, Trash2, ShoppingCart, Barcode, User, Printer, CheckCircle, Package } from "lucide-react";
import { createPosOrder } from "@/app/actions/order";

interface CartItem {
  productId: string;
  title: string;
  price: number;
  qty: number;
  sku?: string;
  image?: string;
  variantId?: string;
  variantName?: string;
}

export default function PosClient({ products, customers, settings }: { products: any[]; customers: any[]; settings?: any }) {
  const [cart, setCart] = useState<CartItem[]>([]);
  const [search, setSearch] = useState("");
  const [barcodeInput, setBarcodeInput] = useState("");
  const [selectedCustomer, setSelectedCustomer] = useState<string>("");
  const [discount, setDiscount] = useState(0);
  const [shippingCost, setShippingCost] = useState(0);
  const [taxRate, setTaxRate] = useState(settings?.taxEnabled ? (settings?.taxRate || 10) : 0);
  const [note, setNote] = useState("");
  const [isCheckoutOpen, setIsCheckoutOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [lastOrder, setLastOrder] = useState<any>(null);
  
  // Variant Selection State
  const [productToSelectVariant, setProductToSelectVariant] = useState<any>(null);

  const barcodeRef = useRef<HTMLInputElement>(null);

  // Auto focus barcode field
  useEffect(() => {
    barcodeRef.current?.focus();
  }, []);

  const filteredProducts = products.filter(p =>
    !search || p.title.includes(search) || (p.sku && p.sku.includes(search)) || (p.barcode && p.barcode.includes(search))
  ).slice(0, 30);

  const addToCart = useCallback((product: any, variant?: any) => {
    // If product has variants and none selected, open modal
    if (!variant && product.variants && product.variants.length > 0) {
      setProductToSelectVariant(product);
      return;
    }

    const price = variant ? (variant.salePrice || variant.price) : (product.salePrice || product.price);
    const sku = variant ? variant.sku : product.sku;
    const variantName = variant ? variant.options.map((o:any) => o.value).join(' / ') : undefined;
    const variantId = variant ? variant.id : undefined;

    // We need to differentiate items by variantId as well
    const itemId = variantId ? `${product.id}-${variantId}` : product.id;

    setCart(prev => {
      const existing = prev.find(i => (i.variantId ? i.variantId === variantId : i.productId === product.id));
      if (existing) {
        return prev.map(i => (i.variantId ? i.variantId === variantId : i.productId === product.id) ? { ...i, qty: i.qty + 1 } : i);
      }
      return [...prev, {
        productId: product.id,
        variantId,
        variantName,
        title: product.title,
        price,
        qty: 1,
        sku,
        image: product.images?.[0]?.imageUrl,
      }];
    });
    
    toast.success(`${product.title} ${variantName ? `(${variantName})` : ''} به سبد اضافه شد`, { duration: 1000 });
    setProductToSelectVariant(null);
  }, []);

  // Barcode scanner handler
  const handleBarcodeSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const code = barcodeInput.trim();
    if (!code) return;
    
    // First try to find exact variant
    for (const p of products) {
      if (p.variants) {
        const foundVariant = p.variants.find((v: any) => v.sku === code || v.barcode === code);
        if (foundVariant) {
          addToCart(p, foundVariant);
          setBarcodeInput("");
          return;
        }
      }
    }

    // Then try to find product
    const found = products.find(p => p.barcode === code || p.sku === code);
    if (found) {
      addToCart(found);
    } else {
      toast.error(`محصول یا تنوعی با کد "${code}" یافت نشد.`);
    }
    setBarcodeInput("");
  };

  const updateQty = (productId: string, variantId: string | undefined, delta: number) => {
    setCart(prev => prev
      .map(i => (i.productId === productId && i.variantId === variantId) ? { ...i, qty: i.qty + delta } : i)
      .filter(i => i.qty > 0)
    );
  };

  const removeFromCart = (productId: string, variantId: string | undefined) => {
    setCart(prev => prev.filter(i => !(i.productId === productId && i.variantId === variantId)));
  };

  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const taxAmount = Math.round((subtotal - discount) * (taxRate / 100));
  const total = subtotal - discount + taxAmount + shippingCost;

  const handleCheckout = async () => {
    if (cart.length === 0) return toast.error("سبد خرید خالی است.");
    setIsLoading(true);
    try {
      const res = await createPosOrder({
        items: cart.map(i => ({ productId: i.productId, variantId: i.variantId, qty: i.qty, price: i.price, title: i.title + (i.variantName ? ` (${i.variantName})` : '') })),
        customerId: selectedCustomer || undefined,
        discount,
        shippingCost,
        taxAmount,
        note,
      });
      if (res.success) {
        setLastOrder(res.order);
        setCart([]);
        setDiscount(0);
        setShippingCost(0);
        setNote("");
        setSelectedCustomer("");
        setIsCheckoutOpen(false);
        toast.success(`سفارش #${res.order.orderCode} با موفقیت ثبت شد!`);
      } else {
        toast.error(res.error || "خطا در ثبت سفارش");
      }
    } catch (e) {
      toast.error("خطای شبکه");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex flex-col h-screen overflow-hidden" dir="rtl">
      <PageHeader
        title="صندوق فروش حضوری (POS)"
        subtitle="فروش حضوری با بارکدخوان"
        icon={<ShoppingCart className="w-5 h-5" />}
      >
        {lastOrder && (
          <div className="flex items-center gap-2 text-xs text-emerald-600 bg-emerald-50 dark:bg-emerald-900/20 px-3 py-1.5 rounded-full">
            <CheckCircle className="w-3.5 h-3.5" /> #{lastOrder.orderCode}
          </div>
        )}
      </PageHeader>

      <div className="flex flex-1 overflow-hidden">
        {/* LEFT: Product Browser */}
        <div className="flex-1 flex flex-col overflow-hidden border-l">
          {/* Barcode Scanner */}
          <div className="p-3 border-b bg-muted/30">
            <form onSubmit={handleBarcodeSubmit} className="flex gap-2">
              <div className="relative flex-1">
                <Barcode className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-indigo-500" />
                <Input
                  ref={barcodeRef}
                  value={barcodeInput}
                  onChange={e => setBarcodeInput(e.target.value)}
                  placeholder="اسکن بارکد یا وارد کردن دستی کد محصول..."
                  className="pr-9 font-sans text-left bg-white dark:bg-zinc-900 border-indigo-200 focus-visible:ring-indigo-500"
                  dir="ltr"
                />
              </div>
              <Button type="submit" variant="outline" className="shrink-0 border-indigo-200 text-indigo-600">اضافه کن</Button>
            </form>
          </div>

          {/* Product Search */}
          <div className="px-3 pt-3 pb-2">
            <div className="relative">
              <Search className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input placeholder="جستجوی محصول..." className="pr-9" value={search} onChange={e => setSearch(e.target.value)} />
            </div>
          </div>

          {/* Products Grid */}
          <div className="flex-1 overflow-y-auto p-3 grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-3 content-start">
            {filteredProducts.map(product => (
              <button
                key={product.id}
                onClick={() => addToCart(product)}
                className="bg-card border rounded-xl overflow-hidden shadow-sm hover:shadow-md hover:border-indigo-300 hover:bg-indigo-50/30 dark:hover:bg-indigo-900/10 transition-all text-right group active:scale-95"
              >
                <div className="aspect-square bg-muted/30 relative overflow-hidden">
                  {product.images?.[0] ? (
                    <img src={product.images[0].imageUrl} alt={product.title} className="w-full h-full object-cover group-hover:scale-105 transition-transform" />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center"><Package className="w-10 h-10 text-muted-foreground/20" /></div>
                  )}
                  {product.manageStock && product.stockQuantity !== null && product.stockQuantity <= 0 && (
                    <div className="absolute inset-0 bg-black/60 flex items-center justify-center">
                      <span className="text-white text-xs font-bold">ناموجود</span>
                    </div>
                  )}
                </div>
                <div className="p-2">
                  <div className="text-xs font-semibold line-clamp-2 leading-tight">{product.title}</div>
                  <div className="text-xs font-black font-sans text-indigo-700 dark:text-indigo-400 mt-1">
                    {(product.salePrice || product.price).toLocaleString("fa-IR")}
                  </div>
                  {product.sku && <div className="text-[10px] text-muted-foreground font-sans mt-0.5">{product.sku}</div>}
                </div>
              </button>
            ))}
            {filteredProducts.length === 0 && (
              <div className="col-span-full text-center py-16 text-muted-foreground text-sm">
                <Package className="w-10 h-10 mx-auto mb-3 opacity-20" />
                محصولی یافت نشد.
              </div>
            )}
          </div>
        </div>

        {/* RIGHT: Cart */}
        <div className="w-80 xl:w-96 flex flex-col bg-card border-r">
          <div className="p-4 border-b">
            <h2 className="font-bold flex items-center gap-2 text-sm">
              <ShoppingCart className="w-4 h-4 text-indigo-500" /> سبد خرید
              {cart.length > 0 && <span className="bg-indigo-600 text-white text-xs px-1.5 py-0.5 rounded-full font-sans">{cart.length}</span>}
            </h2>
          </div>

          {/* Cart Items */}
          <div className="flex-1 overflow-y-auto divide-y">
            {cart.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full text-muted-foreground gap-3">
                <ShoppingCart className="w-12 h-12 opacity-10" />
                <p className="text-sm">سبد خالی است</p>
              </div>
            ) : cart.map(item => (
              <div key={item.productId} className="flex gap-3 p-3 items-center">
                {item.image ? (
                  <img src={item.image} alt={item.title} className="w-10 h-10 rounded-lg object-cover shrink-0" />
                ) : (
                  <div className="w-10 h-10 rounded-lg bg-muted flex items-center justify-center shrink-0">
                    <Package className="w-5 h-5 text-muted-foreground/30" />
                  </div>
                )}
                <div className="flex-1 min-w-0">
                  <div className="text-xs font-semibold line-clamp-1">{item.title}</div>
                  {item.variantName && <div className="text-[10px] text-muted-foreground mt-0.5">{item.variantName}</div>}
                  <div className="text-xs font-sans text-indigo-600 font-bold mt-0.5">{item.price.toLocaleString("fa-IR")}</div>
                </div>
                <div className="flex items-center gap-1 shrink-0">
                  <Button variant="outline" size="icon" className="h-6 w-6 rounded-full" onClick={() => updateQty(item.productId, item.variantId, -1)}>
                    <Minus className="w-3 h-3" />
                  </Button>
                  <span className="w-6 text-center font-sans font-bold text-sm">{item.qty}</span>
                  <Button variant="outline" size="icon" className="h-6 w-6 rounded-full" onClick={() => updateQty(item.productId, item.variantId, 1)}>
                    <Plus className="w-3 h-3" />
                  </Button>
                  <Button variant="ghost" size="icon" className="h-6 w-6 text-rose-500" onClick={() => removeFromCart(item.productId, item.variantId)}>
                    <Trash2 className="w-3 h-3" />
                  </Button>
                </div>
              </div>
            ))}
          </div>

          {/* Cart Footer */}
          <div className="border-t p-4 space-y-3">
            {/* Customer Selector */}
            <Select value={selectedCustomer} onValueChange={setSelectedCustomer}>
              <SelectTrigger className="w-full h-9 text-xs">
                <User className="w-3.5 h-3.5 ml-2 text-muted-foreground" />
                <SelectValue placeholder="انتخاب مشتری (اختیاری)" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="guest">مهمان</SelectItem>
                {customers.map((c: any) => (
                  <SelectItem key={c.id} value={c.id}>{c.firstName} {c.lastName} - {c.mobile || c.phone}</SelectItem>
                ))}
              </SelectContent>
            </Select>

            {/* Discount, Shipping, Tax */}
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <span className="text-xs font-bold text-muted-foreground shrink-0 w-16">تخفیف:</span>
                <Input
                  type="number"
                  className="h-8 text-xs font-sans text-left"
                  dir="ltr"
                  placeholder="0"
                  value={discount || ""}
                  onChange={e => setDiscount(parseInt(e.target.value) || 0)}
                />
                <span className="text-xs text-muted-foreground shrink-0 w-8">تومان</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs font-bold text-muted-foreground shrink-0 w-16">هزینه ارسال:</span>
                <Input
                  type="number"
                  className="h-8 text-xs font-sans text-left"
                  dir="ltr"
                  placeholder="0"
                  value={shippingCost || ""}
                  onChange={e => setShippingCost(parseInt(e.target.value) || 0)}
                />
                <span className="text-xs text-muted-foreground shrink-0 w-8">تومان</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs font-bold text-muted-foreground shrink-0 w-16">مالیات:</span>
                <Input
                  type="number"
                  className="h-8 text-xs font-sans text-left"
                  dir="ltr"
                  placeholder="10"
                  value={taxRate || ""}
                  onChange={e => setTaxRate(parseFloat(e.target.value) || 0)}
                />
                <span className="text-xs text-muted-foreground shrink-0 w-8">%</span>
              </div>
            </div>

            {/* Totals */}
            <div className="bg-muted/30 rounded-xl p-3 space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">جمع کالاها:</span>
                <span className="font-sans font-medium">{subtotal.toLocaleString("fa-IR")}</span>
              </div>
              {discount > 0 && (
                <div className="flex justify-between text-sm text-rose-600">
                  <span>تخفیف:</span>
                  <span className="font-sans font-medium">- {discount.toLocaleString("fa-IR")}</span>
                </div>
              )}
              {shippingCost > 0 && (
                <div className="flex justify-between text-sm text-blue-600">
                  <span>هزینه ارسال:</span>
                  <span className="font-sans font-medium">+ {shippingCost.toLocaleString("fa-IR")}</span>
                </div>
              )}
              {taxAmount > 0 && (
                <div className="flex justify-between text-sm text-purple-600">
                  <span>مالیات ({taxRate}%):</span>
                  <span className="font-sans font-medium">+ {taxAmount.toLocaleString("fa-IR")}</span>
                </div>
              )}
              <div className="flex justify-between font-black text-lg text-indigo-700 dark:text-indigo-400 border-t pt-2 mt-2">
                <span>قابل پرداخت:</span>
                <span className="font-sans">{total.toLocaleString("fa-IR")}</span>
              </div>
            </div>

            <Button
              className="w-full h-12 bg-emerald-600 hover:bg-emerald-700 text-base font-bold shadow-md gap-2"
              onClick={() => setIsCheckoutOpen(true)}
              disabled={cart.length === 0}
            >
              <CheckCircle className="w-5 h-5" /> ثبت و تسویه
            </Button>
          </div>
        </div>
      </div>

      {/* Checkout Confirm Dialog */}
      <Dialog open={isCheckoutOpen} onOpenChange={setIsCheckoutOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckCircle className="w-5 h-5 text-emerald-500" /> تأیید و ثبت فروش
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="bg-muted/30 rounded-xl p-4 max-h-48 overflow-y-auto space-y-2">
              {cart.map(item => (
                <div key={item.productId} className="flex justify-between text-sm">
                  <span>{item.title} × {item.qty}</span>
                  <span className="font-sans font-bold">{(item.price * item.qty).toLocaleString("fa-IR")}</span>
                </div>
              ))}
            </div>
            <div className="bg-indigo-50 dark:bg-indigo-900/20 rounded-xl p-4 flex justify-between items-center">
              <span className="font-bold text-indigo-700 dark:text-indigo-400">مبلغ نهایی قابل پرداخت:</span>
              <span className="font-black text-2xl font-sans text-indigo-700 dark:text-indigo-400">{total.toLocaleString("fa-IR")}</span>
            </div>
            <Input placeholder="یادداشت سفارش (اختیاری)..." value={note} onChange={e => setNote(e.target.value)} />
            <div className="flex gap-3">
              <Button variant="outline" className="flex-1" onClick={() => setIsCheckoutOpen(false)}>انصراف</Button>
              <Button
                className="flex-1 bg-emerald-600 hover:bg-emerald-700 gap-2"
                onClick={handleCheckout}
                disabled={isLoading}
              >
                <CheckCircle className="w-4 h-4" />
                {isLoading ? "در حال ثبت..." : "تأیید و ثبت فروش"}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
      {/* Variant Selection Dialog */}
      <Dialog open={!!productToSelectVariant} onOpenChange={(open) => !open && setProductToSelectVariant(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>انتخاب تنوع: {productToSelectVariant?.title}</DialogTitle>
          </DialogHeader>
          <div className="grid grid-cols-1 gap-2 max-h-60 overflow-y-auto mt-2 p-1">
            {productToSelectVariant?.variants?.map((v: any) => (
              <button
                key={v.id}
                onClick={() => addToCart(productToSelectVariant, v)}
                className="flex items-center justify-between p-3 border rounded-xl hover:border-indigo-500 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors text-right"
              >
                <div className="flex flex-col">
                  <span className="font-bold text-sm">
                    {v.options?.map((o: any) => o.value).join(' / ') || 'تنوع'}
                  </span>
                  {v.sku && <span className="text-[10px] text-muted-foreground font-sans mt-1">کد: {v.sku}</span>}
                </div>
                <div className="flex flex-col items-end">
                  <span className="font-sans font-black text-indigo-600">
                    {(v.salePrice || v.price).toLocaleString("fa-IR")}
                  </span>
                  <span className="text-[10px] text-muted-foreground">تومان</span>
                </div>
              </button>
            ))}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
