"use client";

import {
  Banknote,
  CreditCard,
  Smartphone,
  Trash2,
  ShoppingCart,
  Loader2,
} from "lucide-react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import {
  TableBody,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { CartItemWithProduct, Customer, PaymentMethod } from "../types";
import CartItemRow from "./cart-item-row";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

interface PosSidebarProps {
  cartItems: CartItemWithProduct[];
  onUpdateQuantity: (productId: string, quantity: number) => void;
  onRemoveItem: (productId: string) => void;
  onClearCart: () => void;
  onCheckout: () => void;
  subtotal: number;
  discount: number;
  onDiscountChange: (discount: number) => void;
  grandTotal: number;
  paymentMethod: PaymentMethod;
  onPaymentMethodChange: (method: PaymentMethod) => void;
  amountReceived: string;
  onAmountReceivedChange: (amount: string) => void;
  change: number;
  customer: Customer;
  onCustomerChange: (customer: Customer) => void;
  canCheckout: boolean;
  isCheckingOut?: boolean;
}

const paymentMethods: {
  value: PaymentMethod;
  label: string;
  icon: React.ElementType;
}[] = [
  { value: "cash", label: "Cash", icon: Banknote },
  { value: "card", label: "Card", icon: CreditCard },
  { value: "mobile-banking", label: "Mobile Banking", icon: Smartphone },
];

