/**
 * Cart Rules Tab for Quantity Limits
 * 
 * This is a Pro feature that allows setting cart-level quantity and spend restrictions.
 */

import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import { Checkbox } from "@/components/ui/checkbox"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { ShoppingCart, X, Search, Loader2, Package } from "lucide-react"
import { useProductSearch } from "../../hooks"
import type { CartRules, ProductSearchResult } from "../../types"

interface CartRulesTabProps {
  rules: CartRules
  onChange: (rules: CartRules) => void
}

export function CartRulesTab({ rules, onChange }: CartRulesTabProps) {
  const [searchQuery, setSearchQuery] = useState('')
  const [excludedProductNames, setExcludedProductNames] = useState<Map<number, string>>(new Map())
  const { products: searchResults, isSearching, searchProducts, clearResults } = useProductSearch()

  // Get currency info from Pro plugin (if available)
  const currency = window.swiftCommerceData?.currency
  const currencySymbol = currency?.symbol || '$'
  const currencyCode = currency?.code || 'USD'

  // Debounced search
  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchQuery.length >= 2) {
        searchProducts(searchQuery)
      } else {
        clearResults()
      }
    }, 300)

    return () => clearTimeout(timer)
  }, [searchQuery])

  const handleChange = <K extends keyof CartRules>(field: K, value: CartRules[K]) => {
    onChange({
      ...rules,
      [field]: value
    })
  }

  const addExcludedProduct = (product: ProductSearchResult) => {
    const currentExcluded = rules.excluded_products || []
    if (!currentExcluded.includes(product.id)) {
      handleChange('excluded_products', [...currentExcluded, product.id])
      setExcludedProductNames(new Map(excludedProductNames.set(product.id, product.name)))
    }
    setSearchQuery('')
    clearResults()
  }

  const removeExcludedProduct = (productId: number) => {
    const currentExcluded = rules.excluded_products || []
    handleChange('excluded_products', currentExcluded.filter(id => id !== productId))
    const newNames = new Map(excludedProductNames)
    newNames.delete(productId)
    setExcludedProductNames(newNames)
  }

  return (
    <div className="space-y-6">
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Cart Quantity Restrictions */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <ShoppingCart className="h-5 w-5" />
              Cart Quantity Restrictions
            </CardTitle>
            <CardDescription>
              Set minimum and maximum number of items allowed in the cart.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid gap-4">
              <div className="space-y-2">
                <Label htmlFor="min_qty_restriction">
                  Minimum quantity restriction
                </Label>
                <Input
                  id="min_qty_restriction"
                  type="number"
                  min="0"
                  value={rules.min_qty_restriction || ''}
                  onChange={(e) => handleChange('min_qty_restriction', parseInt(e.target.value) || 0)}
                  placeholder="0"
                />
                <p className="text-sm text-muted-foreground">
                  Minimum number of items in cart. Set zero for no restrictions.
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="max_qty_restriction">
                  Maximum quantity restriction
                </Label>
                <Input
                  id="max_qty_restriction"
                  type="number"
                  min="0"
                  value={rules.max_qty_restriction || ''}
                  onChange={(e) => handleChange('max_qty_restriction', parseInt(e.target.value) || 0)}
                  placeholder="0"
                />
                <p className="text-sm text-muted-foreground">
                  Maximum number of items in cart. Set zero for no restrictions.
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Cart Spend Restrictions */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              Cart Spend Restrictions
            </CardTitle>
            <CardDescription>
              Set minimum and maximum spend amounts for the cart in {currencyCode} ({currencySymbol}).
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-6">
              {/* Enable spend restrictions toggle */}
              <div className="flex items-center space-x-3">
                <Switch
                  id="enable_spend"
                  checked={rules.enable_spend}
                  onCheckedChange={(checked) => handleChange('enable_spend', checked)}
                />
                <Label htmlFor="enable_spend" className="cursor-pointer">
                  Enable cart spend restrictions
                </Label>
              </div>

              {rules.enable_spend && (
                <div className="space-y-6 pl-6 border-l-2 border-muted">
                  <div className="grid gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="min_spend">
                        Minimum spend restriction ({currencySymbol})
                      </Label>
                      <div className="relative">
                        <span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm pointer-events-none">
                          {currencySymbol}
                        </span>
                        <Input
                          id="min_spend"
                          type="number"
                          min="0"
                          step="0.01"
                          value={rules.min_spend || ''}
                          onChange={(e) => handleChange('min_spend', parseFloat(e.target.value) || 0)}
                          placeholder="0"
                          style={{ paddingLeft: `${Math.max(2.5, currencySymbol.length * 0.6 + 1)}rem` }}
                        />
                      </div>
                      <p className="text-sm text-muted-foreground">
                        Minimum spend for items in cart. Set zero for no restrictions.
                      </p>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="max_spend">
                        Maximum spend restriction ({currencySymbol})
                      </Label>
                      <div className="relative">
                        <span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm pointer-events-none">
                          {currencySymbol}
                        </span>
                        <Input
                          id="max_spend"
                          type="number"
                          min="0"
                          step="0.01"
                          value={rules.max_spend || ''}
                          onChange={(e) => handleChange('max_spend', parseFloat(e.target.value) || 0)}
                          placeholder="0"
                          style={{ paddingLeft: `${Math.max(2.5, currencySymbol.length * 0.6 + 1)}rem` }}
                        />
                      </div>
                      <p className="text-sm text-muted-foreground">
                        Maximum spend for items in cart. Set zero for no restrictions.
                      </p>
                    </div>
                  </div>

                  <div className="flex items-center space-x-3">
                    <Checkbox
                      id="include_shipping"
                      checked={rules.include_shipping}
                      onCheckedChange={(checked) => handleChange('include_shipping', checked as boolean)}
                    />
                    <Label htmlFor="include_shipping" className="cursor-pointer">
                      Include shipping rates and relative fees
                    </Label>
                  </div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Excluded Products - Full Width */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Package className="h-5 w-5" />
            Excluded Products
          </CardTitle>
          <CardDescription>
            These products will be excluded from cart quantity and spend calculations.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {/* Search */}
            <div className="relative max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                type="text"
                placeholder="Search for products to exclude..."
                className="pl-9"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
              {isSearching && (
                <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground" />
              )}

              {/* Search Results Dropdown */}
              {searchResults.length > 0 && (
                <div className="absolute z-10 w-full mt-1 bg-background border rounded-md shadow-lg max-h-60 overflow-auto">
                  {searchResults.map((product) => (
                    <button
                      key={product.id}
                      type="button"
                      className="w-full px-4 py-2 text-left hover:bg-muted flex items-center justify-between"
                      onClick={() => addExcludedProduct(product)}
                    >
                      <span className="font-medium">{product.name}</span>
                      {product.sku && (
                        <span className="text-sm text-muted-foreground">SKU: {product.sku}</span>
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Excluded Products List */}
            {(rules.excluded_products?.length || 0) > 0 ? (
              <div className="flex flex-wrap gap-2">
                {rules.excluded_products.map((productId) => (
                  <Badge key={productId} variant="secondary" className="gap-1 pr-1">
                    {excludedProductNames.get(productId) || `Product #${productId}`}
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="h-4 w-4 p-0 hover:bg-transparent"
                      onClick={() => removeExcludedProduct(productId)}
                    >
                      <X className="h-3 w-3" />
                    </Button>
                  </Badge>
                ))}
              </div>
            ) : (
              <p className="text-sm text-muted-foreground py-4 text-center border-2 border-dashed rounded-md">
                No products excluded. Search and select products above.
              </p>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
