import React, { useState, useEffect, useCallback } from 'react';
import { backup, queue, system } from '../api/client';
import { motion } from 'framer-motion';
import { RefreshCw } from 'lucide-react';

interface BackupItem { filename: string; size?: number; createdAt: string; }
interface BackupStatus { status: string; progress?: number; message?: string; }
interface QueueStatus { pending: number; processing: number; completed: number; failed: number; }
interface FailedTask { id: string; type: string; characterId?: string; error?: string; createdAt: string; }
interface HealthInfo { status: string; uptime?: number; timestamp?: string; }
interface SystemError { message: string; timestamp: string; level?: string; }
type TabKey = 'backup' | 'queue' | 'system';

const TABS: { key: TabKey; label: string }[] = [{ key: 'backup', label: 'Yedekleme' }, { key: 'queue', label: 'Kuyruk' }, { key: 'system', label: 'Sistem' }];
const cardClass = 'rounded-2xl border border-white/[0.06] bg-white/[0.03] backdrop-blur-xl p-6';

const Settings: React.FC = () => {
  const [activeTab, setActiveTab] = useState<TabKey>('backup');
  return (
    <div>
      <motion.h1 initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="mb-6 text-2xl font-bold bg-gradient-to-r from-indigo-400 via-violet-400 to-purple-400 bg-clip-text text-transparent">Ayarlar</motion.h1>
      <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.1 }} className="mb-6 flex gap-1 rounded-xl border border-white/[0.06] bg-white/[0.02] p-1">
        {TABS.map((tab) => (
          <button key={tab.key} onClick={() => setActiveTab(tab.key)}
            className={`relative rounded-lg px-5 py-2.5 text-sm font-medium transition-all ${activeTab === tab.key ? 'text-white' : 'text-slate-400 hover:bg-white/[0.04] hover:text-slate-200'}`}>
            {activeTab === tab.key && <motion.div layoutId="settingsTab" className="absolute inset-0 rounded-lg bg-gradient-to-r from-indigo-500 to-violet-500 shadow-lg shadow-indigo-500/20" transition={{ type: 'spring', stiffness: 350, damping: 30 }} />}
            <span className="relative z-10">{tab.label}</span>
          </button>
        ))}
      </motion.div>
      {activeTab === 'backup' && <BackupSection />}
      {activeTab === 'queue' && <QueueSection />}
      {activeTab === 'system' && <SystemSection />}
    </div>
  );
};

const BackupSection: React.FC = () => {
  const [backups, setBackups] = useState<BackupItem[]>([]); const [status, setStatus] = useState<BackupStatus | null>(null);
  const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null);
  const [creating, setCreating] = useState(false); const [restoring, setRestoring] = useState(false);
  const fetchData = useCallback(async () => { setLoading(true); setError(null); try { const [listRes, statusRes] = await Promise.allSettled([backup.list(), backup.getStatus()]); if (listRes.status === 'fulfilled') setBackups(listRes.value.data?.data ?? listRes.value.data ?? []); if (statusRes.status === 'fulfilled') setStatus(statusRes.value.data?.data ?? statusRes.value.data ?? null); } catch { setError('Yedekleme bilgileri yüklenemedi.'); } finally { setLoading(false); } }, []);
  useEffect(() => { fetchData(); }, [fetchData]);
  const handleCreate = async () => { setCreating(true); setError(null); try { await backup.create(); await fetchData(); } catch { setError('Yedekleme başlatılırken hata oluştu.'); } finally { setCreating(false); } };
  const handleRestore = async (e: React.ChangeEvent<HTMLInputElement>) => { const file = e.target.files?.[0]; if (!file) return; if (!confirm('Geri yükleme mevcut verilerin üzerine yazacaktır. Devam etmek istiyor musunuz?')) { e.target.value = ''; return; } setRestoring(true); setError(null); try { const formData = new FormData(); formData.append('file', file); await backup.restore(formData); await fetchData(); } catch { setError('Geri yükleme sırasında hata oluştu.'); } finally { setRestoring(false); e.target.value = ''; } };
  const formatSize = (bytes?: number) => { if (!bytes) return '—'; if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; };
  if (loading) return <LoadingText />;
  return (
    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-5">
      {error && <ErrorBanner message={error} onDismiss={() => setError(null)} />}
      {status && status.status !== 'idle' && (
        <div className="flex items-center gap-3 rounded-2xl border border-white/[0.06] bg-white/[0.03] p-4 backdrop-blur-xl">
          <div className={`h-2.5 w-2.5 rounded-full ${status.status === 'completed' ? 'bg-emerald-500' : 'bg-amber-500 animate-pulse'}`} />
          <span className="text-sm font-medium text-slate-100">{status.message || status.status}</span>
          {status.progress != null && <span className="text-xs text-slate-400">({status.progress}%)</span>}
        </div>
      )}
      <div className={cardClass}><h3 className="text-lg font-semibold text-slate-100 mb-4">İşlemler</h3>
        <div className="flex flex-wrap gap-3">
          <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={handleCreate} disabled={creating} className={`rounded-xl bg-gradient-to-r from-indigo-500 to-violet-500 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-indigo-500/25 ${creating ? 'opacity-50' : ''}`}>{creating ? 'Oluşturuluyor...' : 'Yedekleme Başlat'}</motion.button>
          <label className={`inline-flex cursor-pointer items-center rounded-xl border border-white/[0.06] bg-white/[0.03] px-5 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.06] ${restoring ? 'cursor-not-allowed opacity-50' : ''}`}>{restoring ? 'Yükleniyor...' : 'Geri Yükle'}<input type="file" accept=".zip" onChange={handleRestore} disabled={restoring} className="hidden" /></label>
        </div>
      </div>
      <div className={cardClass}><h3 className="text-lg font-semibold text-slate-100 mb-4">Mevcut Yedekler</h3>
        {backups.length === 0 ? <p className="text-slate-400">Henüz yedek oluşturulmamış.</p> : (
          <div className="space-y-2">{backups.map((b) => (
            <div key={b.filename} className="flex items-center gap-3 rounded-xl border border-white/[0.04] bg-white/[0.02] p-4">
              <div className="flex-1"><div className="text-sm font-medium text-slate-100">{b.filename}</div><div className="text-xs text-slate-500">{new Date(b.createdAt).toLocaleString('tr-TR')} · {formatSize(b.size)}</div></div>
            </div>
          ))}</div>
        )}
      </div>
    </motion.div>
  );
};

