import React, { useState } from "react";
import { clsx } from "clsx";

interface PricingFeature {
  id: string;
  name: string;
  description?: string;
  highlight?: boolean;
}

interface PricingPlan {
  id: string;
  name: string;
  description: string;
  price: {
    monthly: number;
    yearly: number;
    currency: string;
  };
  features: (string | PricingFeature)[];
  popular?: boolean;
  badge?: string;
  ctaText?: string;
  ctaUrl?: string;
  customCta?: boolean;
  trialDays?: number;
  setupFee?: number;
  discountPercentage?: number;
}

interface PlusPricingProps {
  title?: string;
  description?: string;
  plans?: PricingPlan[];
  billingPeriod?: "monthly" | "yearly";
  showBillingToggle?: boolean;
  showComparison?: boolean;
  showTrialInfo?: boolean;
  layout?: "horizontal" | "vertical";
  maxFeaturedPlans?: number;
  className?: string;
  theme?: {
    primaryColor?: string;
    secondaryColor?: string;
    accentColor?: string;
    fontFamily?: string;
  };
}

const defaultPlans: PricingPlan[] = [
  {
    id: "starter",
    name: "스타터",
    description: "개인 사용자나 소규모 프로젝트에 적합",
    price: {
      monthly: 9900,
      yearly: 99000,
      currency: "KRW",
    },
    features: [
      "월 10,000 API 호출",
      "기본 대시보드",
      "이메일 지원",
      "SSL 인증서",
      "99.9% 업타임 보장",
    ],
    trialDays: 14,
    ctaText: "무료 체험 시작",
    ctaUrl: "/signup?plan=starter",
  },
  {
    id: "professional",
    name: "프로페셔널",
    description: "성장하는 비즈니스를 위한 완벽한 솔루션",
    price: {
      monthly: 29900,
      yearly: 299000,
      currency: "KRW",
    },
    features: [
      "월 100,000 API 호출",
      "고급 분석 대시보드",
      "우선 이메일 지원",
      "API 키 관리",
      "워크플로우 자동화",
      "팀 협업 도구",
      "데이터 백업",
    ],
    popular: true,
    badge: "가장 인기",
    trialDays: 30,
    discountPercentage: 17,
    ctaText: "지금 시작하기",
    ctaUrl: "/signup?plan=professional",
  },
  {
    id: "enterprise",
    name: "엔터프라이즈",
    description: "대규모 조직을 위한 맞춤형 솔루션",
    price: {
      monthly: 99900,
      yearly: 999000,
      currency: "KRW",
    },
    features: [
      "무제한 API 호출",
      "전용 계정 관리자",
      "24/7 전화 지원",
      "SSO 통합",
      "고급 보안",
      "맞춤형 대시보드",
      "온프레미스 배포",
      "SLA 보장",
      {
        id: "custom-integration",
        name: "맞춤형 통합",
        description: "기존 시스템과의 완벽한 연동",
        highlight: true,
      },
      {
        id: "dedicated-support",
        name: "전담 기술 지원팀",
        description: "전문 엔지니어의 1:1 지원",
        highlight: true,
      },
    ],
    badge: "최고 가치",
    trialDays: 30,
    setupFee: 500000,
    customCta: true,
    ctaText: "영업팀 문의",
    ctaUrl: "/contact?plan=enterprise",
  },
];

const formatPrice = (price: number, currency: string): string => {
  return new Intl.NumberFormat("ko-KR", {
    style: "currency",
    currency: currency === "KRW" ? "KRW" : "USD",
    minimumFractionDigits: 0,
  }).format(price);
};

const calculateYearlyDiscount = (monthly: number, yearly: number): number => {
  return Math.round(((monthly * 12 - yearly) / (monthly * 12)) * 100);
};

