'use client';

import { useEffect, useState } from 'react';
import { apiFetchJson } from '@/lib/auth';

interface PlanDefinition {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  pricePerStudent: number | null;
  currency: string;
  trialDays: number;
  features: string[];
  isActive: boolean;
  isPublic: boolean;
  sortOrder: number;
  createdAt: string;
  updatedAt: string;
}

const EMPTY_FORM = {
  name: '',
  slug: '',
  description: '',
  pricePerStudent: '',
  currency: 'TRY',
  trialDays: 0,
  features: [] as string[],
  isActive: true,
  isPublic: true,
  sortOrder: 0,
};

const ICON_COLORS = [
  { bg: 'bg-amber-100', text: 'text-amber-600', border: 'border-amber-200', badge: 'bg-amber-100 text-amber-700', gradient: 'from-amber-50 to-orange-50' },
  { bg: 'bg-indigo-100', text: 'text-indigo-600', border: 'border-indigo-200', badge: 'bg-indigo-100 text-indigo-700', gradient: 'from-indigo-50 to-blue-50' },
  { bg: 'bg-emerald-100', text: 'text-emerald-600', border: 'border-emerald-200', badge: 'bg-emerald-100 text-emerald-700', gradient: 'from-emerald-50 to-teal-50' },
  { bg: 'bg-violet-100', text: 'text-violet-600', border: 'border-violet-200', badge: 'bg-violet-100 text-violet-700', gradient: 'from-violet-50 to-purple-50' },
  { bg: 'bg-rose-100', text: 'text-rose-600', border: 'border-rose-200', badge: 'bg-rose-100 text-rose-700', gradient: 'from-rose-50 to-pink-50' },
];

function getColor(idx: number) {
  return ICON_COLORS[idx % ICON_COLORS.length];
}

function slugify(str: string) {
  return str
    .toLowerCase()
    .replace(/ğ/g, 'g').replace(/ü/g, 'u').replace(/ş/g, 's')
    .replace(/ı/g, 'i').replace(/ö/g, 'o').replace(/ç/g, 'c')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '');
}