const QueueSection: React.FC = () => {
  const [queueStatus, setQueueStatus] = useState<QueueStatus | null>(null); const [failedTasks, setFailedTasks] = useState<FailedTask[]>([]);
  const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); const [retrying, setRetrying] = useState<string | null>(null);
  const fetchData = useCallback(async () => { setLoading(true); setError(null); try { const [statusRes, failedRes] = await Promise.allSettled([queue.getStatus(), queue.getFailed()]); if (statusRes.status === 'fulfilled') setQueueStatus(statusRes.value.data?.data ?? statusRes.value.data ?? null); if (failedRes.status === 'fulfilled') setFailedTasks(failedRes.value.data?.data ?? failedRes.value.data ?? []); } catch { setError('Kuyruk bilgileri yüklenemedi.'); } finally { setLoading(false); } }, []);
  useEffect(() => { fetchData(); }, [fetchData]);
  const handleRetry = async (id: string) => { setRetrying(id); try { await queue.retryFailed(id); await fetchData(); } catch { setError('Yeniden deneme başarısız oldu.'); } finally { setRetrying(null); } };
  if (loading) return <LoadingText />;
  return (
    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-5">
      {error && <ErrorBanner message={error} onDismiss={() => setError(null)} />}
      <div className="grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-4">
        {[{ label: 'Bekleyen', value: queueStatus?.pending ?? 0, color: 'text-amber-400', g: 'from-amber-500/10 to-amber-500/5' }, { label: 'İşleniyor', value: queueStatus?.processing ?? 0, color: 'text-blue-400', g: 'from-blue-500/10 to-blue-500/5' }, { label: 'Tamamlanan', value: queueStatus?.completed ?? 0, color: 'text-emerald-400', g: 'from-emerald-500/10 to-emerald-500/5' }, { label: 'Başarısız', value: queueStatus?.failed ?? 0, color: 'text-red-400', g: 'from-red-500/10 to-red-500/5' }].map((s) => (
          <motion.div key={s.label} whileHover={{ y: -2, scale: 1.03 }} className={`overflow-hidden rounded-2xl border border-white/[0.06] bg-gradient-to-br ${s.g} p-5 backdrop-blur-xl`}>
            <div className="mb-1 text-sm text-slate-400">{s.label}</div><div className={`text-2xl font-bold ${s.color}`}>{s.value}</div>
          </motion.div>
        ))}
      </div>
      <div className="mb-4"><motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={fetchData} className="flex items-center gap-2 rounded-xl border border-white/[0.06] bg-white/[0.03] px-5 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.06]"><RefreshCw size={16} /> Yenile</motion.button></div>
      <div className={cardClass}><h3 className="text-lg font-semibold text-slate-100 mb-4">Başarısız Görevler</h3>
        {failedTasks.length === 0 ? <p className="text-slate-400">Başarısız görev bulunmuyor.</p> : (
          <div className="space-y-3">{failedTasks.map((task) => (
            <div key={task.id} className="flex items-center gap-4 rounded-xl border border-white/[0.04] bg-white/[0.02] p-4">
              <div className="min-w-0 flex-1">
                <div className="mb-1 flex items-center gap-2"><span className="text-sm font-semibold text-slate-100">{task.type}</span>{task.characterId && <span className="rounded-lg bg-white/[0.06] px-2 py-0.5 text-xs text-slate-500">{task.characterId}</span>}</div>
                {task.error && <div className="text-xs text-red-400">{task.error}</div>}
                <div className="mt-1 text-xs text-slate-500">{new Date(task.createdAt).toLocaleString('tr-TR')}</div>
              </div>
              <motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={() => handleRetry(task.id)} disabled={retrying === task.id} className="shrink-0 rounded-xl bg-gradient-to-r from-indigo-500 to-violet-500 px-5 py-2 text-sm font-semibold text-white shadow-lg shadow-indigo-500/25">{retrying === task.id ? '...' : 'Yeniden Dene'}</motion.button>
            </div>
          ))}</div>
        )}
      </div>
    </motion.div>
  );
};