export function PlusPricing({
  title = "요금제",
  description = "비즈니스에 맞는 완벽한 플랜을 선택하세요.",
  plans = defaultPlans,
  billingPeriod = "monthly",
  showBillingToggle = true,
  showComparison = true,
  showTrialInfo = true,
  layout = "horizontal",
  maxFeaturedPlans = 3,
  className,
  theme = {},
}: PlusPricingProps) {
  const [selectedBilling, setSelectedBilling] = useState<"monthly" | "yearly">(
    billingPeriod
  );
  const [showFullComparison, setShowFullComparison] = useState(false);

  const featuredPlans = plans.slice(0, maxFeaturedPlans);
  const isYearlySelected = selectedBilling === "yearly";

  const PricingCard = ({
    plan,
    featured = false,
  }: {
    plan: PricingPlan;
    featured?: boolean;
  }) => {
    const currentPrice = isYearlySelected
      ? plan.price.yearly
      : plan.price.monthly;
    const yearlyDiscount = calculateYearlyDiscount(
      plan.price.monthly,
      plan.price.yearly
    );

    return (
      <div
        className={clsx(
          "relative bg-white rounded-2xl shadow-lg border-2 transition-all duration-300 hover:shadow-xl",
          plan.popular && "border-blue-500 scale-105",
          !plan.popular && "border-gray-200",
          featured && "lg:scale-110"
        )}
        style={{ fontFamily: theme.fontFamily }}
      >
        {/* Popular Badge */}
        {plan.popular && (
          <div
            className="absolute -top-4 left-1/2 transform -translate-x-1/2 px-4 py-1 rounded-full text-white text-sm font-semibold"
            style={{ backgroundColor: theme.primaryColor || "#3b82f6" }}
          >
            {plan.badge || "인기"}
          </div>
        )}

        {/* Badge */}
        {plan.badge && !plan.popular && (
          <div className="absolute -top-4 left-1/2 transform -translate-x-1/2 px-4 py-1 bg-gray-800 text-white rounded-full text-sm font-semibold">
            {plan.badge}
          </div>
        )}

        <div className="p-8">
          {/* Header */}
          <div className="text-center mb-8">
            <h3 className="text-2xl font-bold mb-2">{plan.name}</h3>
            <p className="text-gray-600 mb-4">{plan.description}</p>

            {/* Price */}
            <div className="mb-4">
              <div className="flex items-baseline justify-center">
                <span
                  className="text-4xl font-bold"
                  style={{ color: theme.primaryColor || "#1f2937" }}
                >
                  {formatPrice(currentPrice, plan.price.currency)}
                </span>
                <span className="text-gray-500 ml-2">
                  /{isYearlySelected ? "년" : "월"}
                </span>
              </div>

              {/* Yearly Discount */}
              {isYearlySelected && yearlyDiscount > 0 && (
                <div className="text-sm text-green-600 font-semibold mt-2">
                  월간 결제 대비 {yearlyDiscount}% 할인
                </div>
              )}

              {/* Setup Fee */}
              {plan.setupFee && (
                <div className="text-sm text-gray-500 mt-1">
                  초기 설정비: {formatPrice(plan.setupFee, plan.price.currency)}
                </div>
              )}
            </div>

            {/* Trial Info */}
            {showTrialInfo && plan.trialDays && (
              <div
                className="inline-block px-3 py-1 rounded-full text-sm font-semibold"
                style={{
                  backgroundColor: theme.accentColor || "#f0f9ff",
                  color: theme.primaryColor || "#0369a1",
                }}
              >
                {plan.trialDays}일 무료 체험
              </div>
            )}
          </div>

          {/* Features */}
          <div className="mb-8">
            <ul className="space-y-3">
              {plan.features.map((feature, index) => {
                const isFeatureObject = typeof feature === "object";
                const featureName = isFeatureObject ? feature.name : feature;
                const featureDesc = isFeatureObject
                  ? feature.description
                  : undefined;
                const isHighlight = isFeatureObject ? feature.highlight : false;

                return (
                  <li key={index} className="flex items-start">
                    <span
                      className={clsx(
                        "flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center mr-3 mt-0.5",
                        isHighlight
                          ? "bg-yellow-100 text-yellow-600"
                          : "bg-green-100 text-green-600"
                      )}
                    >
                      {isHighlight ? "⭐" : "✓"}
                    </span>
                    <div>
                      <span
                        className={clsx(
                          "text-gray-700",
                          isHighlight && "font-semibold"
                        )}
                      >
                        {featureName}
                      </span>
                      {featureDesc && (
                        <p className="text-sm text-gray-500 mt-1">
                          {featureDesc}
                        </p>
                      )}
                    </div>
                  </li>
                );
              })}
            </ul>
          </div>

          {/* CTA Button */}
          <div>
            <a
              href={plan.ctaUrl}
              className={clsx(
                "w-full inline-flex justify-center py-3 px-6 border border-transparent rounded-lg text-base font-medium transition-colors duration-200",
                plan.popular
                  ? "text-white hover:opacity-90"
                  : plan.customCta
                  ? "border-gray-300 text-gray-700 hover:bg-gray-50"
                  : "text-gray-700 hover:bg-gray-50"
              )}
              style={{
                backgroundColor: plan.popular
                  ? theme.primaryColor || "#3b82f6"
                  : plan.customCta
                  ? "transparent"
                  : theme.accentColor || "#f8fafc",
                borderColor: plan.customCta
                  ? theme.primaryColor || "#d1d5db"
                  : "transparent",
              }}
            >
              {plan.ctaText || "시작하기"}
            </a>
          </div>
        </div>
      </div>
    );
  };

  return (
    <section
      className={clsx("py-16 bg-gray-50", className)}
      style={{ fontFamily: theme.fontFamily }}
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="text-center mb-12">
          <h2
            className="text-3xl font-bold mb-4"
            style={{ color: theme.primaryColor || "#1f2937" }}
          >
            {title}
          </h2>
          <p className="text-xl text-gray-600 max-w-3xl mx-auto mb-8">
            {description}
          </p>

          {/* Billing Toggle */}
          {showBillingToggle && (
            <div className="flex items-center justify-center mb-8">
              <span
                className={clsx(
                  "mr-3",
                  !isYearlySelected ? "font-semibold" : "text-gray-500"
                )}
              >
                월간 결제
              </span>
              <button
                onClick={() =>
                  setSelectedBilling(isYearlySelected ? "monthly" : "yearly")
                }
                className={clsx(
                  "relative inline-flex h-6 w-11 items-center rounded-full transition-colors",
                  isYearlySelected ? "bg-blue-600" : "bg-gray-300"
                )}
              >
                <span
                  className={clsx(
                    "inline-block h-4 w-4 rounded-full bg-white transition-transform",
                    isYearlySelected ? "translate-x-6" : "translate-x-1"
                  )}
                />
              </button>
              <span
                className={clsx(
                  "ml-3 flex items-center",
                  isYearlySelected ? "font-semibold" : "text-gray-500"
                )}
              >
                연간 결제
                <span className="ml-2 px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                  최대 17% 할인
                </span>
              </span>
            </div>
          )}
        </div>

        {/* Pricing Cards */}
        <div
          className={clsx(
            "grid gap-8 mb-12",
            layout === "horizontal"
              ? "grid-cols-1 md:grid-cols-2 lg:grid-cols-3"
              : "grid-cols-1 max-w-lg mx-auto"
          )}
        >
          {featuredPlans.map((plan) => (
            <PricingCard
              key={plan.id}
              plan={plan}
              featured={layout === "horizontal" && plan.popular}
            />
          ))}
        </div>

        {/* Comparison Table */}
        {showComparison && (
          <div className="bg-white rounded-lg shadow-lg overflow-hidden">
            <div className="px-6 py-4 border-b border-gray-200">
              <h3 className="text-lg font-semibold">상세 기능 비교</h3>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="bg-gray-50">
                    <th className="px-6 py-3 text-left text-sm font-medium text-gray-500">
                      기능
                    </th>
                    {featuredPlans.map((plan) => (
                      <th
                        key={plan.id}
                        className="px-6 py-3 text-center text-sm font-medium text-gray-500"
                      >
                        {plan.name}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {/* Extract all unique features */}
                  {Array.from(
                    new Set(
                      featuredPlans.flatMap((plan) =>
                        plan.features.map((f) =>
                          typeof f === "string" ? f : f.name
                        )
                      )
                    )
                  )
                    .slice(0, showFullComparison ? undefined : 8)
                    .map((featureName) => (
                      <tr key={featureName}>
                        <td className="px-6 py-4 text-sm text-gray-900">
                          {featureName}
                        </td>
                        {featuredPlans.map((plan) => {
                          const hasFeature = plan.features.some((f) =>
                            typeof f === "string"
                              ? f === featureName
                              : f.name === featureName
                          );
                          return (
                            <td key={plan.id} className="px-6 py-4 text-center">
                              {hasFeature ? (
                                <span className="text-green-600">✓</span>
                              ) : (
                                <span className="text-gray-300">-</span>
                              )}
                            </td>
                          );
                        })}
                      </tr>
                    ))}
                </tbody>
              </table>
            </div>

            {!showFullComparison && (
              <div className="px-6 py-4 border-t border-gray-200 text-center">
                <button
                  onClick={() => setShowFullComparison(true)}
                  className="text-blue-600 hover:text-blue-800 text-sm font-medium"
                >
                  전체 기능 비교 보기
                </button>
              </div>
            )}
          </div>
        )}

        {/* Additional Info */}
        <div className="mt-12 text-center text-gray-500 text-sm">
          <p>모든 요금제는 언제든지 변경하거나 취소할 수 있습니다.</p>
          <p className="mt-1">
            궁금한 점이 있으시면{" "}
            <a href="/contact" className="text-blue-600 hover:text-blue-800">
              영업팀에 문의
            </a>
            해 주세요.
          </p>
        </div>
      </div>
    </section>
  );
}
