"use client";

import { ReactNode } from "react";
import { ArrowLeftIcon, ArrowRightIcon, InformationCircleIcon } from "@heroicons/react/24/outline";
import { AnimatedCard } from "@/components/molecules";
import { Formatting } from "@customer-portal/domain/toolkit";

const { formatCurrency } = Formatting;
import { Button } from "@/components/atoms/button";
import { useRouter } from "next/navigation";

// Align with shared catalog contracts
import type { CatalogProductBase } from "@customer-portal/domain/catalog";
import type { CheckoutTotals } from "@customer-portal/domain/orders";

// Enhanced order item representation for UI summary
export type OrderItem = CatalogProductBase & {
  id?: string;
  quantity?: number;
  autoAdded?: boolean;
  itemClass?: string;
};

export interface OrderConfiguration {
  label: string;
  value: string;
  important?: boolean;
}

// Totals summary for UI; base fields mirror API aggregates
export type OrderTotals = CheckoutTotals & {
  annualTotal?: number;
  discountAmount?: number;
  taxAmount?: number;
};

export interface EnhancedOrderSummaryProps {
  // Core order data
  items: OrderItem[];
  totals: OrderTotals;

  // Plan information
  planName: string;
  planTier?: string;
  planDescription?: string;

  // Configuration details
  configurations?: OrderConfiguration[];

  // Additional information
  infoLines?: string[];
  disclaimers?: string[];

  // Pricing breakdown control
  showDetailedBreakdown?: boolean;
  showTaxes?: boolean;
  showDiscounts?: boolean;

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

  // State
  disabled?: boolean;
  loading?: boolean;

  // Styling
  variant?: "simple" | "detailed" | "checkout";
  size?: "compact" | "standard" | "large";

  // Custom content
  children?: ReactNode;
  headerContent?: ReactNode;
  footerContent?: ReactNode;
}