const SystemSection: React.FC = () => {
  const [health, setHealth] = useState<HealthInfo | null>(null); const [errors, setErrors] = useState<SystemError[]>([]);
  const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null);
  const fetchData = useCallback(async () => { setLoading(true); setError(null); try { const [healthRes, errorsRes] = await Promise.allSettled([system.health(), system.errors()]); if (healthRes.status === 'fulfilled') setHealth(healthRes.value.data?.data ?? healthRes.value.data ?? null); if (errorsRes.status === 'fulfilled') setErrors(errorsRes.value.data?.data ?? errorsRes.value.data ?? []); } catch { setError('Sistem bilgileri yüklenemedi.'); } finally { setLoading(false); } }, []);
  useEffect(() => { fetchData(); }, [fetchData]);
  const formatUptime = (seconds?: number) => { if (!seconds) return '—'; const h = Math.floor(seconds / 3600); const m = Math.floor((seconds % 3600) / 60); return `${h}s ${m}dk`; };
  if (loading) return <LoadingText />;
  const isHealthy = health?.status === 'ok';
  return (
    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-5">
      {error && <ErrorBanner message={error} onDismiss={() => setError(null)} />}
      <div className={cardClass}><h3 className="text-lg font-semibold text-slate-100 mb-4">Sağlık Durumu</h3>
        <div className="flex items-center gap-3">
          <div className="relative"><div className={`h-4 w-4 rounded-full ${isHealthy ? 'bg-emerald-500' : 'bg-red-500'}`} />{isHealthy && <div className="absolute inset-0 animate-ping rounded-full bg-emerald-500/50" />}</div>
          <span className={`text-base font-semibold ${isHealthy ? 'text-emerald-400' : 'text-red-400'}`}>{isHealthy ? 'Sistem Çalışıyor' : 'Sorun Tespit Edildi'}</span>
        </div>
        <div className="mt-4 flex flex-wrap gap-6 text-sm text-slate-400">
          <span>Çalışma Süresi: <strong className="text-slate-200">{formatUptime(health?.uptime)}</strong></span>
          {health?.timestamp && <span>Son Kontrol: <strong className="text-slate-200">{new Date(health.timestamp).toLocaleString('tr-TR')}</strong></span>}
        </div>
        <div className="mt-4"><motion.button whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }} onClick={fetchData} className="flex items-center gap-2 rounded-xl border border-white/[0.06] bg-white/[0.03] px-5 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.06]"><RefreshCw size={16} /> Yenile</motion.button></div>
      </div>
      <div className={cardClass}><h3 className="text-lg font-semibold text-slate-100 mb-4">Son Hatalar</h3>
        {errors.length === 0 ? <p className="text-slate-400">Kayıtlı hata bulunmuyor.</p> : (
          <div className="space-y-2">{errors.map((err, i) => (
            <div key={i} className="rounded-xl border border-white/[0.04] border-l-[3px] border-l-red-500 bg-white/[0.02] p-4">
              <div className="text-sm font-medium text-red-400">{err.message}</div>
              <div className="mt-1 text-xs text-slate-500">{new Date(err.timestamp).toLocaleString('tr-TR')}{err.level && <span className="ml-2 uppercase">[{err.level}]</span>}</div>
            </div>
          ))}</div>
        )}
      </div>
    </motion.div>
  );
};

const LoadingText: React.FC = () => (<div className="flex min-h-[40vh] items-center justify-center"><div className="flex flex-col items-center gap-3"><div className="h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" /><p className="text-sm text-slate-400">Yükleniyor...</p></div></div>);
const ErrorBanner: React.FC<{ message: string; onDismiss: () => void }> = ({ message, onDismiss }) => (<div className="mb-4 flex items-center justify-between rounded-xl border border-red-500/20 bg-red-500/5 px-4 py-3 text-sm text-red-300"><span>{message}</span><button onClick={onDismiss} className="ml-3 text-lg leading-none text-red-300 transition-colors hover:text-red-200">×</button></div>);

export default Settings;