"use client";

import { useMemo, useCallback, useState } from "react";
import {
  Product,
  CartItem,
  Customer,
  PaymentMethod,
  CartItemWithProduct,
  Category,
} from "../types";
import ProductToolbar from "./product-toolbar";
import ProductGrid from "./product-grid";
import PosSidebar from "./pos-sidebar";
import { posCheckout } from "@/lib/actions/pos";

interface PosTerminalProps {
  products: Product[];
  categories: Category[];
}

export default function PosTerminal({ products, categories }: PosTerminalProps) {
  // ── State ──
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<string>("all");
  const [cart, setCart] = useState<CartItem[]>([]);
  const [customer, setCustomer] = useState<Customer>({
    name: "",
    phone: "",
    email: "",
  });
  const [discount, setDiscount] = useState<number>(0);
  const [paymentMethod, setPaymentMethod] = useState<PaymentMethod>("cash");
  const [amountReceived, setAmountReceived] = useState<string>("");
  const [isCheckingOut, setIsCheckingOut] = useState(false);

  // ── Derived: filtered products ──
  const filteredProducts = useMemo(() => {
    const q = searchQuery.toLowerCase().trim();
    return products.filter((product) => {
      const matchesSearch =
        q === "" ||
        product.name.toLowerCase().includes(q) ||
        product.sku.toLowerCase().includes(q) ||
        product.barcode.toLowerCase().includes(q);
      const matchesCategory =
        selectedCategory === "all" || product.categoryId === selectedCategory;
      return matchesSearch && matchesCategory;
    });
  }, [products, searchQuery, selectedCategory]);

  // ── Derived: cart items joined with product data ──
  const cartItems = useMemo((): CartItemWithProduct[] => {
    return cart
      .map((item) => {
        const product = products.find((p) => p.id === item.productId);
        if (!product) return null;
        return { ...item, product };
      })
      .filter((item): item is CartItemWithProduct => item !== null);
  }, [cart, products]);

  // ── Derived: totals ──
  const subtotal = cartItems.reduce(
    (sum, item) => sum + item.product.price * item.quantity,
    0,
  );
  const discountAmount = Math.min(discount, subtotal);
  const grandTotal = Math.max(0, subtotal - discountAmount);

  const numericAmountReceived =
    amountReceived === "" ? 0 : Number.parseFloat(amountReceived);

  const change =
    paymentMethod === "cash"
      ? Math.max(0, numericAmountReceived - grandTotal)
      : 0;

  // ── Derived: checkout eligibility ──
  const canCheckout = useMemo(() => {
    if (cartItems.length === 0) return false;
    if (!customer.name.trim()) return false;
    if (!customer.phone.trim()) return false;
    if (grandTotal <= 0) return false;
    if (
      paymentMethod === "cash" &&
      (amountReceived === "" || numericAmountReceived < grandTotal)
    ) {
      return false;
    }
    return true;
  }, [
    cartItems,
    customer,
    grandTotal,
    paymentMethod,
    amountReceived,
    numericAmountReceived,
  ]);

  // ── Handlers ──
  const handleAddToCart = useCallback(
    (product: Product) => {
      if (product.stock === 0) return;
      setCart((prev) => {
        const existing = prev.find((item) => item.productId === product.id);
        if (existing) {
          return prev.map((item) =>
            item.productId === product.id
              ? {
                  ...item,
                  quantity: Math.min(item.quantity + 1, product.stock),
                }
              : item,
          );
        }
        return [...prev, { productId: product.id, quantity: 1 }];
      });
    },
    [],
  );

  const handleUpdateQuantity = useCallback(
    (productId: string, quantity: number) => {
      const product = products.find((p) => p.id === productId);
      const maxQty = product ? product.stock : Infinity;
      const qty = Math.max(1, Math.min(quantity, maxQty));
      setCart((prev) =>
        prev.map((item) =>
          item.productId === productId ? { ...item, quantity: qty } : item,
        ),
      );
    },
    [products],
  );

  const handleRemoveItem = useCallback((productId: string) => {
    setCart((prev) => prev.filter((item) => item.productId !== productId));
  }, []);

  const handleClearCart = useCallback(() => {
    setCart([]);
    setCustomer({ name: "", phone: "", email: "" });
    setDiscount(0);
    setPaymentMethod("cash");
    setAmountReceived("");
  }, []);

  const handleCheckout = useCallback(async () => {
    if (!canCheckout) return;
    setIsCheckingOut(true);
    try {
      const result = await posCheckout({
        items: cartItems.map((item) => ({
          productId: item.productId,
          quantity: item.quantity,
        })),
        customer: {
          name: customer.name.trim(),
          phone: customer.phone.trim(),
          email: customer.email.trim(),
        },
        discount: discountAmount,
        paymentMethod,
        amountReceived: numericAmountReceived,
        change,
      });

      if (result.ok && result.data) {
        alert(
          `Order ${result.data.orderNumber} completed!\nTotal: ৳${result.data.grandTotal.toFixed(2)}`,
        );
        handleClearCart();
      } else if (!result.ok) {
        alert(`Checkout failed: ${result.error}`);
      }
    } catch (error) {
      alert(
        `Checkout failed: ${error instanceof Error ? error.message : "Unexpected error"}`,
      );
    } finally {
      setIsCheckingOut(false);
    }
  }, [
    canCheckout,
    cartItems,
    customer,
    discountAmount,
    paymentMethod,
    numericAmountReceived,
    change,
    handleClearCart,
  ]);

  return (
    <div className="flex flex-col lg:flex-row gap-4 h-[calc(100vh-12rem)]">
      {/* ── Product Section ── */}
      <div className="flex-1 flex flex-col gap-4">
        <ProductToolbar
          searchQuery={searchQuery}
          onSearchChange={setSearchQuery}
          selectedCategory={selectedCategory}
          categories={categories}
          onCategoryChange={setSelectedCategory}
        />

        <ProductGrid
          products={filteredProducts}
          onAddToCart={handleAddToCart}
        />
      </div>

      {/* ── Cart Section ── */}
      <PosSidebar
        cartItems={cartItems}
        onUpdateQuantity={handleUpdateQuantity}
        onRemoveItem={handleRemoveItem}
        onClearCart={handleClearCart}
        onCheckout={handleCheckout}
        isCheckingOut={isCheckingOut}
        subtotal={subtotal}
        discount={discountAmount}
        onDiscountChange={setDiscount}
        grandTotal={grandTotal}
        paymentMethod={paymentMethod}
        onPaymentMethodChange={setPaymentMethod}
        amountReceived={amountReceived}
        onAmountReceivedChange={setAmountReceived}
        change={change}
        customer={customer}
        onCustomerChange={setCustomer}
        canCheckout={canCheckout}
      />
    </div>
  );
}