import { useState, useEffect } from 'react';
import type { FC } from 'react';
import TelegramSubNav from '../../components/TelegramSubNav';
import { system } from '../../api/client';
import { motion } from 'framer-motion';
import { Webhook, CheckCircle, XCircle, Radio, Loader2, RefreshCw, Copy, Info } from 'lucide-react';

const glassCard = 'rounded-2xl border border-white/[0.06] bg-white/[0.03] backdrop-blur-xl';

interface HealthData {
  status: string;
  timestamp: string;
}

const Webhooks: FC = () => {
  const [health, setHealth] = useState<HealthData | null>(null);
  const [loading, setLoading] = useState(true);
  const [copied, setCopied] = useState(false);

  const webhookBase = `${window.location.protocol}//${window.location.hostname}:3001`;
  const telegramWebhookUrl = `${webhookBase}/api/v1/webhooks/telegram/{BOT_TOKEN}`;
  const kieCallbackUrl = `${webhookBase}/api/v1/webhooks/kie/callback`;

  async function fetchHealth() {
    setLoading(true);
    try {
      const res = await system.health();
      setHealth(res.data?.data ?? res.data ?? null);
    } catch {
      setHealth(null);
    }
    setLoading(false);
  }

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

  const copyUrl = (url: string) => {
    navigator.clipboard.writeText(url).catch(() => {});
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div>
      <TelegramSubNav />

      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="mb-6 flex items-center gap-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-indigo-500/10">
          <Webhook className="h-5 w-5 text-indigo-400" />
        </div>
        <div>
          <h1 className="text-xl font-bold text-white">Webhook & Baglanti Durumu</h1>
          <p className="text-[13px] text-slate-500">Sistem baglanti yontemleri ve webhook endpoint bilgileri.</p>
        </div>
      </motion.div>

      {/* Connection Status */}
      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.05 }} className={`${glassCard} mb-5 p-5`}>
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-[14px] font-semibold text-white">Sunucu Durumu</h2>
          <button onClick={fetchHealth} disabled={loading} className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] text-slate-400 transition-all hover:bg-white/[0.04] hover:text-slate-200 disabled:opacity-50 cursor-pointer">
            {loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
            Yenile
          </button>
        </div>

        <div className="grid gap-3 sm:grid-cols-2">
          <div className={`flex items-center gap-3 rounded-xl border p-4 ${health?.status === 'ok' ? 'border-emerald-500/20 bg-emerald-500/[0.04]' : 'border-red-500/20 bg-red-500/[0.04]'}`}>
            {health?.status === 'ok' ? <CheckCircle className="h-5 w-5 text-emerald-400" /> : <XCircle className="h-5 w-5 text-red-400" />}
            <div>
              <div className="text-[13px] font-medium text-white">Backend API</div>
              <div className="text-[11px] text-slate-500">{health ? `Aktif \u2014 ${new Date(health.timestamp).toLocaleTimeString('tr-TR')}` : 'Baglanti kurulamadi'}</div>
            </div>
          </div>

          <div className="flex items-center gap-3 rounded-xl border border-indigo-500/20 bg-indigo-500/[0.04] p-4">
            <Radio className="h-5 w-5 text-indigo-400" />
            <div>
              <div className="text-[13px] font-medium text-white">Telegram Baglantisi</div>
              <div className="text-[11px] text-slate-500">Long-Polling modu (lokal gelistirme)</div>
            </div>
          </div>
        </div>
      </motion.div>

      {/* Webhook Endpoints */}
      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }} className={`${glassCard} mb-5 p-5`}>
        <h2 className="mb-4 text-[14px] font-semibold text-white">Webhook Endpoint&apos;leri</h2>

        <div className="space-y-4">
          {/* Telegram Webhook */}
          <div className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-4">
            <div className="mb-2 flex items-center gap-2">
              <span className="rounded-md bg-blue-500/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-blue-400">POST</span>
              <span className="text-[13px] font-medium text-white">Telegram Bot Webhook</span>
            </div>
            <div className="flex items-center gap-2">
              <code className="flex-1 rounded-lg bg-black/20 px-3 py-2 text-[12px] text-slate-300 select-all overflow-x-auto">{telegramWebhookUrl}</code>
              <button onClick={() => copyUrl(telegramWebhookUrl)} className="rounded-lg p-2 text-slate-500 transition-all hover:bg-white/[0.04] hover:text-slate-300 cursor-pointer">
                <Copy className="h-4 w-4" />
              </button>
            </div>
            <p className="mt-2 text-[11px] text-slate-500">Bot token&#39;i URL&#39;deki &#123;BOT_TOKEN&#125; yerine koyun. Sunucu disariya acildiginda Telegram webhook olarak bu URL kullanilir.</p>
          </div>

          {/* KIE Callback */}
          <div className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-4">
            <div className="mb-2 flex items-center gap-2">
              <span className="rounded-md bg-emerald-500/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-emerald-400">POST</span>
              <span className="text-[13px] font-medium text-white">KIE Gorsel Uretim Callback</span>
            </div>
            <div className="flex items-center gap-2">
              <code className="flex-1 rounded-lg bg-black/20 px-3 py-2 text-[12px] text-slate-300 select-all overflow-x-auto">{kieCallbackUrl}</code>
              <button onClick={() => copyUrl(kieCallbackUrl)} className="rounded-lg p-2 text-slate-500 transition-all hover:bg-white/[0.04] hover:text-slate-300 cursor-pointer">
                <Copy className="h-4 w-4" />
              </button>
            </div>
            <p className="mt-2 text-[11px] text-slate-500">KIE API gorsel uretim tamamlandiginda bu URL&#39;e callback gonderir. WEBHOOK_BASE_URL env degiskeniyle ayarlanir.</p>
          </div>
        </div>

        {copied && (
          <motion.div initial={{ opacity: 0, y: 5 }} animate={{ opacity: 1, y: 0 }} className="mt-3 flex items-center gap-1.5 text-[11px] text-emerald-400">
            <CheckCircle className="h-3.5 w-3.5" /> Panoya kopyalandi
          </motion.div>
        )}
      </motion.div>

      {/* Info Card */}
      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }} className={`${glassCard} p-5`}>
        <div className="flex gap-3">
          <Info className="mt-0.5 h-5 w-5 flex-shrink-0 text-amber-400" />
          <div>
            <h3 className="mb-1 text-[13px] font-semibold text-white">Baglanti Yontemleri Hakkinda</h3>
            <div className="space-y-2 text-[12px] text-slate-400 leading-relaxed">
              <p><strong className="text-slate-300">Long-Polling (Varsayilan):</strong> Sistem lokal ortamda calisirken Telegram API&#39;ye periyodik olarak baglanir ve yeni mesajlari ceker. Disariya acik port gerektirmez.</p>
              <p><strong className="text-slate-300">Webhook Modu:</strong> Sunucu disariya acildiginda (ngrok, Cloudflare Tunnel vb.) Telegram webhook URL&#39;i ayarlanarak gercek zamanli mesaj alimi saglanir.</p>
              <p><strong className="text-slate-300">KIE Callback:</strong> Gorsel uretim islemleri tamamlandiginda KIE API sonucu bu endpoint&#39;e gonderir. Lokal ortamda polling ile de kontrol edilir.</p>
            </div>
          </div>
        </div>
      </motion.div>
    </div>
  );
};

export default Webhooks;
