'use client';

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

export interface School {
  id: string;
  name: string;
  slug: string;
  email: string;
  phone?: string;
  address?: string;
  city?: string;
  isActive: boolean;
  createdAt: string;
  _count?: { students: number; staff: number };
}

interface Props {
  school: School | null;
  onClose: () => void;
  onSave: (school: School) => void;
}

interface PlanDefinition {
  id: string;
  name: string;
  slug: string;
  pricePerStudent: number | null;
  trialDays: number;
  isActive: boolean;
}

const EMPTY_SCHOOL_FORM = {
  name: '',
  slug: '',
  email: '',
  phone: '',
  address: '',
  city: '',
  isActive: true,
  planDefinitionId: '',
  billingInterval: 'MONTHLY' as 'MONTHLY' | 'YEARLY',
  startsAt: '',
  endsAt: '',
};

export default function SchoolModal({ school, onClose, onSave }: Props) {
  const isEdit = !!school;

  const [form, setForm] = useState(EMPTY_SCHOOL_FORM);
  const [adminPassword, setAdminPassword] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [plans, setPlans] = useState<PlanDefinition[]>([]);

  // Plan tanımlarını yükle
  useEffect(() => {
    apiFetchJson<{ items: PlanDefinition[] }>('/v1/platform/plan-definitions').then((res) => {
      if (res.error === null && res.data) {
        setPlans(res.data.items.filter((p) => p.isActive));
      }
    });
  }, []);

  type SchoolWithSub = School & {
    subscription?: {
      planDefinition?: { id: string };
      billingInterval?: string;
      startsAt?: string;
      endsAt?: string;
    };
  };

  useEffect(() => {
    if (school) {
      const s = school as SchoolWithSub;
      setForm({
        name: school.name || '',
        slug: school.slug || '',
        email: school.email || '',
        phone: school.phone || '',
        address: school.address || '',
        city: school.city || '',
        isActive: school.isActive ?? true,
        planDefinitionId: s.subscription?.planDefinition?.id ?? '',
        billingInterval: (s.subscription?.billingInterval as 'MONTHLY' | 'YEARLY') ?? 'MONTHLY',
        startsAt: s.subscription?.startsAt ? s.subscription.startsAt.slice(0, 10) : '',
        endsAt: s.subscription?.endsAt ? s.subscription.endsAt.slice(0, 10) : '',
      });
      setAdminPassword('');
    } else {
      const today = new Date().toISOString().slice(0, 10);
      const trialEnd = new Date(Date.now() + 14 * 86400000).toISOString().slice(0, 10);
      setForm({ ...EMPTY_SCHOOL_FORM, startsAt: today, endsAt: trialEnd });
      setAdminPassword('');
    }
  }, [school]);

  // Seçilen plan değiştiğinde bitiş tarihini otomatik hesapla
  const handlePlanChange = (planDefinitionId: string) => {
    const plan = plans.find((p) => p.id === planDefinitionId);
    if (!planDefinitionId) {
      setForm((prev) => ({ ...prev, planDefinitionId: '' }));
      return;
    }
    const today = new Date();
    const startsAt = form.startsAt ? new Date(form.startsAt) : today;
    let endsAt: Date;
    if (plan && plan.trialDays > 0 && !isEdit) {
      endsAt = new Date(startsAt.getTime() + plan.trialDays * 86400000);
    } else if (form.billingInterval === 'YEARLY') {
      endsAt = new Date(startsAt.getFullYear() + 1, startsAt.getMonth(), startsAt.getDate());
    } else {
      endsAt = new Date(startsAt.getFullYear(), startsAt.getMonth() + 1, startsAt.getDate());
    }
    setForm((prev) => ({
      ...prev,
      planDefinitionId,
      endsAt: endsAt.toISOString().slice(0, 10),
    }));
  };

  // Ödeme periyodu değiştiğinde bitiş tarihini güncelle
  const handleIntervalChange = (billingInterval: 'MONTHLY' | 'YEARLY') => {
    const startsAt = form.startsAt ? new Date(form.startsAt) : new Date();
    let endsAt: Date;
    if (billingInterval === 'YEARLY') {
      endsAt = new Date(startsAt.getFullYear() + 1, startsAt.getMonth(), startsAt.getDate());
    } else {
      endsAt = new Date(startsAt.getFullYear(), startsAt.getMonth() + 1, startsAt.getDate());
    }
    setForm((prev) => ({
      ...prev,
      billingInterval,
      endsAt: endsAt.toISOString().slice(0, 10),
    }));
  };

  // Otomatik slug üret
  const handleNameChange = (name: string) => {
    setForm((prev) => ({
      ...prev,
      name,
      slug: isEdit ? prev.slug : name
        .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, ''),
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError('');

    const payload = {
      ...form,
      planDefinitionId: form.planDefinitionId || undefined,
      startsAt: form.startsAt || undefined,
      endsAt: form.endsAt || undefined,
    };

    const result = isEdit
      ? await apiFetchJson<School>(`/v1/admin/tenants/${school.id}`, {
          method: 'PATCH',
          body: JSON.stringify(payload),
        })
      : await apiFetchJson<School>('/v1/admin/tenants', {
          method: 'POST',
          body: JSON.stringify({ ...payload, adminPassword }),
        });

    if (result.error || !result.data) {
      setError(result.error ?? 'İşlem başarısız');
    } else {
      onSave(result.data);
    }

    setSaving(false);
  };

  const selectedPlan = plans.find((p) => p.id === form.planDefinitionId);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="w-full max-w-lg overflow-hidden rounded-2xl bg-white shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-slate-100 px-6 py-4">
          <div>
            <h2 className="text-lg font-semibold text-gray-900">
              {isEdit ? 'Okulu Düzenle' : 'Yeni Okul Ekle'}
            </h2>
            <p className="text-sm text-gray-500">
              {isEdit ? 'Okul bilgilerini güncelleyin' : 'Platforma yeni bir okul ekleyin'}
            </p>
          </div>
          <button
            onClick={onClose}
            className="rounded-lg p-2 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600"
          >
            <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>

        {/* Form */}
        <form onSubmit={handleSubmit}>
          <div className="max-h-[70vh] overflow-y-auto px-6 py-5">
            {error && (
              <div className="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
                {error}
              </div>
            )}

            <div className="space-y-4">
              {/* Okul Adı */}
              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700">
                  Okul Adı <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={form.name}
                  onChange={(e) => handleNameChange(e.target.value)}
                  placeholder="Güneş Anaokulu"
                  className="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm text-gray-900 placeholder-gray-400 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20"
                  required
                />
              </div>

              {/* Slug */}
              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700">
                  Slug (URL kodu) <span className="text-red-500">*</span>
                </label>
                <div className="flex items-center overflow-hidden rounded-lg border border-slate-300 focus-within:border-violet-500 focus-within:ring-2 focus-within:ring-violet-500/20">
                  <span className="border-r border-slate-200 bg-slate-50 px-3 py-2.5 text-sm text-gray-400">
                    vidikid.com/
                  </span>
                  <input
                    type="text"
                    value={form.slug}
                    onChange={(e) => setForm({ ...form, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') })}
                    placeholder="gunes-anaokulu"
                    className="flex-1 bg-transparent px-3 py-2.5 text-sm text-gray-900 placeholder-gray-400 focus:outline-none"
                    required
                    readOnly={isEdit}
                  />
                </div>
                {!isEdit && <p className="mt-1 text-xs text-gray-400">Sadece küçük harf, rakam ve tire kullanın</p>}
              </div>

              {/* E-posta & Telefon */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">
                    E-posta <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="email"
                    value={form.email}
                    onChange={(e) => setForm({ ...form, email: e.target.value })}
                    placeholder="info@okul.com"
                    className="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm text-gray-900 placeholder-gray-400 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20"
                    required
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Telefon</label>
                  <input
                    type="tel"
                    value={form.phone}
                    onChange={(e) => setForm({ ...form, phone: e.target.value })}
                    placeholder="0212 555 00 00"
                    className="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm text-gray-900 placeholder-gray-400 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20"
                  />
                </div>
              </div>

              {/* Yönetici şifresi — sadece yeni okul */}
              {!isEdit && (
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">
                    Yönetici şifresi <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="password"
                    value={adminPassword}
                    onChange={(e) => setAdminPassword(e.target.value)}
                    placeholder="En az 8 karakter, büyük harf ve rakam"
                    minLength={8}
                    pattern="(?=.*[A-Z])(?=.*[0-9]).{8,}"
                    title="En az 8 karakter, en az bir büyük harf ve bir rakam"
                    className="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm text-gray-900 placeholder-gray-400 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20"
                    required
                    autoComplete="new-password"
                  />
                </div>
              )}

              {/* ─── Abonelik Bölümü ─── */}
              <div className="rounded-xl border border-violet-100 bg-violet-50/30 p-4 space-y-4">
                <h3 className="text-xs font-semibold text-violet-700 uppercase tracking-wide">Abonelik Ayarları</h3>

                {/* Plan seçimi */}
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Abonelik Planı</label>
                  {plans.length === 0 ? (
                    <div className="rounded-lg border border-slate-200 bg-slate-50 px-3.5 py-2.5 text-sm text-slate-400">
                      Henüz plan oluşturulmadı
                    </div>
                  ) : (
                    <select
                      value={form.planDefinitionId}
                      onChange={(e) => handlePlanChange(e.target.value)}
                      className="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm text-gray-900 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20"
                    >
                      <option value="">Plan seçin (opsiyonel)</option>
                      {plans.map((p) => (
                        <option key={p.id} value={p.id}>
                          {p.name}
                          {p.trialDays > 0 ? ` (${p.trialDays}g deneme)` : ''}
                          {p.pricePerStudent != null
                            ? ` — ₺${Number(p.pricePerStudent).toLocaleString('tr-TR')}/öğrenci/ay`
                            : ' — Ücretsiz'}
                        </option>
                      ))}
                    </select>
                  )}
                </div>

                {/* Ödeme Periyodu */}
                {form.planDefinitionId && (
                  <div>
                    <label className="mb-1.5 block text-sm font-medium text-gray-700">Ödeme Periyodu</label>
                    <div className="grid grid-cols-2 gap-2">
                      <button
                        type="button"
                        onClick={() => handleIntervalChange('MONTHLY')}
                        className={`rounded-lg border px-4 py-2.5 text-sm font-medium transition ${
                          form.billingInterval === 'MONTHLY'
                            ? 'border-violet-500 bg-violet-600 text-white'
                            : 'border-slate-300 bg-white text-gray-700 hover:bg-slate-50'
                        }`}
                      >
                        Aylık
                      </button>
                      <button
                        type="button"
                        onClick={() => handleIntervalChange('YEARLY')}
                        className={`rounded-lg border px-4 py-2.5 text-sm font-medium transition ${
                          form.billingInterval === 'YEARLY'
                            ? 'border-violet-500 bg-violet-600 text-white'
                            : 'border-slate-300 bg-white text-gray-700 hover:bg-slate-50'
                        }`}
                      >
                        Yıllık <span className="text-emerald-500 text-xs">%15 indirim</span>
                      </button>
                    </div>
                  </div>
                )}

                {/* Başlangıç & Bitiş tarihleri */}
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="mb-1.5 block text-sm font-medium text-gray-700">Başlangıç Tarihi</label>
                    <input
                      type="date"
                      value={form.startsAt}
                      onChange={(e) => setForm({ ...form, startsAt: e.target.value })}
                      className="w-full rounded-lg border border-slate-300 px-3 py-2.5 text-sm text-gray-900 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20"
                    />
                  </div>
                  <div>
                    <label className="mb-1.5 block text-sm font-medium text-gray-700">Bitiş Tarihi</label>
                    <input
                      type="date"
                      value={form.endsAt}
                      onChange={(e) => setForm({ ...form, endsAt: e.target.value })}
                      className="w-full rounded-lg border border-slate-300 px-3 py-2.5 text-sm text-gray-900 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20"
                    />
                  </div>
                </div>
              </div>

              {/* Şehir */}
              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700">Şehir</label>
                <select
                  value={form.city}
                  onChange={(e) => setForm({ ...form, city: e.target.value })}
                  className="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm text-gray-900 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20"
                >
                  <option value="">Şehir seçin</option>
                  {CITIES.map((c) => <option key={c} value={c}>{c}</option>)}
                </select>
              </div>

              {/* Adres */}
              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700">Adres</label>
                <textarea
                  value={form.address}
                  onChange={(e) => setForm({ ...form, address: e.target.value })}
                  placeholder="Okul adresi..."
                  rows={2}
                  className="w-full resize-none rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm text-gray-900 placeholder-gray-400 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20"
                />
              </div>

              {/* Durum */}
              <div 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-gray-700">Aktif Durum</p>
                  <p className="text-xs text-gray-400">Pasif okullar sisteme giriş yapamaz</p>
                </div>
                <button
                  type="button"
                  onClick={() => setForm({ ...form, isActive: !form.isActive })}
                  className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                    form.isActive ? 'bg-violet-600' : 'bg-slate-300'
                  }`}
                >
                  <span
                    className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
                      form.isActive ? 'translate-x-6' : 'translate-x-1'
                    }`}
                  />
                </button>
              </div>
            </div>
          </div>

          {/* Footer */}
          <div className="flex items-center justify-end gap-3 border-t border-slate-100 px-6 py-4">
            <button
              type="button"
              onClick={onClose}
              className="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-medium text-gray-700 transition hover:bg-slate-50"
            >
              İptal
            </button>
            <button
              type="submit"
              disabled={saving}
              className="rounded-xl bg-violet-600 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-violet-700 disabled:opacity-50"
            >
              {saving ? 'Kaydediliyor...' : isEdit ? 'Değişiklikleri Kaydet' : 'Okul Ekle'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
