import { useCallback, useEffect, useMemo } from "react";
import { endOfDay, startOfDay } from "date-fns";
import { DateRange } from "react-day-picker";
import { DateRangePicker } from "@/components/ui/date-range-picker";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Switch } from "@/components/ui/switch";
import { DiscountPromoOption, DiscountPromoType, ShippingPromoType, ShippingTierConfig, SurchargeConfig, DiscountSimulationResponse, CogsCalculationMode } from "@/types/discount-simulator";
import { formatNumber } from "@/utils/productUtils";
import { PlusIcon, X } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";

interface ConfigPanelProps {
  dateRange: DateRange;
  onDateRangeChange: (range: DateRange | undefined) => void;
  promos: DiscountPromoOption[];
  promoLoading?: boolean;
  selectedPromoId?: number;
  onPromoChange: (promoId: number | undefined) => void;
  productPromo: {
    type: DiscountPromoType;
    value: number;
    minSubtotal: number;
  };
  onProductPromoChange: (update: Partial<ConfigPanelProps["productPromo"]>) => void;
  shippingPromo: {
    type: ShippingPromoType;
    value: number;
    minSubtotal: number;
    maxDiscount: number;
  };
  onShippingPromoChange: (update: Partial<ConfigPanelProps["shippingPromo"]>) => void;
  shippingTiers: ShippingTierConfig[];
  onShippingTiersChange: (tiers: ShippingTierConfig[]) => void;
  surcharges: SurchargeConfig[];
  onSurchargesChange: (surcharges: SurchargeConfig[]) => void;
  merchantFeePercent: number;
  onMerchantFeeChange: (value: number) => void;
  fixedCostPerOrder: number;
  onFixedCostChange: (value: number) => void;
  cogsCalculationMode: CogsCalculationMode;
  onCogsCalculationModeChange: (mode: CogsCalculationMode) => void;
  applyHistoricalProductPromo: boolean;
  onApplyHistoricalProductPromoChange: (value: boolean) => void;
  pointsPerDollar: number;
  redemptionRate: number;
  onRedemptionRateChange: (value: number) => void;
  pointDollarValue: number;
  onPointDollarValueChange: (value: number) => void;
  onConfigInputChange: () => void;
  onResetConfig: () => void;
  onRunSimulation: () => void;
  isRunning: boolean;
  recommendedPointDollarValue?: number;
  onApplyRecommendedPointDollarValue?: () => void;
  result?: DiscountSimulationResponse;
}

function parseNumber(value: string, fallback = 0) {
  if (value.trim() === '') {
    return fallback;
  }
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
}

const formatPercent = (value: number) => {
  if (!Number.isFinite(value)) return 'N/A';
  return `${(value * 100).toFixed(2)}%`;
};

const generateTierId = () => `tier-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const generateSurchargeId = () => `surcharge-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;

const parseDateToTimestamp = (value?: string | null): number | undefined => {
  if (!value) {
    return undefined;
  }
  const timestamp = new Date(value).getTime();
  return Number.isFinite(timestamp) ? timestamp : undefined;
};

const promoOverlapsRange = (
  promo: DiscountPromoOption,
  rangeStart?: number,
  rangeEnd?: number
): boolean => {
  if (rangeStart == null || rangeEnd == null) {
    return true;
  }

  const promoStart = parseDateToTimestamp(promo.dateStart) ?? Number.NEGATIVE_INFINITY;
  const promoEnd = parseDateToTimestamp(promo.dateEnd) ?? Number.POSITIVE_INFINITY;

  return promoStart <= rangeEnd && promoEnd >= rangeStart;
};

