import React, { useState, useEffect, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import {
  CheckIcon, XMarkIcon, SparklesIcon, UserIcon,
  CreditCardIcon, ClockIcon, ArrowPathIcon, GiftIcon,
} from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { SubscriptionPlan, MySubscriptionData, SubscriptionPeriod } from '../types';
import { usePaymentConfig } from '../hooks/usePaymentConfig';
import { formatRial, formatNumber } from '../lib/utils';
import Modal from '../components/ui/Modal';
import SettingsLayout from '../components/layout/SettingsLayout';

// ── Constants ─────────────────────────────────────────────────────────────

export const PLAN_FEATURE_LABELS: Record<string, string> = {
  patient_records: 'پرونده بیمار',
  services:        'مدیریت سرویس‌ها',
  sms_panel:       'پنل پیامک',
};

/** The plan highlighted as "most popular" in the UI (no backend flag exists). */
const POPULAR_PLAN_NAME = 'basic';

const PLAN_META: Record<string, { label: string; desc: string; tint: string }> = {
  free:         { label: 'رایگان',  desc: 'مناسب برای شروع کار',              tint: 'var(--surface-2)' },
  basic:        { label: 'پایه',    desc: 'مناسب برای مطب‌های کوچک و متوسط',   tint: 'var(--primary-soft)' },
  professional: { label: 'حرفه‌ای', desc: 'مناسب برای کلینیک‌های بزرگ',        tint: 'var(--violet-bg)' },
};

export const planMetaOf = (name: string) => PLAN_META[name] ?? PLAN_META.free;

// ── Main Page ─────────────────────────────────────────────────────────────

export default function SubscriptionPage() {
  const qc = useQueryClient();
  const [purchaseTarget, setPurchaseTarget] = useState<{ period: SubscriptionPeriod; planName: string } | null>(null);
  const [selectedGateway, setSelectedGateway] = useState<string>('');

  const { data: plansData, isLoading: plansLoading } = useQuery<ApiResponse<SubscriptionPlan[]>>({
    queryKey: ['subscription-plans'],
    queryFn: () => api.get('/api/v1/subscription/plans'),
  });

  const { data: myData, isLoading: myLoading } = useQuery<ApiResponse<MySubscriptionData>>({
    queryKey: ['subscription-my'],
    queryFn: () => api.get('/api/v1/subscription/my'),
  });

  const { isTestMode, gateways } = usePaymentConfig();

  useEffect(() => {
    if (gateways.length > 0 && !gateways.some((g) => g.name === selectedGateway)) {
      setSelectedGateway(gateways[0].name);
    }
  }, [gateways, selectedGateway]);

  // Highest plan first so, under RTL, the top-tier plan sits on the right (Figma order).
  const plans     = [...(plansData?.data ?? [])].sort((a, b) => b.level - a.level);
  const myRaw     = myData?.data;
  const my        = myRaw?.subscription ?? null;
  const usedTrial = myRaw?.used_trial ?? false;

  const trialMutation = useMutation({
    mutationFn: () => api.post('/api/v1/subscription/trial', {}),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['subscription-my'] });
      toast.success('تریال رایگان با موفقیت فعال شد');
    },
    onError: (err: any) => toast.error(err.message),
  });

  const purchaseMutation = useMutation({
    mutationFn: ({ period_uuid, gateway, amount_rials }: { period_uuid: string; gateway: string; amount_rials: number }) =>
      api.post<{ data: { pay_url?: string; redirect_url?: string; payment_url?: string } }>('/api/v1/subscription-payment', {
        period_uuid, gateway, amount_rials,
        // Gateway returns here (with ?payment_uuid&status); the success page reads them.
        frontend_address: `${window.location.origin}/admin/subscription/success`,
      }),
    onSuccess: (res: any) => {
      const url = res?.data?.pay_url ?? res?.data?.redirect_url ?? res?.data?.payment_url;
      if (url) window.location.href = url;
      else toast.error('خطا در دریافت لینک پرداخت');
    },
    onError: (err: any) => toast.error(err.message),
  });

  return (
    <SettingsLayout active="subscription">
      {/* ── Header ── */}
      <div style={{ marginBottom: 20 }}>
        <h1 className="section-title" style={{ marginBottom: 4 }}>انتخاب پلن اشتراک</h1>
        <p style={{ color: 'var(--text-3)', fontSize: 14, margin: 0 }}>
          پلن اشتراک مناسب خود را انتخاب نمایید:
        </p>
      </div>

      {/* ── وضعیت پلن فعلی ── */}
      {!myLoading && <CurrentPlanBanner my={my} />}

      {/* ── کارت‌های پلن ── */}
      {plansLoading ? (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 16 }}>
          {[1, 2, 3].map((i) => (
            <div key={i} className="card" style={{ height: 420 }}>
              <div className="skeleton" style={{ height: '100%', borderRadius: 'var(--r)' }} />
            </div>
          ))}
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 16 }}>
          {plans.map((plan) => (
            <PlanCard
              key={plan.uuid}
              plan={plan}
              currentPlanName={my?.plan.name ?? 'free'}
              currentPlanLevel={my?.plan.level ?? 0}
              currentPlanActive={!!my && (my.days_remaining ?? 0) > 0}
              usedTrial={usedTrial}
              onPurchase={(period) => setPurchaseTarget({ period, planName: plan.name })}
              onTrial={() => trialMutation.mutate()}
              trialPending={trialMutation.isPending}
            />
          ))}
        </div>
      )}

      {/* ── Modal پرداخت (انتخاب درگاه) ── */}
      <Modal
        open={!!purchaseTarget}
        onClose={() => { setPurchaseTarget(null); setSelectedGateway(gateways[0]?.name ?? ''); }}
        title="پرداخت اشتراک"
        size="sm"
      >
        {purchaseTarget && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{
              background: 'var(--surface-2)', borderRadius: 'var(--r-sm)',
              padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <div>
                <div style={{ fontSize: 13, color: 'var(--text-3)', marginBottom: 2 }}>دوره انتخابی</div>
                <div style={{ fontWeight: 700, fontSize: 15 }}>
                  {planMetaOf(purchaseTarget.planName).label} — {purchaseTarget.period.label}
                </div>
                <div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 1 }}>
                  {purchaseTarget.period.duration_months} ماه
                </div>
              </div>
              <div style={{ textAlign: 'left' }}>
                <div style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 2 }}>مبلغ قابل پرداخت</div>
                <div style={{ fontWeight: 800, fontSize: 20, color: 'var(--primary)' }}>
                  {formatRial(purchaseTarget.period.price_rials)}
                </div>
              </div>
            </div>

            {isTestMode ? (
              <div style={{
                background: 'var(--warning-bg)', border: '1px solid var(--warning)',
                borderRadius: 10, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <span style={{ fontSize: 20 }}>⚠️</span>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--warning)' }}>درگاه آزمایشی فعال است</div>
                  <div style={{ fontSize: 12, color: 'var(--warning)', marginTop: 2, opacity: 0.8 }}>پول واقعی کسر نخواهد شد — این تراکنش آزمایشی است</div>
                </div>
              </div>
            ) : gateways.length === 0 ? (
              <div style={{
                background: 'var(--danger-bg)', border: '1px solid var(--danger)',
                borderRadius: 10, padding: '12px 16px', fontSize: 13, color: 'var(--danger)',
              }}>
                در حال حاضر هیچ درگاه پرداخت فعالی وجود ندارد. لطفاً با پشتیبانی تماس بگیرید.
              </div>
            ) : (
              <div>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', marginBottom: 10 }}>
                  انتخاب درگاه پرداخت
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                  {gateways.map((gw) => (
                    <button
                      key={gw.name}
                      onClick={() => setSelectedGateway(gw.name)}
                      style={{
                        padding: '12px 16px', borderRadius: 'var(--r-sm)', cursor: 'pointer',
                        border: `2px solid ${selectedGateway === gw.name ? 'var(--primary)' : 'var(--border)'}`,
                        background: selectedGateway === gw.name ? 'var(--primary-soft)' : 'var(--surface)',
                        color: selectedGateway === gw.name ? 'var(--primary-700)' : 'var(--text-2)',
                        fontWeight: selectedGateway === gw.name ? 700 : 500,
                        fontSize: 13, transition: '.14s', fontFamily: 'inherit',
                        display: 'flex', alignItems: 'center', gap: 8,
                      }}
                    >
                      <CreditCardIcon style={{ width: 17, flexShrink: 0 }} />
                      {gw.label}
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
              <button
                className="btn primary"
                style={{ flex: 1, height: 44 }}
                disabled={purchaseMutation.isPending || (!isTestMode && (gateways.length === 0 || selectedGateway === ''))}
                onClick={() =>
                  purchaseMutation.mutate({ period_uuid: purchaseTarget.period.uuid, gateway: selectedGateway, amount_rials: purchaseTarget.period.price_rials })
                }
              >
                {purchaseMutation.isPending
                  ? 'در حال انتقال...'
                  : `پرداخت ${formatRial(purchaseTarget.period.price_rials)}`}
              </button>
              <button className="btn ghost" style={{ height: 44 }} onClick={() => setPurchaseTarget(null)}>
                انصراف
              </button>
            </div>
          </div>
        )}
      </Modal>
    </SettingsLayout>
  );
}

// ── Current plan banner ─────────────────────────────────────────────────────

function CurrentPlanBanner({ my }: { my: MySubscriptionData['subscription'] }) {
  if (!my) return null;
  const meta     = planMetaOf(my.plan.name);
  const daysLeft = my.days_remaining ?? 0;
  const expiring = daysLeft > 0 && daysLeft <= 7;

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap',
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 'var(--r-lg)', padding: '14px 18px', marginBottom: 20,
    }}>
      <div style={{ flex: 1, minWidth: 180 }}>
        <div style={{ fontSize: 13, color: 'var(--text-3)', marginBottom: 2 }}>
          پلن فعلی شما: <b style={{ color: 'var(--text)' }}>{meta.label}</b>
          {my.is_trial && <span className="badge amber" style={{ marginRight: 8, fontSize: 11 }}><span className="bdot" />تریال</span>}
        </div>
        {daysLeft > 0 ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: expiring ? 'var(--danger)' : 'var(--success)', fontWeight: 600 }}>
            <ClockIcon style={{ width: 14, flexShrink: 0 }} />
            {formatNumber(daysLeft)} روز تا پایان اشتراک
          </div>
        ) : (
          <div style={{ fontSize: 13, color: 'var(--text-3)' }}>اشتراک فعالی ندارید</div>
        )}
      </div>
      <Link to="/admin/my-financial" className="btn ghost sm" style={{ flexShrink: 0 }}>
        مشاهده فاکتور
      </Link>
    </div>
  );
}

