/**
 * Super Admin Subscription Plan Manager
 * File: src/pages/admin/SubscriptionPlans.tsx
 * frontend/src/pages/admin/SubscriptionPlans.tsx
 */
import React, { useEffect, useState } from 'react';
import { useSubscriptionApi } from '../../hooks/useSubscriptionApi';
import { SubscriptionPlan, PlanFeature, PlanStatus } from '../../types/subscription';

export default function SubscriptionPlans() {
  const api = useSubscriptionApi();
  const [plans, setPlans] = useState<SubscriptionPlan[]>([]);
  const [editing, setEditing] = useState<SubscriptionPlan | null>(null);
  const [showForm, setShowForm] = useState(false);

  useEffect(() => {
    loadPlans();
  }, []);

  const loadPlans = async () => {
    const data = await api.getPlans(true);
    setPlans(data.items || []);
  };

  const handleToggleStatus = async (plan: SubscriptionPlan, newStatus: PlanStatus) => {
    await api.togglePlanStatus(plan.id, newStatus, 'Super Admin toggle');
    loadPlans();
  };

  const formatPrice = (price: number, currency: string) => {
    if (price === 0) return 'Free';
    return `${currency} ${price.toLocaleString()}`;
  };

  const renderFeatureValue = (f: PlanFeature) => {
    if (f.is_unlimited || f.value_type === 'unlimited') return 'Unlimited';
    if (f.value_type === 'boolean') return f.is_enabled ? '✓' : '—';
    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="p-6 max-w-7xl mx-auto">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">Subscription Plans</h1>
        <button
          onClick={() => { setEditing(null); setShowForm(true); }}
          className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
        >
          + Create Plan
        </button>
      </div>

      {api.error && (
        <div className="bg-red-100 text-red-700 p-3 rounded mb-4">{api.error}</div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {plans.map((plan) => (
          <div key={plan.id} className={`border rounded-lg p-5 shadow-sm ${plan.is_popular ? 'ring-2 ring-yellow-400' : ''}`}>
            <div className="flex justify-between items-start mb-2">
              <div>
                <h3 className="text-lg font-semibold">{plan.name}</h3>
                <p className="text-sm text-gray-500">{plan.subtitle}</p>
              </div>
              {plan.is_popular && <span className="bg-yellow-100 text-yellow-800 text-xs px-2 py-1 rounded">Popular</span>}
            </div>

            <div className="mb-4">
              <span className="text-2xl font-bold">{formatPrice(Number(plan.price), plan.currency)}</span>
              <span className="text-gray-500 text-sm"> / {plan.billing_cycle}</span>
              {plan.activation_fee > 0 && (
                <div className="text-xs text-gray-500 mt-1">Activation: {formatPrice(Number(plan.activation_fee), plan.currency)}</div>
              )}
            </div>

            <div className="space-y-2 mb-4">
              {plan.features.map((f) => (
                <div key={f.id} className="flex justify-between text-sm">
                  <span className="text-gray-600">{f.feature_name}</span>
                  <span className="font-medium">{renderFeatureValue(f)}</span>
                </div>
              ))}
            </div>

            <div className="flex gap-2 mt-4">
              <button
                onClick={() => { setEditing(plan); setShowForm(true); }}
                className="flex-1 bg-gray-100 text-gray-700 py-2 rounded hover:bg-gray-200 text-sm"
              >
                Edit
              </button>
              {plan.status === 'active' ? (
                <button
                  onClick={() => handleToggleStatus(plan, 'inactive')}
                  className="flex-1 bg-orange-100 text-orange-700 py-2 rounded hover:bg-orange-200 text-sm"
                >
                  Deactivate
                </button>
              ) : (
                <button
                  onClick={() => handleToggleStatus(plan, 'active')}
                  className="flex-1 bg-green-100 text-green-700 py-2 rounded hover:bg-green-200 text-sm"
                >
                  Activate
                </button>
              )}
            </div>
          </div>
        ))}
      </div>

      {showForm && (
        <PlanForm
          plan={editing}
          onClose={() => setShowForm(false)}
          onSaved={loadPlans}
        />
      )}
    </div>
  );
}

// Inline simplified form component
function PlanForm({ plan, onClose, onSaved }: { plan: SubscriptionPlan | null; onClose: () => void; onSaved: () => void }) {
  const api = useSubscriptionApi();
  const [form, setForm] = useState<any>(plan || {
    slug: '', name: '', subtitle: '', description: '', plan_type: 'paid',
    price: 0, currency: 'PKR', billing_cycle: 'monthly', trial_days: 0,
    activation_fee: 0, requires_payment_before_activation: false,
    is_popular: false, status: 'active', display_order: 0, cta_label: 'Get Started',
    features: []
  });

  const save = async () => {
    if (plan) {
      await api.updatePlan(plan.id, form);
    } else {
      await api.createPlan(form);
    }
    onSaved();
    onClose();
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto p-6">
        <h2 className="text-xl font-bold mb-4">{plan ? 'Edit Plan' : 'Create Plan'}</h2>
        <div className="grid grid-cols-2 gap-4 mb-4">
          <input className="border p-2 rounded" placeholder="Slug" value={form.slug} onChange={e => setForm({...form, slug: e.target.value})} />
          <input className="border p-2 rounded" placeholder="Name" value={form.name} onChange={e => setForm({...form, name: e.target.value})} />
          <input className="border p-2 rounded" placeholder="Subtitle" value={form.subtitle} onChange={e => setForm({...form, subtitle: e.target.value})} />
          <input className="border p-2 rounded" placeholder="Price" type="number" value={form.price} onChange={e => setForm({...form, price: Number(e.target.value)})} />
          <select className="border p-2 rounded" value={form.plan_type} onChange={e => setForm({...form, plan_type: e.target.value})}>
            <option value="trial">Trial</option>
            <option value="paid">Paid</option>
            <option value="custom">Custom</option>
            <option value="enterprise">Enterprise</option>
          </select>
          <select className="border p-2 rounded" value={form.billing_cycle} onChange={e => setForm({...form, billing_cycle: e.target.value})}>
            <option value="trial">Trial</option>
            <option value="monthly">Monthly</option>
            <option value="quarterly">Quarterly</option>
            <option value="annual">Annual</option>
            <option value="custom">Custom</option>
          </select>
          <input className="border p-2 rounded" placeholder="Trial Days" type="number" value={form.trial_days} onChange={e => setForm({...form, trial_days: Number(e.target.value)})} />
          <input className="border p-2 rounded" placeholder="Activation Fee" type="number" value={form.activation_fee} onChange={e => setForm({...form, activation_fee: Number(e.target.value)})} />
          <input className="border p-2 rounded" placeholder="Display Order" type="number" value={form.display_order} onChange={e => setForm({...form, display_order: Number(e.target.value)})} />
          <input className="border p-2 rounded" placeholder="CTA Label" value={form.cta_label} onChange={e => setForm({...form, cta_label: e.target.value})} />
        </div>

        <div className="flex gap-4 mb-4">
          <label className="flex items-center gap-2">
            <input type="checkbox" checked={form.is_popular} onChange={e => setForm({...form, is_popular: e.target.checked})} />
            Popular
          </label>
          <label className="flex items-center gap-2">
            <input type="checkbox" checked={form.requires_payment_before_activation} onChange={e => setForm({...form, requires_payment_before_activation: e.target.checked})} />
            Requires Payment Before Activation
          </label>
        </div>

        <div className="flex justify-end gap-3">
          <button onClick={onClose} className="px-4 py-2 border rounded">Cancel</button>
          <button onClick={save} className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
            {api.loading ? 'Saving...' : 'Save Plan'}
          </button>
        </div>
      </div>
    </div>
  );
}