export default function PosSidebar({
  cartItems,
  onUpdateQuantity,
  onRemoveItem,
  onClearCart,
  onCheckout,
  subtotal,
  discount,
  onDiscountChange,
  grandTotal,
  paymentMethod,
  onPaymentMethodChange,
  amountReceived,
  onAmountReceivedChange,
  change,
  customer,
  onCustomerChange,
  canCheckout,
  isCheckingOut,
}: PosSidebarProps) {
  const handleCustomerFieldChange = (field: keyof Customer, value: string) => {
    onCustomerChange({ ...customer, [field]: value });
  };

  return (
    <aside className="w-full lg:w-95 xl:w-100 flex flex-col">
      <ScrollArea className="flex-1 -mx-4 lg:mx-0">
        <div className="px-4 lg:px-0 space-y-4 pb-4">
          {/* ── Cart Items ── */}
          <Card>
            <CardHeader>
              <CardTitle>Cart ({cartItems.length})</CardTitle>
              <CardDescription>
                {cartItems.length === 0
                  ? "Add products to get started."
                  : "Review and adjust your items."}
              </CardDescription>
            </CardHeader>
            <CardContent>
              {cartItems.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-8 text-center">
                  <ShoppingCart className="h-10 w-10 text-muted-foreground/50 mb-3" />
                  <p className="text-sm text-muted-foreground">
                    Your cart is empty.
                  </p>
                </div>
              ) : (
                <div className="space-y-2 overflow-x-hidden">
                  <table className="w-full caption-bottom text-sm">
                    <TableHeader>
                      <TableRow>
                        <TableHead className="whitespace-normal">
                          Product
                        </TableHead>
                        <TableHead className="whitespace-normal">Qty</TableHead>
                        <TableHead className="whitespace-normal">
                          Price
                        </TableHead>
                        <TableHead className="whitespace-normal" />
                      </TableRow>
                    </TableHeader>
                    <TooltipProvider>
                      <TableBody>
                        {cartItems.map((item) => (
                          <Tooltip key={item.productId}>
                            <TooltipTrigger
                              render={
                                <CartItemRow
                                  item={item}
                                  onUpdateQuantity={onUpdateQuantity}
                                  onRemoveItem={onRemoveItem}
                                />
                              }
                            />
                            <TooltipContent className="px-2 py-1" side="left">
                              {item.product.name}
                            </TooltipContent>
                          </Tooltip>
                        ))}
                      </TableBody>
                    </TooltipProvider>
                  </table>
                </div>
              )}
            </CardContent>
          </Card>

          {/* ── Customer ── */}
          <Card>
            <CardHeader>
              <CardTitle>Customer</CardTitle>
              <CardDescription>
                Add customer details for the receipt.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="space-y-1.5">
                <Label htmlFor="customer-name">
                  Name <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="customer-name"
                  placeholder="Jane Doe"
                  value={customer.name}
                  onChange={(e) =>
                    handleCustomerFieldChange("name", e.target.value)
                  }
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="customer-phone">
                  Phone <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="customer-phone"
                  type="tel"
                  placeholder="+1 (555) 123-4567"
                  value={customer.phone}
                  onChange={(e) =>
                    handleCustomerFieldChange("phone", e.target.value)
                  }
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="customer-email">Email (optional)</Label>
                <Input
                  id="customer-email"
                  type="email"
                  placeholder="jane@example.com"
                  value={customer.email}
                  onChange={(e) =>
                    handleCustomerFieldChange("email", e.target.value)
                  }
                />
              </div>
            </CardContent>
          </Card>

          {/* ── Summary ── */}
          <Card>
            <CardHeader>
              <CardTitle>Order Summary</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">Subtotal</span>
                <span>${subtotal.toFixed(2)}</span>
              </div>

              <div className="flex justify-between text-sm items-center">
                <Label htmlFor="discount" className="text-muted-foreground">
                  Discount
                </Label>
                <Input
                  id="discount"
                  type="number"
                  min={0}
                  max={subtotal}
                  placeholder="$0.00"
                  value={discount === 0 ? "" : discount}
                  onChange={(e) =>
                    onDiscountChange(parseFloat(e.target.value) || 0)
                  }
                  className="w-24 text-right"
                />
              </div>

              <Separator />

              <div className="flex justify-between text-lg font-semibold">
                <span>Total</span>
                <span>${grandTotal.toFixed(2)}</span>
              </div>
            </CardContent>
          </Card>

          {/* ── Payment ── */}
          <Card>
            <CardHeader>
              <CardTitle>Payment</CardTitle>
              <CardDescription>
                Select a payment method to complete the order.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <Select
                items={paymentMethods.map((method) => ({
                  value: method.value,
                  label: method.label,
                }))}
                value={paymentMethod}
                onValueChange={(val) =>
                  onPaymentMethodChange(val as PaymentMethod)
                }
              >
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="Select payment method" />
                </SelectTrigger>
                <SelectContent>
                  {paymentMethods.map((method) => {
                    const Icon = method.icon;
                    return (
                      <SelectItem key={method.value} value={method.value}>
                        <div className="flex items-center gap-2">
                          <Icon className="h-4 w-4" />
                          {method.label}
                        </div>
                      </SelectItem>
                    );
                  })}
                </SelectContent>
              </Select>

              {paymentMethod === "cash" && (
                <div className="space-y-3">
                  <div className="space-y-1.5">
                    <Label htmlFor="amount-received">Amount Received</Label>
                    <Input
                      id="amount-received"
                      type="number"
                      min={grandTotal}
                      step={0.01}
                      placeholder={grandTotal.toFixed(2)}
                      value={amountReceived}
                      onChange={(e) => onAmountReceivedChange(e.target.value)}
                    />
                  </div>

                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Change</span>
                    <span
                      className={`font-semibold ${
                        Number(amountReceived) < grandTotal &&
                        amountReceived !== ""
                          ? "text-destructive"
                          : "text-green-500"
                      }`}
                    >
                      {amountReceived === "" ||
                      Number(amountReceived) < grandTotal
                        ? "-$" + grandTotal.toFixed(2)
                        : `$${change.toFixed(2)}`}
                    </span>
                  </div>
                </div>
              )}

              {paymentMethod === "card" && (
                <div className="text-center py-4 text-sm text-muted-foreground">
                  <CreditCard className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p>Card payment ready.</p>
                  <p className="text-xs mt-1">
                    Present the card to the customer to complete.
                  </p>
                </div>
              )}

              {paymentMethod === "mobile-banking" && (
                <div className="text-center py-4 text-sm text-muted-foreground">
                  <Smartphone className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p>Mobile banking payment ready.</p>
                  <p className="text-xs mt-1">
                    Scan the QR code or enter the transaction ID.
                  </p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </ScrollArea>

      {/* ── Actions (sticky footer) ── */}
      <div className="pt-4 border-t space-y-2">
        <Button
          variant="outline"
          className="w-full justify-start"
          onClick={onClearCart}
          disabled={cartItems.length === 0}
        >
          <Trash2 className="h-4 w-4 mr-2" />
          Clear Cart
        </Button>

        <Button
          className="w-full"
          size="lg"
          disabled={!canCheckout || isCheckingOut}
          onClick={onCheckout}
        >
          {isCheckingOut ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Processing…
            </>
          ) : (
            "Complete Checkout"
          )}
        </Button>
      </div>
    </aside>
  );
}