export function ConfigPanel({
  dateRange,
  onDateRangeChange,
  promos,
  selectedPromoId,
  onPromoChange,
  productPromo,
  onProductPromoChange,
  shippingPromo,
  onShippingPromoChange,
  shippingTiers,
  onShippingTiersChange,
  surcharges,
  onSurchargesChange,
  merchantFeePercent,
  onMerchantFeeChange,
  fixedCostPerOrder,
  onFixedCostChange,
  cogsCalculationMode,
  onCogsCalculationModeChange,
  applyHistoricalProductPromo,
  onApplyHistoricalProductPromoChange,
  pointsPerDollar,
  redemptionRate,
  onRedemptionRateChange,
  pointDollarValue,
  onPointDollarValueChange,
  onConfigInputChange,
  onResetConfig,
  promoLoading = false,
  onRunSimulation,
  isRunning,
  result
}: ConfigPanelProps) {
  const promoOptions = useMemo(() => {
    if (!Array.isArray(promos) || promos.length === 0) {
      return [];
    }

    const rangeStartDate = dateRange?.from ? startOfDay(dateRange.from) : undefined;
    const rangeEndSource = dateRange?.to ?? dateRange?.from;
    const rangeEndDate = rangeEndSource ? endOfDay(rangeEndSource) : undefined;
    const rangeStartTimestamp = rangeStartDate?.getTime();
    const rangeEndTimestamp = rangeEndDate?.getTime();

    const filteredPromos = promos.filter((promo) =>
      promoOverlapsRange(promo, rangeStartTimestamp, rangeEndTimestamp)
    );

    return filteredPromos
      .sort((a, b) => Number(b.id) - Number(a.id))
      .map((promo) => {
        const privateDescription = (promo.privateDescription ?? '').trim();
        return {
          value: promo.id.toString(),
          label: promo.code || `Promo ${promo.id}`,
          description: privateDescription,
        };
      });
  }, [promos, dateRange]);

  useEffect(() => {
    if (shippingTiers.length === 0) {
      return;
    }

    const tiersMissingIds = shippingTiers.some((tier) => !tier.id);
    if (!tiersMissingIds) {
      return;
    }

    const normalizedTiers = shippingTiers.map((tier) =>
      tier.id ? tier : { ...tier, id: generateTierId() }
    );
    onShippingTiersChange(normalizedTiers);
  }, [shippingTiers, onShippingTiersChange]);

  const handleTierUpdate = (index: number, update: Partial<ShippingTierConfig>) => {
    const tiers = [...shippingTiers];
    const current = tiers[index];
    if (!current) {
      return;
    }

    const tierId = current.id ?? generateTierId();
    const mergedTier = {
      ...current,
      ...update,
      id: tierId,
    };

    const normalizedTier: ShippingTierConfig = {
      ...mergedTier,
      threshold: Number.isFinite(mergedTier.threshold) ? mergedTier.threshold ?? 0 : 0,
      value: Number.isFinite(mergedTier.value) ? mergedTier.value ?? 0 : 0,
    };

    tiers[index] = normalizedTier;
    onShippingTiersChange(tiers);
  };

  const handleTierRemove = (index: number) => {
    onConfigInputChange();
    const tiers = shippingTiers.filter((_, i) => i !== index);
    onShippingTiersChange(tiers);
  };

  const handleTierAdd = () => {
    onConfigInputChange();
    const lastThreshold = shippingTiers[shippingTiers.length - 1]?.threshold ?? 0;
    const tiers = [
      ...shippingTiers,
      {
        threshold: lastThreshold,
        mode: "percentage" as const,
        value: 0,
        id: generateTierId(),
      },
    ];
    onShippingTiersChange(tiers);
  };

  const handleFieldBlur = useCallback(() => {
    setTimeout(onRunSimulation, 0);
  }, [onRunSimulation]);

  const sortShippingTiers = useCallback(() => {
    if (shippingTiers.length < 2) {
      return;
    }

    const originalIds = shippingTiers.map((tier) => tier.id);
    const sortedTiers = [...shippingTiers]
      .map((tier) => ({
        ...tier,
        threshold: Number.isFinite(tier.threshold) ? tier.threshold : 0,
        value: Number.isFinite(tier.value) ? tier.value : 0,
      }))
      .sort((a, b) => a.threshold - b.threshold);

    const orderChanged = sortedTiers.some((tier, index) => tier.id !== originalIds[index]);
    if (orderChanged) {
      onShippingTiersChange(sortedTiers);
    }
  }, [shippingTiers, onShippingTiersChange]);

  const handleTierBlur = useCallback(() => {
    sortShippingTiers();
    handleFieldBlur();
  }, [sortShippingTiers, handleFieldBlur]);

  // Surcharge handlers
  useEffect(() => {
    if (surcharges.length === 0) {
      return;
    }

    const surchargesMissingIds = surcharges.some((s) => !s.id);
    if (!surchargesMissingIds) {
      return;
    }

    const normalizedSurcharges = surcharges.map((s) =>
      s.id ? s : { ...s, id: generateSurchargeId() }
    );
    onSurchargesChange(normalizedSurcharges);
  }, [surcharges, onSurchargesChange]);

  const handleSurchargeUpdate = (index: number, update: Partial<SurchargeConfig>) => {
    const items = [...surcharges];
    const current = items[index];
    if (!current) {
      return;
    }

    const surchargeId = current.id ?? generateSurchargeId();
    const merged = {
      ...current,
      ...update,
      id: surchargeId,
    };

    const normalized: SurchargeConfig = {
      ...merged,
      threshold: Number.isFinite(merged.threshold) ? merged.threshold ?? 0 : 0,
      maxThreshold: Number.isFinite(merged.maxThreshold) && (merged.maxThreshold ?? 0) > 0 ? merged.maxThreshold : undefined,
      amount: Number.isFinite(merged.amount) ? merged.amount ?? 0 : 0,
    };

    items[index] = normalized;
    onSurchargesChange(items);
  };

  const handleSurchargeRemove = (index: number) => {
    onConfigInputChange();
    const items = surcharges.filter((_, i) => i !== index);
    onSurchargesChange(items);
  };

  const handleSurchargeAdd = () => {
    onConfigInputChange();
    const lastThreshold = surcharges[surcharges.length - 1]?.threshold ?? 0;
    const items = [
      ...surcharges,
      {
        threshold: lastThreshold,
        target: "shipping" as const,
        amount: 0,
        id: generateSurchargeId(),
      },
    ];
    onSurchargesChange(items);
  };

  const sortSurcharges = useCallback(() => {
    if (surcharges.length < 2) {
      return;
    }

    const originalIds = surcharges.map((s) => s.id);
    const sorted = [...surcharges]
      .map((s) => ({
        ...s,
        threshold: Number.isFinite(s.threshold) ? s.threshold : 0,
        amount: Number.isFinite(s.amount) ? s.amount : 0,
      }))
      .sort((a, b) => a.threshold - b.threshold);

    const orderChanged = sorted.some((s, index) => s.id !== originalIds[index]);
    if (orderChanged) {
      onSurchargesChange(sorted);
    }
  }, [surcharges, onSurchargesChange]);

  const handleSurchargeBlur = useCallback(() => {
    sortSurcharges();
    handleFieldBlur();
  }, [sortSurcharges, handleFieldBlur]);

  const sectionTitleClass = "text-[0.65rem] font-semibold uppercase tracking-[0.18em] text-muted-foreground";
  const sectionBaseClass = "flex flex-col rounded-md border border-border/60 bg-muted/30 px-3 py-2.5";
  const sectionClass = `${sectionBaseClass} gap-3`;
  const compactSectionClass = `${sectionBaseClass} gap-2`;
  const sectionHeaderClass = "flex items-center justify-between";
  const fieldClass = "flex flex-col gap-1";
  const labelClass = "text-[0.65rem] uppercase tracking-wide text-muted-foreground";
  const fieldRowClass = "flex flex-col gap-2";
  const fieldRowHorizontalClass = "flex flex-col gap-2 sm:flex-row sm:gap-3";
  const compactTriggerClass = "h-8 px-1.5 text-xs";
  const compactNumberClass = "h-8 px-1.5 text-sm";
  const compactWideNumberClass = "h-8 px-1.5 text-sm";
  const metricPillClass = "flex items-center gap-1 rounded border border-border/60 bg-background px-2 py-1 text-[0.68rem] font-medium text-foreground";
  const showProductAdjustments = productPromo.type !== "none";
  const showShippingAdjustments = shippingPromo.type !== "none";
  const promoSelectValue = selectedPromoId != null ? selectedPromoId.toString() : "__all__";

  return (
    <Card className="w-full">
      <CardContent className="flex flex-col gap-2 px-2 py-2">
        <div className="space-y-2">
          <section className={sectionClass}>
            <div className={fieldRowClass}>
              <div className={fieldClass}>
                <Label className={labelClass}>Date range</Label>
                <DateRangePicker
                  value={dateRange}
                  onChange={(range) => onDateRangeChange(range)}
                  className=""
                />
              </div>
              <div className={fieldClass}>
                <Label className={labelClass}>Promo code</Label>
                <Select
                  value={promoSelectValue}
                  onValueChange={(value) => {
                    if (value === '__all__') {
                      onPromoChange(undefined);
                      return;
                    }
                    const parsed = Number(value);
                    onPromoChange(Number.isNaN(parsed) ? undefined : parsed);
                  }}
                >
                  <SelectTrigger className={`${compactTriggerClass} w-full`}>
                    {promoLoading ? (
                      <div className="flex w-full items-center">
                        <Skeleton className="h-4 w-3/4" />
                      </div>
                    ) : (
                      <SelectValue placeholder="All promos">
                        {promoSelectValue === "__all__" 
                          ? "All promos" 
                          : promoOptions.find(p => p.value === promoSelectValue)?.label
                        }
                      </SelectValue>
                    )}
                  </SelectTrigger>
                  <SelectContent className="max-h-56">
                    <SelectItem value="__all__">All promos</SelectItem>
                    {promoOptions.map((promo) => (
                      <SelectItem key={promo.value} value={promo.value}>
                        <div className="flex flex-col text-xs">
                          <span>{promo.label}</span>
                          {promo.description && (
                            <span className="text-muted-foreground">{promo.description}</span>
                          )}
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {result?.totals && (
              <div className="flex flex-wrap gap-2">
                <div className={`${metricPillClass} whitespace-nowrap`}>
                  <span className="text-xs font-semibold">{formatNumber(result.totals.orders)}</span>
                  <span className="text-[0.6rem] uppercase text-muted-foreground">orders</span>
                </div>
                <div className={`${metricPillClass} whitespace-nowrap`}>
                  <span className="text-xs font-semibold">{formatPercent(result.totals.productDiscountRate)}</span>
                  <span className="text-[0.6rem] uppercase text-muted-foreground">avg discount</span>
                </div>
                {result.totals.overallCogsPercentage != null && (
                  <div className={`${metricPillClass} whitespace-nowrap`}>
                    <span className="text-xs font-semibold">{formatPercent(result.totals.overallCogsPercentage)}</span>
                    <span className="text-[0.6rem] uppercase text-muted-foreground">avg COGS</span>
                  </div>
                )}
              </div>
            )}
          </section>
          <section className={sectionClass}>
            <div className={sectionHeaderClass}>
              <span className={sectionTitleClass}>Product promo</span>
            </div>
            <div className={fieldRowClass}>
              <div className={fieldClass}>
                <Label className={labelClass}>Promo type</Label>
                <Select
                  value={productPromo.type}
                  onValueChange={(value) => onProductPromoChange({ type: value as DiscountPromoType })}
                >
                  <SelectTrigger className={`${compactTriggerClass} w-full`}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">No additional promo</SelectItem>
                    <SelectItem value="percentage_subtotal">% off subtotal</SelectItem>
                    <SelectItem value="percentage_regular">% off regular price</SelectItem>
                    <SelectItem value="fixed_amount">Fixed dollar discount</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {showProductAdjustments && (
                <div className={fieldRowHorizontalClass}>
                  <div className={fieldClass}>
                    <Label className={labelClass}>
                      {productPromo.type.startsWith("percentage") ? "Percent" : "Amount"}
                    </Label>
                    <Input
                      className={compactNumberClass}
                      type="number"
                      step="1"
                      value={productPromo.value ?? 0}
                      onChange={(event) => {
                        onConfigInputChange();
                        onProductPromoChange({ value: parseNumber(event.target.value, 0) });
                      }}
                      onBlur={handleFieldBlur}
                    />
                  </div>
                  <div className={fieldClass}>
                    <Label className={labelClass}>Min subtotal</Label>
                    <Input
                      className={compactNumberClass}
                      type="number"
                      step="1"
                      value={productPromo.minSubtotal ?? 0}
                      onChange={(event) => {
                        onConfigInputChange();
                        onProductPromoChange({ minSubtotal: parseNumber(event.target.value, 0) });
                      }}
                      onBlur={handleFieldBlur}
                    />
                  </div>
                </div>
              )}
              <div className="flex items-start justify-between gap-2 pt-1">
                <div className="flex flex-col">
                  <Label className={labelClass}>Replay historical discount</Label>
                  <span className="text-[0.65rem] text-muted-foreground leading-snug">
                    Only when promo type is "No additional promo"
                  </span>
                </div>
                <Switch
                  checked={applyHistoricalProductPromo}
                  onCheckedChange={(checked) => {
                    onConfigInputChange();
                    onApplyHistoricalProductPromoChange(checked);
                    setTimeout(() => onRunSimulation(), 0);
                  }}
                  disabled={productPromo.type !== "none"}
                />
              </div>
            </div>
          </section>
              
          <section className={sectionClass}>
            <div className={sectionHeaderClass}>
              <span className={sectionTitleClass}>Shipping promo</span>
            </div>
            <div className={fieldRowClass}>
              <div className={fieldClass}>
                <Label className={labelClass}>Promo type</Label>
                <Select
                  value={shippingPromo.type}
                  onValueChange={(value) => onShippingPromoChange({ type: value as ShippingPromoType })}
                >
                  <SelectTrigger className={`${compactTriggerClass} w-full`}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">No shipping promo</SelectItem>
                    <SelectItem value="percentage">% off shipping charge</SelectItem>
                    <SelectItem value="fixed">Fixed dollar discount</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {showShippingAdjustments && (
                <>
                  <div className={fieldRowHorizontalClass}>
                    <div className={fieldClass}>
                      <Label className={labelClass}>
                        {shippingPromo.type === "percentage" ? "Percent" : "Amount"}
                      </Label>
                      <Input
                        className={compactNumberClass}
                        type="number"
                        step="1"
                        value={shippingPromo.value ?? 0}
                        onChange={(event) => {
                          onConfigInputChange();
                          onShippingPromoChange({ value: parseNumber(event.target.value, 0) });
                        }}
                        onBlur={handleFieldBlur}
                      />
                    </div>
                    <div className={fieldClass}>
                      <Label className={labelClass}>Min subtotal</Label>
                      <Input
                        className={compactNumberClass}
                        type="number"
                        step="1"
                        value={shippingPromo.minSubtotal ?? 0}
                        onChange={(event) => {
                          onConfigInputChange();
                          onShippingPromoChange({ minSubtotal: parseNumber(event.target.value, 0) });
                        }}
                        onBlur={handleFieldBlur}
                      />
                    </div>
                  </div>
                  <div className={fieldClass}>
                    <Label className={labelClass}>Max discount</Label>
                    <Input
                      className={compactNumberClass}
                      type="number"
                      step="1"
                      value={shippingPromo.maxDiscount ?? 0}
                      onChange={(event) => {
                        onConfigInputChange();
                        onShippingPromoChange({ maxDiscount: parseNumber(event.target.value, 0) });
                      }}
                      onBlur={handleFieldBlur}
                    />
                  </div>
                </>
              )}
            </div>
          </section>

          <section className={compactSectionClass}>
            <div className={sectionHeaderClass}>
              <span className={sectionTitleClass}>Shipping tiers</span>
              <Button variant="outline" size="sm" onClick={handleTierAdd} className="flex items-center gap-1">
                <PlusIcon className="w-3 h-3" />
                Add tier
              </Button>
            </div>
            {shippingTiers.length === 0 ? (
              <p className="text-xs text-muted-foreground">Add tiers to model automatic shipping discounts.</p>
            ) : (
              <ScrollArea>
                <div className="flex flex-col gap-2 pr-1 -mx-2">
                  <div className="grid gap-2 px-2 py-1 text-[0.65rem] font-medium uppercase tracking-[0.18em] text-muted-foreground sm:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)_minmax(0,1fr)_auto]">
                    <div>Amount</div>
                    <div>Type</div>
                    <div>Value</div>
                    <div className="w-1.5" aria-hidden="true" />
                  </div>
                  {shippingTiers.map((tier, index) => {
                    const tierKey = tier.id ?? `tier-${index}`;
                    return (
                      <div
                        key={tierKey}
                        className="relative grid gap-2 rounded px-2 py-0.5 text-xs sm:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)_minmax(0,1fr)_auto] sm:items-end"
                      >
                        <div>
                          <Input
                            className={compactNumberClass}
                            type="number"
                            step="1"
                            value={tier.threshold}
                            onChange={(event) => {
                              onConfigInputChange();
                              handleTierUpdate(index, {
                                threshold: parseNumber(event.target.value, 0),
                              });
                            }}
                            onBlur={handleTierBlur}
                          />
                        </div>
                        <div>
                          <Select
                            value={tier.mode}
                            onValueChange={(value) => {
                              onConfigInputChange();
                              handleTierUpdate(index, { mode: value as ShippingTierConfig["mode"] });
                            }}
                          >
                            <SelectTrigger className={`${compactTriggerClass} w-full`}>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="percentage">% off</SelectItem>
                              <SelectItem value="flat">Flat rate</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <div>
                          <Input
                            className={compactNumberClass}
                            type="number"
                            step="1"
                            value={tier.value}
                            onChange={(event) => {
                              onConfigInputChange();
                              handleTierUpdate(index, { value: parseNumber(event.target.value, 0) });
                            }}
                            onBlur={handleTierBlur}
                          />
                        </div>
                        <div className="w-1.5" aria-hidden="true" />
                        <div className="absolute -right-0.5 top-1/2 -translate-y-1/2 flex justify-end">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleTierRemove(index)}
                            className="p-1"
                          >
                            <X className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </ScrollArea>
            )}
          </section>

          <section className={compactSectionClass}>
            <div className={sectionHeaderClass}>
              <span className={sectionTitleClass}>Surcharges</span>
              <Button variant="outline" size="sm" onClick={handleSurchargeAdd} className="flex items-center gap-1">
                <PlusIcon className="w-3 h-3" />
                Add surcharge
              </Button>
            </div>
            {surcharges.length === 0 ? (
              <p className="text-xs text-muted-foreground">Add surcharges to model fees at different order values.</p>
            ) : (
              <ScrollArea>
                <div className="flex flex-col gap-2 pr-1 -mx-2">
                  <div className="grid gap-2 px-2 py-1 text-[0.65rem] font-medium uppercase tracking-[0.18em] text-muted-foreground sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1.2fr)_minmax(0,0.8fr)_auto]">
                    <div>Min</div>
                    <div>Max</div>
                    <div>Add To</div>
                    <div>Amount</div>
                    <div className="w-1.5" aria-hidden="true" />
                  </div>
                  {surcharges.map((surcharge, index) => {
                    const surchargeKey = surcharge.id ?? `surcharge-${index}`;
                    return (
                      <div
                        key={surchargeKey}
                        className="relative grid gap-2 rounded px-2 py-2 text-xs sm:grid-cols-[minmax(0,0.9fr)_minmax(0,0.9fr)_minmax(0,1fr)_minmax(0,0.9fr)_auto] sm:items-end"
                      >
                        <div>
                          <Input
                            className={compactNumberClass}
                            type="number"
                            step="1"
                            value={surcharge.threshold}
                            onChange={(event) => {
                              onConfigInputChange();
                              handleSurchargeUpdate(index, {
                                threshold: parseNumber(event.target.value, 0),
                              });
                            }}
                            onBlur={handleSurchargeBlur}
                          />
                        </div>
                        <div>
                          <Input
                            className={compactNumberClass}
                            type="number"
                            step="1"
                            placeholder="∞"
                            value={surcharge.maxThreshold ?? ''}
                            onChange={(event) => {
                              onConfigInputChange();
                              const val = event.target.value;
                              handleSurchargeUpdate(index, {
                                maxThreshold: val === '' ? undefined : parseNumber(val, 0),
                              });
                            }}
                            onBlur={handleSurchargeBlur}
                          />
                        </div>
                        <div>
                          <Select
                            value={surcharge.target}
                            onValueChange={(value) => {
                              onConfigInputChange();
                              handleSurchargeUpdate(index, { target: value as SurchargeConfig["target"] });
                            }}
                          >
                            <SelectTrigger className={`${compactTriggerClass} w-full`}>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="shipping">Shipping</SelectItem>
                              <SelectItem value="order">Order</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <div>
                          <Input
                            className={compactNumberClass}
                            type="number"
                            step="0.01"
                            value={surcharge.amount}
                            onChange={(event) => {
                              onConfigInputChange();
                              handleSurchargeUpdate(index, { amount: parseNumber(event.target.value, 0) });
                            }}
                            onBlur={handleSurchargeBlur}
                          />
                        </div>
                        <div className="w-1.5" aria-hidden="true" />
                        <div className="absolute -right-0.5 top-1/2 -translate-y-1/2 flex justify-end">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleSurchargeRemove(index)}
                            className="p-1"
                          >
                            <X className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </ScrollArea>
            )}
          </section>

          <section className={sectionClass}>
            <div className={sectionHeaderClass}>
              <span className={sectionTitleClass}>Order costs</span>
            </div>
            <div className={fieldRowClass}>
              <div className={fieldClass}>
                <Label className={labelClass}>COGS calculation</Label>
                <Select
                  value={cogsCalculationMode}
                  onValueChange={(value) => {
                    onConfigInputChange();
                    onCogsCalculationModeChange(value as CogsCalculationMode);
                  }}
                >
                  <SelectTrigger className={`${compactTriggerClass} w-full`}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="actual">Actual COGS per bucket</SelectItem>
                    <SelectItem value="average">Average COGS percentage</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className={fieldRowHorizontalClass}>
                <div className={fieldClass}>
                  <Label className={labelClass}>Merchant fee (%)</Label>
                  <Input
                    className={compactNumberClass}
                    type="number"
                    step="0.01"
                    value={merchantFeePercent}
                    onChange={(event) => {
                      onConfigInputChange();
                      onMerchantFeeChange(parseNumber(event.target.value, merchantFeePercent));
                    }}
                    onBlur={handleFieldBlur}
                  />
                </div>
                <div className={fieldClass}>
                  <Label className={labelClass}>Fixed costs ($)</Label>
                  <Input
                    className={compactNumberClass}
                    type="number"
                    step="0.01"
                    value={fixedCostPerOrder}
                    onChange={(event) => {
                      onConfigInputChange();
                      onFixedCostChange(parseNumber(event.target.value, fixedCostPerOrder));
                    }}
                    onBlur={handleFieldBlur}
                  />
                </div>
              </div>
            </div>
          </section>

          <section className={sectionClass}>
            <div className={sectionHeaderClass}>
              <span className={sectionTitleClass}>Rewards points</span>
            </div>
            <div className={fieldRowClass}>
              <div className={fieldRowHorizontalClass}>
                <div className="flex flex-col gap-1.5">
                  <span className={labelClass}>Points per $</span>
                  <span className="text-sm font-medium mt-1">{Number.isFinite(pointsPerDollar) ? pointsPerDollar.toFixed(4) : '—'}</span>
                </div>
                <div className={fieldClass}>
                  <Label className={labelClass}>Redemption rate (%)</Label>
                  <Input
                    className={compactNumberClass}
                    type="number"
                    step="0.01"
                    value={Number((redemptionRate * 100).toFixed(2))}
                    onChange={(event) => {
                      onConfigInputChange();
                      onRedemptionRateChange(parseNumber(event.target.value, redemptionRate * 100) / 100);
                    }}
                    onBlur={handleFieldBlur}
                  />
                </div>
              </div>
              <div className={fieldClass}>
                <Label className={labelClass}>Point value ($)</Label>
                <Input
                  className={compactWideNumberClass}
                  type="number"
                  step="0.0001"
                  value={pointDollarValue}
                  onChange={(event) => {
                    onConfigInputChange();
                    onPointDollarValueChange(parseNumber(event.target.value, pointDollarValue));
                  }}
                  onBlur={handleFieldBlur}
                />
              </div>
            </div>
          </section>
        </div>

        <div className="flex flex-wrap gap-2">
          <Button variant="outline" size="sm" onClick={onResetConfig} disabled={isRunning}>
            Reset
          </Button>
          <Button size="sm" className="sm:w-auto" onClick={onRunSimulation} disabled={isRunning}>
            {isRunning ? "Running simulation..." : "Run simulation"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