// ── PlanCard ──────────────────────────────────────────────────────────────

function PlanCard({
  plan, currentPlanName, currentPlanLevel, currentPlanActive,
  usedTrial, onPurchase, onTrial, trialPending,
}: {
  plan: SubscriptionPlan;
  currentPlanName: string;
  currentPlanLevel: number;
  currentPlanActive: boolean;
  usedTrial: boolean;
  onPurchase: (period: SubscriptionPeriod) => void;
  onTrial: () => void;
  trialPending: boolean;
}) {
  const meta        = planMetaOf(plan.name);
  const isCurrent   = plan.name === currentPlanName;
  const isPopular   = plan.name === POPULAR_PLAN_NAME;
  const isDowngrade = currentPlanActive && (plan.level ?? 0) < currentPlanLevel;
  const paidPeriods = useMemo(
    () => [...plan.periods].filter((p) => !p.is_trial).sort((a, b) => a.duration_months - b.duration_months),
    [plan.periods],
  );
  const trialPeriod = plan.periods.find((p) => p.is_trial);

  // Default to the longest (best-value) period, matching the Figma default.
  const [selectedUuid, setSelectedUuid] = useState<string>('');
  useEffect(() => {
    if (paidPeriods.length > 0 && !paidPeriods.some((p) => p.uuid === selectedUuid)) {
      setSelectedUuid(paidPeriods[paidPeriods.length - 1].uuid);
    }
  }, [paidPeriods, selectedUuid]);
  const selectedPeriod = paidPeriods.find((p) => p.uuid === selectedUuid) ?? paidPeriods[0];

  const accent = isPopular ? 'var(--primary)' : 'var(--border-2)';

  return (
    <div style={{
      background: 'var(--surface)',
      border: `${isPopular || isCurrent ? '2px' : '1.5px'} solid ${isPopular ? 'var(--primary)' : isCurrent ? 'var(--primary)' : 'var(--border)'}`,
      borderRadius: 'var(--r-lg)',
      display: 'flex', flexDirection: 'column',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* بج محبوب‌ترین */}
      {isPopular && (
        <span style={{
          position: 'absolute', top: 14, left: 14, zIndex: 1,
          background: 'var(--primary)', color: '#fff',
          fontSize: 11, fontWeight: 700, padding: '4px 10px',
          borderRadius: 999, display: 'inline-flex', alignItems: 'center', gap: 5,
        }}>
          <SparklesIcon style={{ width: 13, height: 13 }} />
          محبوب‌ترین
        </span>
      )}

      {/* سربرگ */}
      <div style={{ padding: '20px 20px 16px', background: meta.tint }}>
        <div style={{ fontWeight: 800, fontSize: 20, color: 'var(--text)', marginBottom: 4 }}>
          پلن {meta.label}
        </div>
        <div style={{ fontSize: 13, color: 'var(--text-2)', marginBottom: 12 }}>{meta.desc}</div>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 5,
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 999, padding: '4px 12px', fontSize: 12.5,
        }}>
          <UserIcon style={{ width: 14, color: 'var(--text-3)' }} />
          <span style={{ fontWeight: 700, color: 'var(--text)' }}>{formatNumber(plan.max_secretaries)}</span>
          <span style={{ color: 'var(--text-3)' }}>منشی</span>
        </div>
      </div>

      <div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 14, flex: 1 }}>
        {/* توگل دوره */}
        {paidPeriods.length > 1 && (
          <div role="tablist" aria-label="دوره اشتراک" style={{
            display: 'grid', gridTemplateColumns: `repeat(${paidPeriods.length}, 1fr)`, gap: 4,
            background: 'var(--surface-2)', border: '1px solid var(--border)',
            borderRadius: 'var(--r-sm)', padding: 4,
          }}>
            {paidPeriods.map((p) => {
              const on = p.uuid === selectedPeriod?.uuid;
              return (
                <button
                  key={p.uuid} role="tab" aria-selected={on}
                  onClick={() => setSelectedUuid(p.uuid)}
                  style={{
                    padding: '7px 6px', borderRadius: 'var(--r-xs)', border: 'none', cursor: 'pointer',
                    fontFamily: 'inherit', fontSize: 12.5, fontWeight: on ? 700 : 500, transition: '.14s',
                    background: on ? 'var(--primary)' : 'transparent',
                    color: on ? '#fff' : 'var(--text-2)',
                  }}
                >
                  {p.label}
                </button>
              );
            })}
          </div>
        )}

        {/* قیمت */}
        <div>
          {selectedPeriod ? (
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
              <span style={{ fontSize: 13, color: 'var(--text-3)' }}>قیمت:</span>
              <span style={{ fontWeight: 800, fontSize: 20, color: 'var(--text)' }}>
                {formatRial(selectedPeriod.price_rials)}
              </span>
            </div>
          ) : (
            <div style={{ fontWeight: 800, fontSize: 18, color: 'var(--success)' }}>رایگان</div>
          )}
        </div>

        {/* امکانات */}
        <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {Object.entries(plan.features).map(([key, enabled]) => (
            <li key={key} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5 }}>
              <span style={{
                width: 20, height: 20, borderRadius: '50%', flexShrink: 0,
                display: 'grid', placeItems: 'center',
                background: enabled ? 'var(--success-bg)' : 'var(--surface-3)',
              }}>
                {enabled
                  ? <CheckIcon style={{ width: 12, color: 'var(--success)' }} />
                  : <XMarkIcon style={{ width: 11, color: 'var(--text-3)' }} />}
              </span>
              <span style={{ color: enabled ? 'var(--text)' : 'var(--text-3)' }}>
                {PLAN_FEATURE_LABELS[key] ?? key}
              </span>
            </li>
          ))}
        </ul>

        {/* تریال */}
        {trialPeriod && !usedTrial && plan.level > 0 && !isDowngrade && (
          <div style={{
            padding: '10px 12px', borderRadius: 'var(--r-sm)',
            background: 'var(--accent-bg)',
            border: '1px dashed color-mix(in oklch, var(--accent) 45%, transparent)',
            fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <GiftIcon style={{ width: 16, color: 'var(--accent)', flexShrink: 0 }} />
            <span style={{ color: 'var(--text-2)' }}>
              تریال <b>{formatNumber(trialPeriod.duration_months)} ماهه</b> رایگان
            </span>
            <button
              onClick={onTrial} disabled={trialPending}
              style={{
                marginRight: 'auto', background: 'none', border: 'none', cursor: 'pointer',
                color: 'var(--accent)', fontWeight: 700, fontSize: 12.5, fontFamily: 'inherit',
              }}
            >
              {trialPending
                ? <ArrowPathIcon style={{ width: 14, animation: 'spin 1s linear infinite' }} />
                : 'فعال سازی'}
            </button>
          </div>
        )}
      </div>

      {/* دکمه خرید */}
      <div style={{ padding: '0 20px 20px' }}>
        {isDowngrade ? (
          <button className="btn" style={{ width: '100%', height: 44, opacity: 0.6, cursor: 'not-allowed' }} disabled>
            تا پایان اشتراک فعلی قابل انتخاب نیست
          </button>
        ) : selectedPeriod ? (
          <button
            className={isPopular ? 'btn primary' : 'btn'}
            style={{
              width: '100%', height: 44, fontWeight: 700,
              ...(isPopular ? {} : { border: '1.5px solid var(--primary)', color: 'var(--primary)', background: 'var(--surface)' }),
            }}
            onClick={() => onPurchase(selectedPeriod)}
          >
            {isCurrent ? 'تمدید اشتراک' : 'خرید اشتراک'}
          </button>
        ) : (
          <button className="btn" style={{ width: '100%', height: 44, cursor: 'default' }} disabled>
            {isCurrent ? 'پلن فعلی شما' : 'رایگان'}
          </button>
        )}
      </div>
    </div>
  );
}
