/**
 * Public Pricing Page
 * File: src/pages/public/Pricing.tsx
 * FRONTEND: PUBLIC PRICING PAGE
 */
import React, { useEffect, useState } from 'react';
import { useSubscriptionApi } from '../../hooks/useSubscriptionApi';
import { SubscriptionPlan, PlanFeature } from '../../types/subscription';

export default function Pricing() {
  const api = useSubscriptionApi();
  const [plans, setPlans] = useState<SubscriptionPlan[]>([]);
  const [billingCycle, setBillingCycle] = useState<'monthly' | 'annual'>('monthly');

  useEffect(() => {
    api.getPublicPlans().then((data) => setPlans(data || []));
  }, []);

  const formatPrice = (plan: SubscriptionPlan) => {
    if (plan.plan_type === 'trial') {
      return `${plan.currency} ${Number(plan.activation_fee).toLocaleString()} activation`;
    }
    if (plan.plan_type === 'custom') return 'Custom';
    const price = billingCycle === 'annual' && plan.annual_price
      ? Number(plan.annual_price)
      : Number(plan.price);
    return `${plan.currency} ${price.toLocaleString()}`;
  };

  const renderFeature = (f: PlanFeature) => {
    if (f.is_unlimited || f.value_type === 'unlimited') return 'Unlimited';
    if (f.value_type === 'boolean') return f.is_enabled ? '✓ Included' : '—';
    if (f.value_type === 'numeric') return f.numeric_limit?.toString() ?? '—';
    if (f.value_type === 'level') return f.level ?? '—';
    if (f.value_type === 'text') return f.text_value ?? '—';
    if (f.value_type === 'custom') return f.text_value ?? 'Custom';
    return '—';
  };

  return (
    <div className="py-12 px-4 max-w-7xl mx-auto">
      <div className="text-center mb-12">
        <h1 className="text-3xl font-bold mb-4">Choose Your Plan</h1>
        <p className="text-gray-600 mb-6">Select the perfect plan for your business</p>
        <div className="inline-flex bg-gray-100 rounded-lg p-1">
          <button
            onClick={() => setBillingCycle('monthly')}
            className={`px-4 py-2 rounded-md text-sm font-medium ${billingCycle === 'monthly' ? 'bg-white shadow text-blue-600' : 'text-gray-500'}`}
          >
            Monthly
          </button>
          <button
            onClick={() => setBillingCycle('annual')}
            className={`px-4 py-2 rounded-md text-sm font-medium ${billingCycle === 'annual' ? 'bg-white shadow text-blue-600' : 'text-gray-500'}`}
          >
            Annual
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6">
        {plans.map((plan) => (
          <div key={plan.id} className={`border rounded-xl p-6 flex flex-col ${plan.is_popular ? 'ring-2 ring-blue-500 shadow-lg' : 'shadow-sm'}`}>
            {plan.is_popular && (
              <span className="bg-blue-500 text-white text-xs font-bold px-3 py-1 rounded-full self-start mb-3">
                MOST POPULAR
              </span>
            )}
            <h3 className="text-xl font-bold mb-1">{plan.name}</h3>
            <p className="text-sm text-gray-500 mb-4">{plan.subtitle}</p>

            <div className="mb-6">
              <span className="text-3xl font-bold">{formatPrice(plan)}</span>
              {plan.plan_type === 'paid' && (
                <span className="text-gray-500 text-sm">/{billingCycle}</span>
              )}
            </div>

            <ul className="space-y-3 mb-6 flex-1">
              {plan.features.map((f) => (
                <li key={f.id} className="flex justify-between text-sm">
                  <span className="text-gray-600">{f.feature_name}</span>
                  <span className="font-medium">{renderFeature(f)}</span>
                </li>
              ))}
            </ul>

            <button className={`w-full py-2 rounded-lg font-medium ${plan.is_popular ? 'bg-blue-600 text-white hover:bg-blue-700' : 'bg-gray-100 text-gray-800 hover:bg-gray-200'}`}>
              {plan.cta_label || 'Get Started'}
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}