'use client';

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

interface Announcement {
  id: string;
  title: string;
  content: string;
  targetAudience: string;
  status: string;
  sentAt: string;
}

type TabKey = 'announcements' | 'templates' | 'history';

const AUDIENCE_LABELS: Record<string, string> = {
  ALL: 'Tüm Okullar',
  ACTIVE: 'Aktif Okullar',
  TRIAL: 'Deneme Okulları',
  ADMINS: 'Sadece Adminler',
};

const AUDIENCE_BADGE: Record<string, string> = {
  ALL: 'bg-indigo-100 text-indigo-700',
  ACTIVE: 'bg-emerald-100 text-emerald-700',
  TRIAL: 'bg-amber-100 text-amber-700',
  ADMINS: 'bg-violet-100 text-violet-700',
};

const TEMPLATES = [
  {
    id: 'welcome',
    title: 'Hoş Geldiniz',
    description: 'Yeni kayıt olan okullara gönderilecek karşılama mesajı',
    preview: 'VidiKid ailesine hoş geldiniz! Platformumuzu keşfetmeye başlamak için...',
    icon: '👋',
  },
  {
    id: 'trial_ending',
    title: 'Deneme Süresi Bitiyor',
    description: '7 günü kalan deneme okullarına hatırlatma',
    preview: 'Deneme süreniz 7 gün içinde sona erecek. Abonenizi aktifleştirin...',
    icon: '⏳',
  },
  {
    id: 'maintenance',
    title: 'Bakım Bildirimi',
    description: 'Planlı bakım dönemleri için bildirim',
    preview: 'Sayın kullanıcılar, [TARİH] tarihinde saat [SAAT] ile [SAAT] arasında...',
    icon: '🔧',
  },
  {
    id: 'new_feature',
    title: 'Yeni Özellik',
    description: 'Yeni eklenen özellikler hakkında duyuru',
    preview: 'VidiKid\'e yeni özellikler eklendi! Artık [ÖZELLİK] ile...',
    icon: '✨',
  },
];

