import { ArrowLeftIcon, ArrowRightIcon } from "@heroicons/react/24/outline";
import type { CatalogProductBase } from "@customer-portal/domain/services";
import { useRouter } from "next/navigation";
import { Button } from "@/components/atoms/button";

interface OrderSummaryProps {
  plan: {
    name: string;
    monthlyPrice?: number | null;
    internetPlanTier?: string | null;
  };

  // Selected items
  selectedAddons?: CatalogProductBase[];
  activationFees?: CatalogProductBase[];

  // Configuration details
  configDetails?: Array<{
    label: string;
    value: string;
  }>;

  // Additional info lines
  infoLines?: string[];

  // Totals
  monthlyTotal: number;
  oneTimeTotal?: number;
  hasMissingPrices?: boolean;

  // Actions (optional)
  onContinue?: () => void;
  backUrl?: string;
  backLabel?: string;
  continueLabel?: string;
  showActions?: boolean;

  // Styling
  variant?: "simple" | "enhanced";
  disabled?: boolean;
}

function EnhancedPricingSection({
  plan,
  selectedAddons,
  activationFees,
  monthlyTotal,
  oneTimeTotal,
  hasMissingPrices,
}: {
  plan: OrderSummaryProps["plan"];
  selectedAddons: CatalogProductBase[];
  activationFees: CatalogProductBase[];
  monthlyTotal: number;
  oneTimeTotal: number;
  hasMissingPrices: boolean;
}) {
  return (
    <div className="pt-2 border-t border-border mb-4">
      <h4 className="font-semibold text-foreground mb-3">Pricing Summary</h4>

      <div className="space-y-2 mb-4">
        <div className="text-sm font-medium text-foreground mb-1">Monthly Costs:</div>
        {plan.monthlyPrice != null && (
          <div className="flex justify-between text-sm">
            <span className="text-muted-foreground">
              Base Plan {plan.internetPlanTier && `(${plan.internetPlanTier})`}:
            </span>
            <span className="font-medium">¥{plan.monthlyPrice.toLocaleString()}</span>
          </div>
        )}

        {selectedAddons.map(
          (addon, index) =>
            addon.billingCycle === "Monthly" && (
              <div key={index} className="flex justify-between text-sm">
                <span className="text-muted-foreground">{String(addon.name)}:</span>
                <span className="font-medium">
                  ¥{(addon.monthlyPrice ?? 0).toLocaleString()}/month
                </span>
              </div>
            )
        )}

        <div className="flex justify-between pt-2 border-t border-border">
          <span className="font-semibold text-foreground">Total Monthly:</span>
          <span className="font-bold text-lg text-blue-600">
            {hasMissingPrices ? (
              <span className="text-red-600 text-sm">Some prices unavailable</span>
            ) : (
              `¥${monthlyTotal.toLocaleString()}`
            )}
          </span>
        </div>
      </div>

      {(oneTimeTotal > 0 || activationFees.length > 0) && (
        <div className="space-y-2">
          <div className="text-sm font-medium text-foreground mb-1">One-time Costs:</div>
          {activationFees.map((fee, index) => (
            <div key={index} className="flex justify-between text-sm">
              <span className="text-muted-foreground">{String(fee.name)}:</span>
              <span className="font-medium">¥{(fee.oneTimePrice ?? 0).toLocaleString()}</span>
            </div>
          ))}
          {selectedAddons.map(
            (addon, index) =>
              addon.billingCycle !== "Monthly" && (
                <div key={index} className="flex justify-between text-sm">
                  <span className="text-muted-foreground">{String(addon.name)}:</span>
                  <span className="font-medium">¥{(addon.oneTimePrice ?? 0).toLocaleString()}</span>
                </div>
              )
          )}
          {oneTimeTotal > 0 && (
            <div className="flex justify-between pt-2 border-t border-border">
              <span className="font-semibold text-foreground">Total One-time:</span>
              <span className="font-bold text-lg text-orange-600">
                ¥{oneTimeTotal.toLocaleString()}
              </span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function SimplePricingSection({
  plan,
  selectedAddons,
  activationFees,
  infoLines,
  monthlyTotal,
  oneTimeTotal,
}: {
  plan: OrderSummaryProps["plan"];
  selectedAddons: CatalogProductBase[];
  activationFees: CatalogProductBase[];
  infoLines: string[];
  monthlyTotal: number;
  oneTimeTotal: number;
}) {
  return (
    <>
      <div className="space-y-2 mb-4">
        <div className="flex justify-between">
          <span className="text-muted-foreground">{plan.name}</span>
          <span className="font-medium">¥{(plan.monthlyPrice ?? 0).toLocaleString()}/mo</span>
        </div>
        {activationFees.map((fee, index) => (
          <div key={index} className="flex justify-between">
            <span className="text-muted-foreground">{String(fee.name)}</span>
            <span className="font-medium">
              ¥{(fee.oneTimePrice ?? fee.unitPrice ?? 0).toLocaleString()} one-time
            </span>
          </div>
        ))}
        {selectedAddons.map((addon, index) => (
          <div key={index} className="flex justify-between">
            <span className="text-muted-foreground">{String(addon.name)}</span>
            <span className="font-medium">
              ¥
              {(addon.billingCycle === "Monthly"
                ? (addon.monthlyPrice ?? 0)
                : (addon.oneTimePrice ?? 0)
              ).toLocaleString()}
              {addon.billingCycle === "Monthly" ? "/mo" : " one-time"}
            </span>
          </div>
        ))}
      </div>

      {infoLines.length > 0 && (
        <div className="text-xs text-muted-foreground mb-4 space-y-1">
          {infoLines.map((line, index) => (
            <div key={index}>• {line}</div>
          ))}
        </div>
      )}

      <div className="border-t pt-4 mb-4">
        <div className="flex justify-between text-lg font-semibold">
          <span>Monthly Total:</span>
          <span>¥{monthlyTotal.toLocaleString()}/mo</span>
        </div>
        {oneTimeTotal > 0 && (
          <div className="flex justify-between text-lg font-semibold text-orange-600">
            <span>One-time Total:</span>
            <span>¥{oneTimeTotal.toLocaleString()}</span>
          </div>
        )}
      </div>
    </>
  );
}

function OrderActions({
  variant,
  showActions,
  onContinue,
  backUrl,
  backLabel,
  continueLabel,
  disabled,
}: {
  variant: string;
  showActions: boolean;
  onContinue: (() => void) | undefined;
  backUrl: string | undefined;
  backLabel: string;
  continueLabel: string;
  disabled: boolean;
}) {
  const router = useRouter();
  if (!showActions) return null;

  if (variant === "simple") {
    return (
      <div className="flex gap-4">
        {backUrl ? (
          <Button
            variant="outline"
            className="flex-1"
            leftIcon={<ArrowLeftIcon className="h-4 w-4" />}
            onClick={() => {
              if (!disabled) router.push(backUrl);
            }}
            disabled={disabled}
          >
            {backLabel}
          </Button>
        ) : null}
        {onContinue ? (
          <Button
            className="flex-1"
            rightIcon={<ArrowRightIcon className="h-4 w-4" />}
            onClick={onContinue}
            disabled={disabled}
          >
            {continueLabel}
          </Button>
        ) : null}
      </div>
    );
  }

  if (!onContinue) return null;

  return (
    <div>
      <Button
        size="lg"
        className="w-full mt-8 group text-lg font-bold"
        rightIcon={<ArrowRightIcon className="w-5 h-5" />}
        onClick={onContinue}
        disabled={disabled}
      >
        {continueLabel}
      </Button>
    </div>
  );
}

function PlanConfigDetails({
  plan,
  configDetails,
  addonCount,
}: {
  plan: OrderSummaryProps["plan"];
  configDetails: Array<{ label: string; value: string }>;
  addonCount: number;
}) {
  return (
    <div className="space-y-2 text-sm mb-4">
      <div className="flex justify-between">
        <span className="text-muted-foreground">Plan:</span>
        <span className="font-medium">
          {plan.name}
          {plan.internetPlanTier && ` (${plan.internetPlanTier})`}
        </span>
      </div>
      {configDetails.map((detail, index) => (
        <div key={index} className="flex justify-between">
          <span className="text-muted-foreground">{detail.label}:</span>
          <span className="font-medium">{detail.value}</span>
        </div>
      ))}
      {addonCount > 0 && (
        <div className="flex justify-between">
          <span className="text-muted-foreground">Add-ons:</span>
          <span className="font-medium">{addonCount} selected</span>
        </div>
      )}
    </div>
  );
}

const CONTAINER_CLASSES = {
  enhanced:
    "bg-gradient-to-br from-muted to-info-bg rounded-2xl border-2 border-border p-8 shadow-lg",
  simple: "bg-card border border-border rounded-xl p-6",
};

export function OrderSummary({
  plan,
  selectedAddons = [],
  activationFees = [],
  configDetails = [],
  infoLines = [],
  monthlyTotal,
  oneTimeTotal = 0,
  hasMissingPrices = false,
  onContinue,
  backUrl,
  backLabel = "Back to Plans",
  continueLabel = "Continue to Checkout",
  showActions = true,
  variant = "simple",
  disabled = false,
}: OrderSummaryProps) {
  return (
    <div className={CONTAINER_CLASSES[variant]}>
      <h3 className="text-lg font-semibold text-foreground mb-4">Order Summary</h3>

      <PlanConfigDetails
        plan={plan}
        configDetails={configDetails}
        addonCount={selectedAddons.length}
      />

      {variant === "enhanced" && (
        <EnhancedPricingSection
          plan={plan}
          selectedAddons={selectedAddons}
          activationFees={activationFees}
          monthlyTotal={monthlyTotal}
          oneTimeTotal={oneTimeTotal}
          hasMissingPrices={hasMissingPrices}
        />
      )}

      {variant === "simple" && (
        <SimplePricingSection
          plan={plan}
          selectedAddons={selectedAddons}
          activationFees={activationFees}
          infoLines={infoLines}
          monthlyTotal={monthlyTotal}
          oneTimeTotal={oneTimeTotal}
        />
      )}

      <OrderActions
        variant={variant}
        showActions={showActions}
        onContinue={onContinue}
        backUrl={backUrl}
        backLabel={backLabel}
        continueLabel={continueLabel}
        disabled={disabled}
      />
    </div>
  );
}