export function EnhancedOrderSummary({
  items,
  totals,
  planName,
  planTier,
  planDescription,
  configurations = [],
  infoLines = [],
  disclaimers = [],
  showDetailedBreakdown = true,
  showTaxes = false,
  showDiscounts = false,
  onContinue,
  onBack,
  backUrl,
  backLabel = "Back",
  continueLabel = "Continue",
  showActions = true,
  disabled = false,
  loading = false,
  variant = "detailed",
  size = "standard",
  children,
  headerContent,
  footerContent,
}: EnhancedOrderSummaryProps) {
  const router = useRouter();
  const sizeClasses = {
    compact: "p-4",
    standard: "p-6",
    large: "p-8",
  };

  const getVariantClasses = () => {
    switch (variant) {
      case "checkout":
        return "bg-gradient-to-br from-gray-50 to-blue-50 border-2 border-blue-200 shadow-lg";
      case "detailed":
        return "bg-white border border-gray-200 shadow-md";
      default:
        return "bg-white border border-gray-200";
    }
  };

  const monthlyItems = items.filter(item => item.billingCycle === "Monthly");
  const oneTimeItems = items.filter(item => item.billingCycle === "Onetime");

  return (
    <AnimatedCard className={`${getVariantClasses()} ${sizeClasses[size]} overflow-hidden`}>
      {/* Header */}
      <div className="mb-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-xl font-bold text-gray-900">Order Summary</h3>
          {variant === "checkout" && (
            <div className="text-right">
              <div className="text-2xl font-bold text-blue-600">
                ¥{formatCurrency(totals.monthlyTotal)}/mo
              </div>
              {totals.oneTimeTotal > 0 && (
                <div className="text-sm text-orange-600 font-medium">
                  + ¥{formatCurrency(totals.oneTimeTotal)} one-time
                </div>
              )}
            </div>
          )}
        </div>

        {headerContent}
      </div>

      {/* Plan Information */}
      <div className="mb-6 pb-4 border-b border-gray-200">
        <div className="flex justify-between items-start mb-2">
          <div>
            <h4 className="font-semibold text-gray-900">
              {planName}
              {planTier && <span className="text-blue-600 ml-2">({planTier})</span>}
            </h4>
            {planDescription && <p className="text-sm text-gray-600 mt-1">{planDescription}</p>}
          </div>
        </div>

        {/* Configuration Details */}
        {configurations.length > 0 && (
          <div className="mt-4 space-y-2">
            {configurations.map((config, index) => (
              <div key={index} className="flex justify-between text-sm">
                <span className={`text-gray-600 ${config.important ? "font-medium" : ""}`}>
                  {config.label}:
                </span>
                <span
                  className={`${config.important ? "font-semibold text-gray-900" : "text-gray-800"}`}
                >
                  {config.value}
                </span>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Detailed Pricing Breakdown */}
      {showDetailedBreakdown && variant !== "simple" && (
        <div className="mb-6">
          {/* Monthly Services */}
          {monthlyItems.length > 0 && (
            <div className="mb-4">
              <h5 className="font-medium text-gray-900 mb-2">Monthly Charges</h5>
              <div className="space-y-2">
                {monthlyItems.map((item, index) => (
                  <div key={index} className="flex justify-between text-sm">
                    <div className="flex-1">
                      <span className="text-gray-700">{String(item.name)}</span>
                      {Boolean(item.autoAdded) && (
                        <span className="text-xs text-blue-600 ml-2">(Auto-added)</span>
                      )}
                      {item.description && (
                        <div className="text-xs text-gray-500 mt-1">{String(item.description)}</div>
                      )}
                    </div>
                    <span className="font-medium text-gray-900 ml-4">
                      ¥{formatCurrency(Number(item.monthlyPrice || item.unitPrice || 0))}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* One-time Charges */}
          {oneTimeItems.length > 0 && (
            <div className="mb-4">
              <h5 className="font-medium text-gray-900 mb-2">One-time Charges</h5>
              <div className="space-y-2">
                {oneTimeItems.map((item, index) => (
                  <div key={index} className="flex justify-between text-sm">
                    <div className="flex-1">
                      <span className="text-gray-700">{String(item.name)}</span>
                      {item.description && (
                        <div className="text-xs text-gray-500 mt-1">{String(item.description)}</div>
                      )}
                    </div>
                    <span className="font-medium text-orange-600 ml-4">
                      ¥{formatCurrency(Number(item.oneTimePrice || item.unitPrice || 0))}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Discounts */}
          {showDiscounts && totals.discountAmount && totals.discountAmount > 0 && (
            <div className="mb-4">
              <div className="flex justify-between text-sm">
                <span className="text-green-700">Discount Applied</span>
                <span className="font-medium text-green-600">
                  -¥{formatCurrency(totals.discountAmount)}
                </span>
              </div>
            </div>
          )}

          {/* Taxes */}
          {showTaxes && totals.taxAmount && totals.taxAmount > 0 && (
            <div className="mb-4">
              <div className="flex justify-between text-sm">
                <span className="text-gray-700">Tax (10%)</span>
                <span className="font-medium text-gray-900">
                  ¥{formatCurrency(totals.taxAmount)}
                </span>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Simple Item List for simple variant */}
      {variant === "simple" && (
        <div className="mb-6 space-y-2">
          {items.map((item, index) => (
            <div key={index} className="flex justify-between text-sm">
              <span className="text-gray-700">{String(item.name)}</span>
              <span className="font-medium">
                ¥
                {formatCurrency(
                  Number(
                    item.billingCycle === "Monthly"
                      ? item.monthlyPrice || item.unitPrice || 0
                      : item.oneTimePrice || item.unitPrice || 0
                  )
                )}
                {item.billingCycle === "Monthly" ? "/mo" : " one-time"}
              </span>
            </div>
          ))}
        </div>
      )}

      {/* Totals */}
      <div className="mb-6 pt-4 border-t border-gray-300">
        <div className="space-y-2">
          <div className="flex justify-between text-lg font-semibold">
            <span className="text-gray-900">Monthly Total:</span>
            <span className="text-blue-600">{formatCurrency(totals.monthlyTotal)}</span>
          </div>

          {totals.oneTimeTotal > 0 && (
            <div className="flex justify-between text-lg font-semibold">
              <span className="text-gray-900">One-time Total:</span>
              <span className="text-orange-600">{formatCurrency(totals.oneTimeTotal)}</span>
            </div>
          )}

          {totals.annualTotal && (
            <div className="flex justify-between text-sm text-gray-600">
              <span>Annual Total:</span>
              <span>{formatCurrency(totals.annualTotal)}</span>
            </div>
          )}
        </div>
      </div>

      {/* Info Lines */}
      {infoLines.length > 0 && (
        <div className="mb-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
          <div className="flex items-start gap-2">
            <InformationCircleIcon className="h-5 w-5 text-blue-500 flex-shrink-0 mt-0.5" />
            <div className="space-y-1">
              {infoLines.map((line, index) => (
                <p key={index} className="text-sm text-blue-700">
                  {line}
                </p>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Disclaimers */}
      {disclaimers.length > 0 && (
        <div className="mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200">
          <div className="space-y-2">
            {disclaimers.map((disclaimer, index) => (
              <p key={index} className="text-xs text-gray-600">
                {disclaimer}
              </p>
            ))}
          </div>
        </div>
      )}

      {/* Custom Content */}
      {children && <div className="mb-6">{children}</div>}

      {/* Actions */}
      {showActions && (
        <div className="flex gap-4">
          {backUrl ? (
            <Button
              variant="outline"
              className="flex-1 group"
              disabled={disabled || loading}
              leftIcon={<ArrowLeftIcon className="w-4 h-4" />}
              onClick={() => {
                if (disabled || loading) return;
                router.push(backUrl);
              }}
            >
              {backLabel}
            </Button>
          ) : onBack ? (
            <Button
              onClick={onBack}
              variant="outline"
              className="flex-1 group"
              disabled={disabled || loading}
              leftIcon={<ArrowLeftIcon className="w-4 h-4" />}
            >
              {backLabel}
            </Button>
          ) : null}

          {onContinue && (
            <Button
              onClick={onContinue}
              className="flex-1 group"
              disabled={disabled || loading}
              loading={loading}
              loadingText="Processing..."
              rightIcon={!loading ? <ArrowRightIcon className="w-4 h-4" /> : undefined}
            >
              {continueLabel}
            </Button>
          )}
        </div>
      )}

      {/* Footer Content */}
      {footerContent && <div className="mt-6 pt-4 border-t border-gray-200">{footerContent}</div>}
    </AnimatedCard>
  );
}