function fmtDate(d: string) {
  return new Date(d).toLocaleString('tr-TR', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
}

export default function CommunicationsPage() {
  const [activeTab, setActiveTab] = useState<TabKey>('announcements');
  const [announcements, setAnnouncements] = useState<Announcement[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCompose, setShowCompose] = useState(false);
  const [composeForm, setComposeForm] = useState({ title: '', content: '', targetAudience: 'ALL' });
  const [sending, setSending] = useState(false);
  const [toast, setToast] = useState<{ msg: string; type: 'success' | 'error' } | null>(null);
  const [selectedTemplate, setSelectedTemplate] = useState<string | null>(null);

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

  useEffect(() => {
    apiFetchJson<{ items: Announcement[] }>('/v1/platform/communications/announcements').then((res) => {
      if (res.error === null && res.data) setAnnouncements(res.data.items);
      setLoading(false);
    });
  }, []);

  const handleSend = async () => {
    if (!composeForm.title || !composeForm.content) {
      showToast('Başlık ve içerik zorunludur', 'error');
      return;
    }
    setSending(true);
    try {
      const res = await apiFetchJson('/v1/platform/communications/announcements', {
        method: 'POST',
        body: JSON.stringify(composeForm),
      });
      if (res.error === null) {
        showToast('Duyuru gönderildi');
        setShowCompose(false);
        setComposeForm({ title: '', content: '', targetAudience: 'ALL' });
        if (res.data) setAnnouncements((prev) => [res.data as Announcement, ...prev]);
      } else {
        showToast(res.error || 'Hata oluştu', 'error');
      }
    } finally {
      setSending(false);
    }
  };

  const useTemplate = (template: typeof TEMPLATES[0]) => {
    setComposeForm({ title: template.title, content: template.preview, targetAudience: 'ALL' });
    setSelectedTemplate(template.id);
    setActiveTab('announcements');
    setShowCompose(true);
  };

  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 ${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-rose-950 to-slate-900 px-8 py-10 text-white shadow-xl">
        <div className="absolute inset-0 overflow-hidden">
          <div className="absolute -top-16 -right-16 h-56 w-56 rounded-full bg-rose-500/10 blur-3xl" />
          <div className="absolute -bottom-8 -left-8 h-40 w-40 rounded-full bg-orange-500/10 blur-3xl" />
        </div>
        <div className="relative flex items-start justify-between">
          <div>
            <div className="flex items-center gap-2 text-rose-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="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z" />
              </svg>
              İletişim Merkezi
            </div>
            <h1 className="text-3xl font-bold tracking-tight">Duyurular & İletişim</h1>
            <p className="mt-1.5 text-slate-300">Tüm okullara toplu bildirim ve duyuru gönderin.</p>
          </div>
          <button
            onClick={() => { setShowCompose(true); setSelectedTemplate(null); }}
            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 Duyuru
          </button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
        {[
          { label: 'Toplam Duyuru', value: announcements.length, bg: 'bg-slate-50', icon: (
            <svg className="h-5 w-5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z" />
            </svg>
          ), color: 'text-slate-900' },
          { label: 'Bu Ay Gönderildi', value: announcements.filter(a => {
            const d = new Date(a.sentAt);
            const now = new Date();
            return d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear();
          }).length, bg: 'bg-emerald-50', icon: (
            <svg className="h-5 w-5 text-emerald-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          ), color: 'text-emerald-700' },
          { label: 'Hedef Gruplar', value: 4, bg: 'bg-indigo-50', icon: (
            <svg className="h-5 w-5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
          ), color: 'text-indigo-700' },
        ].map((s) => (
          <div key={s.label} className={`rounded-2xl border border-slate-200 ${s.bg} p-5 shadow-sm`}>
            <div className="flex items-center gap-3">
              {s.icon}
              <div>
                <div className={`text-2xl font-bold ${s.color}`}>{s.value}</div>
                <div className="text-sm text-slate-500">{s.label}</div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div className="rounded-2xl border border-slate-200 bg-white shadow-sm overflow-hidden">
        <div className="flex border-b border-slate-100 px-4 pt-4">
          {([
            { key: 'announcements', label: 'Duyuru Geçmişi' },
            { key: 'templates', label: 'Şablonlar' },
          ] as { key: TabKey; label: string }[]).map((tab) => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={`px-4 py-2.5 text-sm font-medium rounded-t-lg border-b-2 mr-1 transition-colors ${
                activeTab === tab.key
                  ? 'border-indigo-600 text-indigo-700 bg-indigo-50/50'
                  : 'border-transparent text-slate-500 hover:text-slate-700'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {/* Announcements list */}
        {activeTab === 'announcements' && (
          loading ? (
            <div className="p-6 space-y-3">
              {Array.from({ length: 4 }).map((_, i) => <div key={i} className="h-16 rounded-xl bg-slate-100 animate-pulse" />)}
            </div>
          ) : announcements.length === 0 ? (
            <div className="py-16 text-center">
              <div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-slate-100">
                <svg className="h-7 w-7 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z" />
                </svg>
              </div>
              <p className="text-sm font-medium text-slate-700">Henüz duyuru gönderilmedi</p>
              <p className="text-sm text-slate-400 mt-1">İlk duyuruyu oluşturmak için "Yeni Duyuru" butonunu kullanın.</p>
              <button
                onClick={() => setShowCompose(true)}
                className="mt-4 inline-flex items-center gap-2 rounded-xl bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-indigo-700 transition-colors"
              >
                Duyuru Oluştur
              </button>
            </div>
          ) : (
            <div className="divide-y divide-slate-100">
              {announcements.map((ann) => (
                <div key={ann.id} className="px-6 py-4 hover:bg-slate-50/60 transition-colors">
                  <div className="flex items-start gap-4">
                    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-rose-50 text-rose-500">
                      <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z" />
                      </svg>
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="font-medium text-slate-900">{ann.title}</span>
                        <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${AUDIENCE_BADGE[ann.targetAudience] ?? 'bg-slate-100 text-slate-600'}`}>
                          {AUDIENCE_LABELS[ann.targetAudience] ?? ann.targetAudience}
                        </span>
                        <span className="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-emerald-100 text-emerald-700">
                          Gönderildi
                        </span>
                      </div>
                      <p className="text-sm text-slate-500 mt-1 line-clamp-2">{ann.content}</p>
                      <div className="text-xs text-slate-400 mt-2">{fmtDate(ann.sentAt)}</div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )
        )}

        {/* Templates */}
        {activeTab === 'templates' && (
          <div className="p-6 grid grid-cols-1 sm:grid-cols-2 gap-4">
            {TEMPLATES.map((t) => (
              <div key={t.id} className="rounded-xl border border-slate-200 p-5 hover:border-indigo-300 hover:shadow-md transition-all group cursor-pointer" onClick={() => useTemplate(t)}>
                <div className="flex items-start gap-3 mb-3">
                  <span className="text-2xl">{t.icon}</span>
                  <div className="flex-1 min-w-0">
                    <div className="font-semibold text-slate-900 group-hover:text-indigo-700 transition-colors">{t.title}</div>
                    <div className="text-xs text-slate-500 mt-0.5">{t.description}</div>
                  </div>
                </div>
                <p className="text-sm text-slate-400 italic line-clamp-2">"{t.preview}"</p>
                <div className="mt-3 flex justify-end">
                  <span className="text-xs font-medium text-indigo-600 group-hover:text-indigo-700">Şablonu Kullan →</span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Compose modal */}
      {showCompose && (
        <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={() => setShowCompose(false)} />
          <div className="relative w-full max-w-lg rounded-2xl bg-white shadow-2xl">
            <div className="px-6 py-5 border-b border-slate-100 flex items-start justify-between">
              <div>
                <h3 className="text-lg font-semibold text-slate-900">Yeni Duyuru</h3>
                <p className="text-sm text-slate-500 mt-0.5">Tüm okullara veya belirli gruplara duyuru gönderin</p>
              </div>
              <button onClick={() => setShowCompose(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="px-6 py-5 space-y-4">
              <div>
                <label className={labelCls}>Hedef Kitle</label>
                <select
                  value={composeForm.targetAudience}
                  onChange={(e) => setComposeForm({ ...composeForm, targetAudience: e.target.value })}
                  className={inputCls}
                >
                  {Object.entries(AUDIENCE_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
                </select>
              </div>
              <div>
                <label className={labelCls}>Başlık</label>
                <input
                  value={composeForm.title}
                  onChange={(e) => setComposeForm({ ...composeForm, title: e.target.value })}
                  placeholder="Duyuru başlığı"
                  className={inputCls}
                />
              </div>
              <div>
                <label className={labelCls}>İçerik</label>
                <textarea
                  value={composeForm.content}
                  onChange={(e) => setComposeForm({ ...composeForm, content: e.target.value })}
                  placeholder="Duyuru içeriğini buraya yazın..."
                  rows={6}
                  className={inputCls + ' resize-none'}
                />
                <div className="flex justify-end mt-1">
                  <span className="text-xs text-slate-400">{composeForm.content.length} karakter</span>
                </div>
              </div>

              {/* Preview */}
              {composeForm.title && composeForm.content && (
                <div className="rounded-xl bg-slate-50 border border-slate-200 p-4">
                  <div className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Önizleme</div>
                  <div className="font-semibold text-slate-900 text-sm">{composeForm.title}</div>
                  <p className="text-xs text-slate-600 mt-1">{composeForm.content}</p>
                  <div className="flex items-center gap-1.5 mt-2">
                    <div className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
                    <span className="text-xs text-slate-400">→ {AUDIENCE_LABELS[composeForm.targetAudience]}</span>
                  </div>
                </div>
              )}
            </div>
            <div className="px-6 py-4 border-t border-slate-100 flex gap-3 justify-end">
              <button onClick={() => setShowCompose(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={handleSend}
                disabled={sending}
                className="flex items-center gap-2 rounded-xl bg-rose-600 hover:bg-rose-700 px-5 py-2 text-sm font-semibold text-white disabled:opacity-60 transition-colors"
              >
                {sending ? (
                  'Gönderiliyor...'
                ) : (
                  <>
                    <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                    </svg>
                    Gönder
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
