'use client';

import { useEffect, useState } from 'react';
import { apiFetchJson } from '@/lib/auth';
import { PageHeader } from '@/components/school/page-header';

interface PlanDefinition {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  price: number | null;
  currency: string;
  trialDays: number;
  features: string[];
  pricing: {
    perStudent: number | null;
    currency: string;
    yearlyDiscount: number;
  };
}

interface Subscription {
  id: string;
  plan: string;
  status: string;
  billingInterval: string;
  startsAt: string;
  endsAt: string | null;
  planDefinition: {
    id: string;
    name: string;
    price: number | null;
    currency: string;
    features: string[];
  } | null;
  isExpired: boolean;
  daysRemaining: number | null;
  pricing: {
    pricePerStudent: number | null;
    currency: string;
  };
}

const STATUS_LABELS: Record<string, string> = {
  TRIAL: 'Deneme Süresi', ACTIVE: 'Aktif', SUSPENDED: 'Askıda', CANCELLED: 'İptal',
};
const STATUS_COLOR: Record<string, string> = {
  TRIAL: 'bg-amber-100 text-amber-700 border border-amber-200',
  ACTIVE: 'bg-emerald-100 text-emerald-700 border border-emerald-200',
  SUSPENDED: 'bg-red-100 text-red-700 border border-red-200',
  CANCELLED: 'bg-slate-100 text-slate-600 border border-slate-200',
};

function fmt(d: string | null) {
  if (!d) return '—';
  return new Date(d).toLocaleDateString('tr-TR', { day: '2-digit', month: 'long', year: 'numeric' });
}