export default function PlansPage() {
  const [plans, setPlans] = useState<PlanDefinition[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editPlan, setEditPlan] = useState<PlanDefinition | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<PlanDefinition | null>(null);
  const [form, setForm] = useState({ ...EMPTY_FORM });
  const [newFeature, setNewFeature] = useState('');
  const [saving, setSaving] = 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), 3500);
  };

  const load = async () => {
    setLoading(true);
    const res = await apiFetchJson<{ items: PlanDefinition[] }>('/v1/platform/plan-definitions');
    if (res.error === null && res.data) setPlans(res.data.items);
    setLoading(false);
  };

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

  const openCreate = () => {
    setEditPlan(null);
    setForm({ ...EMPTY_FORM });
    setNewFeature('');
    setShowModal(true);
  };

  const openEdit = (plan: PlanDefinition) => {
    setEditPlan(plan);
    setForm({
      name: plan.name,
      slug: plan.slug,
      description: plan.description ?? '',
      pricePerStudent: plan.pricePerStudent != null ? String(plan.pricePerStudent) : '',
      currency: plan.currency,
      trialDays: plan.trialDays,
      features: [...plan.features],
      isActive: plan.isActive,
      isPublic: plan.isPublic,
      sortOrder: plan.sortOrder,
    });
    setNewFeature('');
    setShowModal(true);
  };

  const handleNameChange = (name: string) => {
    setForm((f) => ({ ...f, name, slug: editPlan ? f.slug : slugify(name) }));
  };

  const addFeature = () => {
    const f = newFeature.trim();
    if (f && !form.features.includes(f)) {
      setForm((prev) => ({ ...prev, features: [...prev.features, f] }));
    }
    setNewFeature('');
  };

  const removeFeature = (idx: number) => {
    setForm((prev) => ({ ...prev, features: prev.features.filter((_, i) => i !== idx) }));
  };

  const handleSave = async () => {
    if (!form.name || !form.slug) {
      showToast('Plan adı ve slug zorunludur', 'error');
      return;
    }
    setSaving(true);
    try {
      const body = {
        name: form.name,
        ...(editPlan ? {} : { slug: form.slug }),
        description: form.description || undefined,
        pricePerStudent: form.pricePerStudent ? parseFloat(form.pricePerStudent) : undefined,
        currency: form.currency,
        trialDays: Number(form.trialDays),
        features: form.features,
        isActive: form.isActive,
        isPublic: form.isPublic,
        sortOrder: Number(form.sortOrder),
      };

      const res = editPlan
        ? await apiFetchJson(`/v1/platform/plan-definitions/${editPlan.id}`, { method: 'PATCH', body: JSON.stringify(body) })
        : await apiFetchJson('/v1/platform/plan-definitions', { method: 'POST', body: JSON.stringify(body) });

      if (res.error === null) {
        showToast(editPlan ? 'Plan güncellendi' : 'Plan oluşturuldu');
        setShowModal(false);
        load();
      } else {
        showToast(res.error || 'Hata oluştu', 'error');
      }
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    setSaving(true);
    try {
      const res = await apiFetchJson(`/v1/platform/plan-definitions/${deleteTarget.id}`, { method: 'DELETE' });
      if (res.error === null) {
        showToast('Plan silindi');
        setDeleteTarget(null);
        load();
      } else {
        showToast(res.error || 'Silinemedi', 'error');
      }
    } finally {
      setSaving(false);
    }
  };

  const inputCls = 'w-full rounded-xl border border-slate-200 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent';
  const labelCls = 'block text-xs font-semibold text-slate-600 uppercase tracking-wide mb-1.5';

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

      {/* Page header */}
      <div className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-slate-900 via-indigo-950 to-slate-900 px-8 py-10 text-white shadow-xl">
        <div className="absolute inset-0 overflow-hidden">
          <div className="absolute -top-20 -right-20 h-64 w-64 rounded-full bg-indigo-500/10 blur-3xl" />
          <div className="absolute -bottom-10 -left-10 h-48 w-48 rounded-full bg-violet-500/10 blur-3xl" />
        </div>
        <div className="relative flex items-start justify-between">
          <div>
            <div className="flex items-center gap-2 text-indigo-300 text-sm font-medium mb-2">
              <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" />
              </svg>
              Plan Yönetimi
            </div>
            <h1 className="text-3xl font-bold tracking-tight">Abonelik Planları</h1>
            <p className="mt-1.5 text-slate-300 max-w-xl">
              Dinamik planlar oluşturun, limitlerini ve özelliklerini belirleyin.
            </p>
          </div>
          <button
            onClick={openCreate}
            className="flex items-center gap-2 rounded-xl bg-white/10 hover:bg-white/20 backdrop-blur-sm px-4 py-2.5 text-sm font-semibold text-white border border-white/20 transition-colors"
          >
            <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
            Yeni Plan
          </button>
        </div>
      </div>

      {/* Plan cards */}
      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
          {Array.from({ length: 3 }).map((_, i) => (
            <div key={i} className="h-64 rounded-2xl bg-slate-100 animate-pulse" />
          ))}
        </div>
      ) : plans.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-slate-300 bg-white py-20 text-center">
          <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-indigo-50">
            <svg className="h-8 w-8 text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 2L2 7l10 5 10-5-10-5Z M2 17l10 5 10-5 M2 12l10 5 10-5" />
            </svg>
          </div>
          <p className="text-base font-semibold text-slate-700">Henüz plan oluşturulmadı</p>
          <p className="text-sm text-slate-400 mt-1">İlk planı oluşturmak için "Yeni Plan" butonuna tıklayın.</p>
          <button onClick={openCreate} className="mt-5 inline-flex items-center gap-2 rounded-xl bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-indigo-700 transition-colors">
            <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
            Plan Oluştur
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
          {plans.map((plan, i) => {
            const clr = getColor(i);
            return (
              <div
                key={plan.id}
                className={`relative rounded-2xl border bg-gradient-to-br ${clr.gradient} ${clr.border} p-6 shadow-sm transition-shadow hover:shadow-md`}
              >
                {!plan.isActive && (
                  <div className="absolute top-3 right-3">
                    <span className="rounded-full bg-slate-200 px-2.5 py-0.5 text-xs font-medium text-slate-500">Pasif</span>
                  </div>
                )}

                {/* Header */}
                <div className="flex items-start gap-3 mb-4">
                  <div className={`flex h-11 w-11 items-center justify-center rounded-xl ${clr.bg} ${clr.text} shrink-0`}>
                    <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 2L2 7l10 5 10-5-10-5Z M2 17l10 5 10-5 M2 12l10 5 10-5" />
                    </svg>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-bold text-slate-900 text-base">{plan.name}</div>
                    <div className="text-xs text-slate-500 font-mono mt-0.5">{plan.slug}</div>
                  </div>
                </div>

                {/* Price */}
                <div className="mb-3">
                  {plan.pricePerStudent != null ? (
                    <>
                      <span className="text-2xl font-extrabold text-slate-900">
                        ₺{Number(plan.pricePerStudent).toLocaleString('tr-TR')}
                      </span>
                      <span className="text-sm text-slate-500 ml-1">/ öğrenci / ay</span>
                    </>
                  ) : (
                    <>
                      <span className="text-2xl font-extrabold text-slate-900">Ücretsiz</span>
                    </>
                  )}
                  {plan.trialDays > 0 && (
                    <span className="ml-2 rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700">
                      {plan.trialDays}g deneme
                    </span>
                  )}
                </div>

                {/* Description */}
                {plan.description && (
                  <p className="text-sm text-slate-600 mb-4 line-clamp-2">{plan.description}</p>
                )}

                {/* Features */}
                {plan.features.length > 0 && (
                  <ul className="space-y-1.5 mb-4">
                    {plan.features.slice(0, 4).map((f, fi) => (
                      <li key={fi} className="flex items-center gap-2 text-sm">
                        <svg className={`h-3.5 w-3.5 shrink-0 ${clr.text}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                        </svg>
                        <span className="text-slate-700 truncate">{f}</span>
                      </li>
                    ))}
                    {plan.features.length > 4 && (
                      <li className="text-xs text-slate-400 pl-5.5">+{plan.features.length - 4} özellik daha</li>
                    )}
                  </ul>
                )}

                {/* Actions */}
                <div className="flex gap-2 pt-1">
                  <button
                    onClick={() => openEdit(plan)}
                    className="flex-1 flex items-center justify-center gap-1.5 rounded-xl border border-slate-200 bg-white/70 px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-white hover:shadow-sm transition-all"
                  >
                    <svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                    Düzenle
                  </button>
                  <button
                    onClick={() => setDeleteTarget(plan)}
                    className="flex items-center justify-center rounded-xl border border-red-200 bg-white/70 px-3 py-2 text-xs font-semibold text-red-600 hover:bg-red-50 transition-all"
                  >
                    <svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Create / Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={() => setShowModal(false)} />
          <div className="relative w-full max-w-xl rounded-2xl bg-white shadow-2xl max-h-[90vh] flex flex-col">
            <div className="px-6 py-5 border-b border-slate-100 flex items-start justify-between shrink-0">
              <div>
                <h3 className="text-lg font-semibold text-slate-900">{editPlan ? 'Planı Düzenle' : 'Yeni Plan Oluştur'}</h3>
                <p className="text-sm text-slate-500 mt-0.5">Planın fiyatını ve özelliklerini belirleyin</p>
              </div>
              <button onClick={() => setShowModal(false)} className="text-slate-400 hover:text-slate-600 transition-colors">
                <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            <div className="overflow-y-auto flex-1 px-6 py-5 space-y-5">
              {/* Name + slug */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className={labelCls}>Plan Adı <span className="text-red-500">*</span></label>
                  <input
                    value={form.name}
                    onChange={(e) => handleNameChange(e.target.value)}
                    placeholder="Starter"
                    className={inputCls}
                  />
                </div>
                <div>
                  <label className={labelCls}>Slug <span className="text-red-500">*</span></label>
                  <input
                    value={form.slug}
                    onChange={(e) => setForm({ ...form, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') })}
                    placeholder="starter"
                    className={inputCls}
                    readOnly={!!editPlan}
                  />
                </div>
              </div>

              {/* Description */}
              <div>
                <label className={labelCls}>Açıklama</label>
                <textarea
                  value={form.description}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                  rows={2}
                  placeholder="Plan hakkında kısa açıklama..."
                  className={inputCls + ' resize-none'}
                />
              </div>

              {/* Price + currency + trial */}
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className={labelCls}>Öğrenci Başı Fiyat (₺)</label>
                  <input
                    type="number"
                    value={form.pricePerStudent}
                    onChange={(e) => setForm({ ...form, pricePerStudent: e.target.value })}
                    placeholder="29"
                    min="0"
                    step="0.01"
                    className={inputCls}
                  />
                </div>
                <div>
                  <label className={labelCls}>Para Birimi</label>
                  <select value={form.currency} onChange={(e) => setForm({ ...form, currency: e.target.value })} className={inputCls}>
                    <option value="TRY">TRY</option>
                    <option value="USD">USD</option>
                    <option value="EUR">EUR</option>
                  </select>
                </div>
                <div>
                  <label className={labelCls}>Deneme (gün)</label>
                  <input
                    type="number"
                    value={form.trialDays}
                    onChange={(e) => setForm({ ...form, trialDays: parseInt(e.target.value) || 0 })}
                    min="0"
                    className={inputCls}
                  />
                </div>
              </div>

              {/* Features */}
              <div>
                <label className={labelCls}>Özellikler</label>
                <div className="flex gap-2 mb-2">
                  <input
                    value={newFeature}
                    onChange={(e) => setNewFeature(e.target.value)}
                    onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addFeature())}
                    placeholder="Özellik ekle (Enter ile kaydet)"
                    className={inputCls}
                  />
                  <button
                    type="button"
                    onClick={addFeature}
                    className="rounded-xl bg-indigo-600 px-4 text-sm font-semibold text-white hover:bg-indigo-700 transition-colors shrink-0"
                  >
                    Ekle
                  </button>
                </div>
                {form.features.length > 0 && (
                  <div className="flex flex-wrap gap-2">
                    {form.features.map((f, i) => (
                      <div key={i} className="flex items-center gap-1.5 rounded-lg bg-indigo-50 px-3 py-1.5 text-sm text-indigo-700">
                        <span>{f}</span>
                        <button onClick={() => removeFeature(i)} className="text-indigo-400 hover:text-indigo-700 ml-0.5">×</button>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {/* Toggles */}
              <div className="grid grid-cols-2 gap-4">
                {[
                  { key: 'isActive' as const, label: 'Aktif', desc: 'Plan yeni aboneliklere atanabilir' },
                  { key: 'isPublic' as const, label: 'Halka Açık', desc: 'Fiyatlandırma sayfasında göster' },
                ].map((toggle) => (
                  <div key={toggle.key} className="flex items-center justify-between rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
                    <div>
                      <p className="text-sm font-medium text-slate-800">{toggle.label}</p>
                      <p className="text-xs text-slate-500">{toggle.desc}</p>
                    </div>
                    <button
                      type="button"
                      onClick={() => setForm({ ...form, [toggle.key]: !form[toggle.key] })}
                      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${form[toggle.key] ? 'bg-indigo-600' : 'bg-slate-200'}`}
                    >
                      <span className={`inline-block h-4 w-4 rounded-full bg-white shadow transform transition-transform ${form[toggle.key] ? 'translate-x-6' : 'translate-x-1'}`} />
                    </button>
                  </div>
                ))}
              </div>

              {/* Sort order */}
              <div className="w-32">
                <label className={labelCls}>Sıralama</label>
                <input
                  type="number"
                  value={form.sortOrder}
                  onChange={(e) => setForm({ ...form, sortOrder: parseInt(e.target.value) || 0 })}
                  min="0"
                  className={inputCls}
                />
              </div>
            </div>

            <div className="px-6 py-4 border-t border-slate-100 flex gap-3 justify-end shrink-0">
              <button onClick={() => setShowModal(false)} className="rounded-xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors">
                İptal
              </button>
              <button
                onClick={handleSave}
                disabled={saving}
                className="rounded-xl bg-indigo-600 px-6 py-2 text-sm font-semibold text-white hover:bg-indigo-700 disabled:opacity-60 transition-colors"
              >
                {saving ? 'Kaydediliyor...' : editPlan ? 'Güncelle' : 'Oluştur'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete confirm */}
      {deleteTarget && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={() => setDeleteTarget(null)} />
          <div className="relative w-full max-w-sm rounded-2xl bg-white shadow-2xl p-6">
            <div className="flex h-12 w-12 items-center justify-center rounded-full bg-red-100 mb-4">
              <svg className="h-6 w-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-slate-900">Planı Sil</h3>
            <p className="text-sm text-slate-500 mt-1.5">
              <strong>{deleteTarget.name}</strong> planı kalıcı olarak silinecek.
              Bu plana atanmış aktif abonelik varsa silinemez.
            </p>
            <div className="flex gap-3 mt-6">
              <button onClick={() => setDeleteTarget(null)} className="flex-1 rounded-xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors">
                İptal
              </button>
              <button
                onClick={handleDelete}
                disabled={saving}
                className="flex-1 rounded-xl bg-red-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-red-700 disabled:opacity-60 transition-colors"
              >
                {saving ? 'Siliniyor...' : 'Evet, Sil'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
