"use client";

import { CheckCircleIcon } from "@heroicons/react/24/solid";
import type { CatalogProductBase } from "@customer-portal/domain/catalog";
interface AddonGroupProps {
  addons: Array<CatalogProductBase & { bundledAddonId?: string; isBundledAddon?: boolean }>;
  selectedAddonSkus: string[];
  onAddonToggle: (skus: string[]) => void;
  showSkus?: boolean;
}

type BundledAddonGroup = {
  id: string;
  name: string;
  description: string;
  monthlyPrice?: number;
  activationPrice?: number;
  skus: string[];
  isBundled: boolean;
  displayOrder: number;
};

function buildGroupedAddons(
  addons: Array<CatalogProductBase & { bundledAddonId?: string; isBundledAddon?: boolean }>
): BundledAddonGroup[] {
  const groups: BundledAddonGroup[] = [];
  const processed = new Set<string>();

  // Sort by display order
  const sorted = [...addons].sort((a, b) => (a.displayOrder ?? 0) - (b.displayOrder ?? 0));

  for (const addon of sorted) {
    if (processed.has(addon.sku)) continue;

    // Try to find bundle partner
    if (addon.isBundledAddon && addon.bundledAddonId) {
      const partner = sorted.find(candidate => candidate.id === addon.bundledAddonId);

      if (partner && !processed.has(partner.sku)) {
        // Create bundle
        const bundle = createBundle(addon, partner);
        groups.push(bundle);
        processed.add(addon.sku);
        processed.add(partner.sku);
        continue;
      }
    }

    // Create standalone item
    groups.push(createStandaloneItem(addon));
    processed.add(addon.sku);
  }

  return groups;
}

function createBundle(
  addon1: CatalogProductBase & { bundledAddonId?: string; isBundledAddon?: boolean },
  addon2: CatalogProductBase & { bundledAddonId?: string; isBundledAddon?: boolean }
): BundledAddonGroup {
  // Determine which is monthly vs onetime
  const monthlyAddon = addon1.billingCycle === "Monthly" ? addon1 : addon2;
  const onetimeAddon = addon1.billingCycle === "Onetime" ? addon1 : addon2;

  // Use monthly addon name as base, clean it up
  const baseName = monthlyAddon.name.replace(/\s*(Monthly|Installation|Fee)\s*/gi, "").trim();

  return {
    id: `bundle-${addon1.sku}-${addon2.sku}`,
    name: baseName,
    description: `${baseName} (monthly service + installation)`,
    monthlyPrice:
      typeof monthlyAddon.monthlyPrice === "number" && monthlyAddon.monthlyPrice > 0
        ? monthlyAddon.monthlyPrice
        : undefined,
    activationPrice:
      typeof onetimeAddon.oneTimePrice === "number" && onetimeAddon.oneTimePrice > 0
        ? onetimeAddon.oneTimePrice
        : undefined,
    skus: [addon1.sku, addon2.sku],
    isBundled: true,
    displayOrder: Math.min(addon1.displayOrder ?? 0, addon2.displayOrder ?? 0),
  };
}

function createStandaloneItem(
  addon: CatalogProductBase & { bundledAddonId?: string; isBundledAddon?: boolean }
): BundledAddonGroup {
  return {
    id: addon.sku,
    name: addon.name,
    description: addon.description || "",
    monthlyPrice:
      typeof addon.monthlyPrice === "number" && addon.monthlyPrice > 0
        ? addon.monthlyPrice
        : undefined,
    activationPrice:
      typeof addon.oneTimePrice === "number" && addon.oneTimePrice > 0
        ? addon.oneTimePrice
        : undefined,
    skus: [addon.sku],
    isBundled: false,
    displayOrder: addon.displayOrder ?? 0,
  };
}

export function AddonGroup({
  addons,
  selectedAddonSkus,
  onAddonToggle,
  showSkus = false,
}: AddonGroupProps) {
  const showEmptyState = selectedAddonSkus.length === 0;
  const groupedAddons = buildGroupedAddons(addons);

  const handleGroupToggle = (group: BundledAddonGroup) => {
    const isSelected = group.skus.every(sku => selectedAddonSkus.includes(sku));
    if (isSelected) {
      onAddonToggle(selectedAddonSkus.filter(sku => !group.skus.includes(sku)));
    } else {
      const filtered = selectedAddonSkus.filter(sku => !group.skus.includes(sku));
      onAddonToggle([...filtered, ...group.skus]);
    }
  };

  if (groupedAddons.length === 0) {
    return (
      <div className="text-center py-4 text-gray-500">
        <p>No add-ons available for this plan</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {groupedAddons.map(group => {
        const isSelected = group.skus.every(sku => selectedAddonSkus.includes(sku));

        return (
          <label
            key={group.id}
            className={`flex items-start gap-3 p-4 rounded-lg border-2 cursor-pointer transition-all ${
              isSelected
                ? "border-green-500 bg-green-50 ring-2 ring-green-100"
                : "border-gray-200 hover:border-gray-300"
            }`}
          >
            <input
              type="checkbox"
              checked={isSelected}
              onChange={() => handleGroupToggle(group)}
              className="text-green-600 focus:ring-green-500 mt-1"
            />
            <div className="flex-1">
              <div className="flex items-center justify-between">
                <span className="font-medium text-gray-900">{group.name}</span>
                {isSelected && <CheckCircleIcon className="h-5 w-5 text-green-600" />}
              </div>
              <p className="text-sm text-gray-600 mt-1">{group.description}</p>
              <div className="flex flex-wrap gap-4 mt-2">
                {group.monthlyPrice !== undefined && (
                  <span className="text-sm font-semibold text-blue-600">
                    ¥{group.monthlyPrice.toLocaleString()}/month
                  </span>
                )}
                {group.activationPrice !== undefined && (
                  <span className="text-sm font-semibold text-orange-600">
                    Activation: ¥{group.activationPrice.toLocaleString()}
                  </span>
                )}
              </div>
              {group.isBundled && (
                <div className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                    <path
                      fillRule="evenodd"
                      d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z"
                      clipRule="evenodd"
                    />
                  </svg>
                  Bundle Package
                </div>
              )}
              {showSkus && (
                <div className="text-xs text-gray-500 mt-1">SKUs: {group.skus.join(", ")}</div>
              )}
            </div>
          </label>
        );
      })}

      <div
        aria-hidden={!showEmptyState}
        className={`overflow-hidden rounded-xl border border-dashed border-blue-200/70 bg-blue-50/80 px-5 transition-all duration-300 ease-out ${
          showEmptyState
            ? "opacity-100 translate-y-0 max-h-32 py-4"
            : "pointer-events-none opacity-0 -translate-y-2 max-h-0 py-0"
        }`}
      >
        <p className="text-sm font-medium text-blue-800">No add-ons selected</p>
        <p className="text-xs text-blue-700/80 mt-1">
          Pick optional services now or continue without extras—add them later anytime.
        </p>
      </div>
    </div>
  );
}