export default function SchoolSubscriptionPage() {
  const [sub, setSub] = useState<Subscription | null>(null);
  const [plans, setPlans] = useState<PlanDefinition[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedPlan, setSelectedPlan] = useState<string>('');
  const [billingInterval, setBillingInterval] = useState<'MONTHLY' | 'YEARLY'>('MONTHLY');
  const [upgrading, setUpgrading] = useState(false);
  const [toast, setToast] = useState<{ msg: string; type: 'success' | 'error' } | null>(null);

  const showToast = (msg: string, type: 'success' | 'error' = 'success') => {
    setToast({ msg, type });
    setTimeout(() => setToast(null), 4000);
  };

  const load = async () => {
    setLoading(true);
    const [subRes, plansRes] = await Promise.all([
      apiFetchJson<Subscription>('/v1/tenants/me/subscription'),
      apiFetchJson<{ items: PlanDefinition[] }>('/v1/tenants/me/subscription/plans'),
    ]);
    if (subRes.error === null && subRes.data) {
      setSub(subRes.data);
      setBillingInterval((subRes.data.billingInterval as 'MONTHLY' | 'YEARLY') ?? 'MONTHLY');
      setSelectedPlan(subRes.data.planDefinition?.id ?? '');
    }
    if (plansRes.error === null && plansRes.data) setPlans(plansRes.data.items);
    setLoading(false);
  };

  useEffect(() => { load(); }, []);

  const handleUpgrade = async () => {
    if (!selectedPlan) return;
    setUpgrading(true);
    const res = await apiFetchJson<{ subscription: Subscription; payment: { amount: number; currency: string; message: string } }>(
      '/v1/tenants/me/subscription/upgrade',
      {
        method: 'PATCH',
        body: JSON.stringify({ planDefinitionId: selectedPlan, billingInterval }),
      },
    );
    if (res.error === null && res.data) {
      showToast(res.data.payment.message);
      load();
    } else {
      showToast(res.error ?? 'Hata oluştu', 'error');
    }
    setUpgrading(false);
  };

  const chosenPlan = plans.find((p) => p.id === selectedPlan);
  const chosenMonthly = null;
  const chosenAmount = null;

  const currentPlanId = sub?.planDefinition?.id ?? '';
  const isCurrentPlan = selectedPlan === currentPlanId && billingInterval === (sub?.billingInterval ?? 'MONTHLY');

  if (loading) {
    return (
      <div className="space-y-6">
        <PageHeader title="Aboneliğim" description="Abonelik planınızı yönetin" />
        <div className="space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-32 rounded-2xl bg-slate-100 animate-pulse" />
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {toast && (
        <div className={`fixed top-5 right-5 z-50 rounded-xl px-5 py-3.5 text-sm font-medium shadow-xl ${
          toast.type === 'success' ? 'bg-emerald-600 text-white' : 'bg-red-600 text-white'
        }`}>
          {toast.msg}
        </div>
      )}

      <PageHeader title="Aboneliğim" description="Abonelik planınızı görüntüleyin ve yönetin" />

      {/* Mevcut abonelik kartı */}
      {sub && (
        <div className="rounded-2xl bg-gradient-to-br from-violet-600 to-indigo-700 p-6 text-white shadow-lg">
          <div className="flex items-start justify-between">
            <div>
              <div className="text-sm font-medium text-violet-200 mb-1">Mevcut Plan</div>
              <div className="text-2xl font-bold">
                {sub.planDefinition?.name ?? 'Temel Plan'}
              </div>
              <div className="mt-2 flex items-center gap-3">
                <span className={`rounded-full px-3 py-1 text-xs font-semibold ${STATUS_COLOR[sub.status]}`}>
                  {STATUS_LABELS[sub.status] ?? sub.status}
                </span>
                <span className={`rounded-full px-3 py-1 text-xs font-semibold ${
                  sub.billingInterval === 'YEARLY'
                    ? 'bg-violet-500/40 text-violet-100'
                    : 'bg-indigo-500/40 text-indigo-100'
                }`}>
                  {sub.billingInterval === 'YEARLY' ? 'Yıllık ödeme' : 'Aylık ödeme'}
                </span>
              </div>
            </div>
            {sub.pricing.pricePerStudent != null && (
              <div className="text-right">
                <div className="text-2xl font-bold">
                  ₺{sub.pricing.pricePerStudent.toLocaleString('tr-TR')}
                </div>
                <div className="text-sm text-violet-200">/ öğrenci / ay</div>
              </div>
            )}
          </div>

          <div className="mt-6 grid grid-cols-2 gap-4">
            <div className="rounded-xl bg-white/10 p-3">
              <div className="text-xs text-violet-200 mb-1">Başlangıç</div>
              <div className="text-sm font-semibold">{fmt(sub.startsAt)}</div>
            </div>
            <div className="rounded-xl bg-white/10 p-3">
              <div className="text-xs text-violet-200 mb-1">
                {sub.isExpired ? 'Sona Erdi' : 'Bitiş'}
              </div>
              <div className={`text-sm font-semibold ${sub.isExpired ? 'text-red-300' : ''}`}>
                {fmt(sub.endsAt)}
              </div>
              {sub.daysRemaining !== null && !sub.isExpired && (
                <div className="text-xs text-violet-200 mt-0.5">{sub.daysRemaining} gün kaldı</div>
              )}
            </div>
          </div>

          {sub.planDefinition?.features && (sub.planDefinition.features as string[]).length > 0 && (
            <div className="mt-4 flex flex-wrap gap-2">
              {(sub.planDefinition.features as string[]).map((f, i) => (
                <span key={i} className="rounded-full bg-white/15 px-3 py-1 text-xs text-white">
                  ✓ {f}
                </span>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Plan Seçimi */}
      {plans.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold text-slate-900 mb-4">Plan Değiştir / Yenile</h2>

          {/* Ödeme periyodu seçimi */}
          <div className="flex gap-3 mb-6">
            <button
              onClick={() => setBillingInterval('MONTHLY')}
              className={`flex-1 rounded-xl border py-3 text-sm font-medium transition ${
                billingInterval === 'MONTHLY'
                  ? 'border-violet-500 bg-violet-600 text-white shadow-md'
                  : 'border-slate-200 bg-white text-slate-700 hover:bg-slate-50'
              }`}
            >
              Aylık Ödeme
            </button>
            <button
              onClick={() => setBillingInterval('YEARLY')}
              className={`flex-1 rounded-xl border py-3 text-sm font-medium transition ${
                billingInterval === 'YEARLY'
                  ? 'border-violet-500 bg-violet-600 text-white shadow-md'
                  : 'border-slate-200 bg-white text-slate-700 hover:bg-slate-50'
              }`}
            >
              Yıllık Ödeme
              <span className={`ml-2 text-xs font-semibold ${billingInterval === 'YEARLY' ? 'text-emerald-300' : 'text-emerald-600'}`}>
                %15 indirim
              </span>
            </button>
          </div>

          {/* Plan kartları */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {plans.map((plan) => {
              const price = billingInterval === 'YEARLY' ? plan.pricing.yearly : plan.pricing.monthly;
              const perMonth = billingInterval === 'YEARLY' ? plan.pricing.yearlyMonthly : plan.pricing.monthly;
              const isCurrent = plan.id === currentPlanId;
              const isSelected = plan.id === selectedPlan;

              return (
                <button
                  key={plan.id}
                  onClick={() => setSelectedPlan(plan.id)}
                  className={`text-left rounded-2xl border-2 p-5 transition-all ${
                    isSelected
                      ? 'border-violet-500 bg-violet-50 shadow-md'
                      : 'border-slate-200 bg-white hover:border-violet-300 hover:shadow-sm'
                  }`}
                >
                  <div className="flex items-start justify-between mb-3">
                    <div>
                      <div className="font-bold text-slate-900 text-base">{plan.name}</div>
                      {isCurrent && (
                        <span className="inline-block mt-1 rounded-full bg-violet-100 px-2 py-0.5 text-xs font-semibold text-violet-700">
                          Mevcut Plan
                        </span>
                      )}
                    </div>
                    <div className={`h-5 w-5 rounded-full border-2 mt-1 ${
                      isSelected ? 'border-violet-500 bg-violet-500' : 'border-slate-300'
                    }`}>
                      {isSelected && (
                        <svg className="h-full w-full text-white p-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                        </svg>
                      )}
                    </div>
                  </div>

                  {price != null ? (
                    <div className="mb-3">
                      <span className="text-2xl font-bold text-slate-900">
                        ₺{price.toLocaleString('tr-TR')}
                      </span>
                      <span className="text-slate-500 text-sm ml-1">
                        {billingInterval === 'YEARLY' ? '/yıl' : '/ay'}
                      </span>
                      {billingInterval === 'YEARLY' && perMonth != null && (
                        <div className="text-xs text-emerald-600 font-medium mt-0.5">
                          ₺{perMonth.toLocaleString('tr-TR')}/ay karşılığı
                        </div>
                      )}
                    </div>
                  ) : (
                    <div className="mb-3 text-xl font-bold text-slate-900">Ücretsiz</div>
                  )}

                  <div className="space-y-1.5 text-xs text-slate-600 mb-3">
                    {plan.features.slice(0, 3).map((f, i) => (
                      <div key={i} className="flex items-center gap-1.5">
                        <svg className="h-3.5 w-3.5 text-emerald-500 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                        </svg>
                        {f}
                      </div>
                    ))}
                  </div>

                  {plan.description && (
                    <p className="text-xs text-slate-400">{plan.description}</p>
                  )}
                </button>
              );
            })}
          </div>

          {/* Seçilen plan özeti + ödeme butonu */}
          {selectedPlan && chosenPlan && (
            <div className="mt-6 rounded-2xl border border-violet-200 bg-violet-50 p-5">
              <div className="flex items-center justify-between">
                <div>
                  <div className="font-semibold text-slate-900">
                    {chosenPlan.name} — {billingInterval === 'YEARLY' ? 'Yıllık' : 'Aylık'} Ödeme
                  </div>
                  {chosenAmount != null && (
                    <div className="text-sm text-slate-600 mt-0.5">
                      Toplam: <span className="font-bold text-violet-700">₺{chosenAmount.toLocaleString('tr-TR')}</span>
                      {billingInterval === 'YEARLY' ? '/yıl' : '/ay'}
                      {billingInterval === 'YEARLY' && chosenMonthly != null && (
                        <span className="ml-2 text-emerald-600 text-xs">
                          (%15 indirimli, aylık ₺{(chosenMonthly * 0.85).toFixed(0)} karşılığı)
                        </span>
                      )}
                    </div>
                  )}
                  {isCurrentPlan && (
                    <div className="text-xs text-violet-600 mt-1">Bu zaten mevcut planınız ve ödeme periyodunuz.</div>
                  )}
                </div>
                <button
                  onClick={handleUpgrade}
                  disabled={upgrading || isCurrentPlan}
                  className="rounded-xl bg-violet-600 px-6 py-2.5 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50 transition"
                >
                  {upgrading ? 'İşleniyor...' : isCurrentPlan ? 'Mevcut Plan' : 'Planı Seç'}
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {plans.length === 0 && !loading && (
        <div className="rounded-2xl border border-slate-200 bg-white p-8 text-center text-slate-400">
          <p className="text-sm">Henüz satın alınabilir plan bulunmuyor.</p>
        </div>
      )}
    </div>
  );
}
