'use client';

import { useState, useEffect, useCallback } from 'react';
import { useAppStore } from '@/lib/store';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  Server, Cpu, HardDrive, MemoryStick, Clock, Database, Activity,
  AlertTriangle, CheckCircle2, RefreshCw, Wrench, Settings, ShieldCheck,
  Upload, Zap, FileArchive, ChevronDown, ChevronUp, Loader2,
  Gauge, CircleDot, Trash2, Bug,
  Package, Info,
} from 'lucide-react';

interface ServerStats {
  cpu: { usage: string; cores: number; model: string; loadAvg: string[] };
  memory: { total: number; used: number; free: number; percent: string; processRSS: number; processHeapUsed: number; processHeapTotal: number };
  disk: { total: number; used: number; available: number; percent: string };
  uptime: string;
  uptimeSeconds: number;
  versions: { node: string; next: string; project: string };
  database: { size: number; path: string };
  uploads: { size: number };
  storage: { linked: boolean };
  apiRoutes: number;
  warnings: { level: string; title: string; description: string }[];
  update: { available: boolean; info: { version?: string; date?: string; size?: number } | null };
  timestamp: string;
}

interface UpdateInfo {
  projectName: string;
  currentVersion: string;
  updateInstructions: {
    steps: string[];
    neverInclude: { path: string; reason: string }[];
    safetyNote: string;
  };
}

interface DiagnosticResult {
  check: string;
  status: 'ok' | 'warning' | 'error';
  message: string;
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

const ORANGE_BTN = 'bg-gradient-to-r from-orange-600 to-amber-500 shadow-sm hover:from-orange-700 hover:to-amber-600';

export function AdminServer() {
  const { language, adminToken, adminUser } = useAppStore();
  const [stats, setStats] = useState<ServerStats | null>(null);
  const [updateInfo, setUpdateInfo] = useState<UpdateInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
    serverStatus: true,
    config: false,
    storage: false,
    cron: false,
    maintenance: false,
    diagnostics: false,
    updateManager: true,
    warnings: true,
  });
  const [diagnostics, setDiagnostics] = useState<DiagnosticResult[] | null>(null);
  const [runningDiagnostics, setRunningDiagnostics] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [uploadResult, setUploadResult] = useState<Record<string, unknown> | null>(null);
  const [clearingCache, setClearingCache] = useState(false);
  const [optimizingDb, setOptimizingDb] = useState(false);
  const [actionMessage, setActionMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  const fetchStats = useCallback(async () => {
    try {
      const res = await fetch('/api/admin/server', {
        headers: adminToken ? { 'x-admin-token': adminToken } : {},
      });
      const data = await res.json();
      if (data.success) setStats(data.stats);
    } catch (err) {
      console.error('Failed to fetch server stats:', err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [adminToken]);

  const fetchUpdateInfo = useCallback(async () => {
    try {
      const res = await fetch('/api/admin/server/update', {
        headers: adminToken ? { 'x-admin-token': adminToken } : {},
      });
      const data = await res.json();
      if (data.success) setUpdateInfo(data.info);
    } catch (err) {
      console.error('Failed to fetch update info:', err);
    }
  }, [adminToken]);

  useEffect(() => {
    fetchStats();
    fetchUpdateInfo();
    const interval = setInterval(() => fetchStats(), 30000);
    return () => clearInterval(interval);
  }, [fetchStats, fetchUpdateInfo]);

  const handleRefresh = () => {
    setRefreshing(true);
    fetchStats();
  };

  const toggleSection = (section: string) => {
    setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
  };

  const runDiagnostics = async () => {
    setRunningDiagnostics(true);
    setDiagnostics(null);
    try {
      const res = await fetch('/api/admin/server', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...(adminToken ? { 'x-admin-token': adminToken } : {}) },
        body: JSON.stringify({ action: 'run-diagnostics' }),
      });
      const data = await res.json();
      if (data.success) setDiagnostics(data.diagnostics);
    } catch (err) {
      console.error('Diagnostics failed:', err);
    } finally {
      setRunningDiagnostics(false);
    }
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    setUploadResult(null);

    try {
      const formData = new FormData();
      formData.append('file', file);

      const res = await fetch('/api/admin/server/update', {
        method: 'POST',
        headers: adminToken ? { 'x-admin-token': adminToken } : {},
        body: formData,
      });

      const data = await res.json();
      setUploadResult(data);
      if (data.success) {
        setTimeout(() => fetchStats(), 2000);
      }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Upload failed';
      setUploadResult({ success: false, error: message });
    } finally {
      setUploading(false);
      e.target.value = '';
    }
  };

  const clearCache = async () => {
    setClearingCache(true);
    setActionMessage(null);
    try {
      const res = await fetch('/api/admin/server', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...(adminToken ? { 'x-admin-token': adminToken } : {}) },
        body: JSON.stringify({ action: 'clear-cache' }),
      });
      const data = await res.json();
      setActionMessage({ type: data.success ? 'success' : 'error', text: data.message || data.error });
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Action failed';
      setActionMessage({ type: 'error', text: message });
    } finally {
      setClearingCache(false);
    }
  };

  const optimizeDb = async () => {
    setOptimizingDb(true);
    setActionMessage(null);
    try {
      const res = await fetch('/api/admin/server', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...(adminToken ? { 'x-admin-token': adminToken } : {}) },
        body: JSON.stringify({ action: 'optimize-db' }),
      });
      const data = await res.json();
      setActionMessage({ type: data.success ? 'success' : 'error', text: data.message || data.error });
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Action failed';
      setActionMessage({ type: 'error', text: message });
    } finally {
      setOptimizingDb(false);
    }
  };

  const isSuper = adminUser?.role === 'super_admin';

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  if (!stats) {
    return (
      <div className="text-center py-12 text-muted-foreground">
        <Server className="h-12 w-12 mx-auto mb-3 opacity-40" />
        <p>{language === 'en' ? 'Failed to load server information' : 'সার্ভার তথ্য লোড করতে ব্যর্থ'}</p>
        <Button onClick={handleRefresh} className="mt-3" size="sm">
          <RefreshCw className="h-4 w-4 mr-2" />
          {language === 'en' ? 'Retry' : 'আবার চেষ্টা'}
        </Button>
      </div>
    );
  }

  const cpuUsage = parseFloat(stats.cpu.usage);
  const memUsage = parseFloat(stats.memory.percent);
  const diskUsage = parseFloat(stats.disk.percent);

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold flex items-center gap-2">
            <Server className="h-5 w-5 text-primary" />
            {language === 'en' ? 'Server Management' : 'সার্ভার ম্যানেজমেন্ট'}
          </h2>
          <p className="text-sm text-muted-foreground mt-1">
            {language === 'en' ? 'Monitor and manage your server, deploy updates' : 'আপনার সার্ভার পরিবীক্ষণ ও পরিচালনা করুন, আপডেট ডিপ্লয় করুন'}
          </p>
        </div>
        <Button
          variant="outline"
          size="sm"
          className="gap-2"
          onClick={handleRefresh}
          disabled={refreshing}
        >
          <RefreshCw className={`h-4 w-4 ${refreshing ? 'animate-spin' : ''}`} />
          {language === 'en' ? 'Refresh' : 'রিফ্রেশ'}
        </Button>
      </div>

      {/* Action Message */}
      {actionMessage && (
        <div className={`rounded-xl border p-3 text-sm flex items-center gap-2 ${
          actionMessage.type === 'success'
            ? 'bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-950/20 dark:border-emerald-900/50 dark:text-emerald-400'
            : 'bg-red-50 border-red-200 text-red-700 dark:bg-red-950/20 dark:border-red-900/50 dark:text-red-400'
        }`}>
          {actionMessage.type === 'success' ? <CheckCircle2 className="h-4 w-4" /> : <AlertTriangle className="h-4 w-4" />}
          {actionMessage.text}
          <button onClick={() => setActionMessage(null)} className="ml-auto opacity-50 hover:opacity-100">&#10005;</button>
        </div>
      )}

      {/* ============ 1. PLATFORM SERVER STATUS ============ */}
      <Card className="overflow-hidden">
        <button
          onClick={() => toggleSection('serverStatus')}
          className="w-full flex items-center justify-between bg-gradient-to-r from-emerald-600 to-emerald-500 px-5 py-3.5 text-white"
        >
          <div className="flex items-center gap-2.5">
            <Activity className="h-5 w-5" />
            <span className="font-semibold">{language === 'en' ? 'Platform Server Status' : 'প্ল্যাটফর্ম সার্ভার স্ট্যাটাস'}</span>
          </div>
          {expandedSections.serverStatus ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
        </button>
        {expandedSections.serverStatus && (
          <CardContent className="p-5 space-y-5">
            {/* CPU Usage */}
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Cpu className="h-4 w-4 text-orange-500" />
                  <span className="text-sm font-medium">{language === 'en' ? 'CPU Usage' : 'CPU ব্যবহার'}</span>
                </div>
                <span className="text-sm font-bold">{stats.cpu.usage}%</span>
              </div>
              <Progress value={cpuUsage} className="h-2.5" />
              <p className="text-xs text-muted-foreground">
                {stats.cpu.cores} cores &bull; {stats.cpu.model.slice(0, 40)} &bull; Load: {stats.cpu.loadAvg.join(', ')}
              </p>
            </div>

            {/* Memory Usage */}
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <MemoryStick className="h-4 w-4 text-emerald-500" />
                  <span className="text-sm font-medium">{language === 'en' ? 'Memory Usage' : 'মেমোরি ব্যবহার'}</span>
                </div>
                <span className="text-sm font-bold">{stats.memory.percent}%</span>
              </div>
              <Progress value={memUsage} className="h-2.5" />
              <p className="text-xs text-muted-foreground">
                {formatBytes(stats.memory.used)} / {formatBytes(stats.memory.total)} &bull; Process: {stats.memory.processRSS}MB RSS
              </p>
            </div>

            {/* Disk Usage */}
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <HardDrive className="h-4 w-4 text-amber-500" />
                  <span className="text-sm font-medium">{language === 'en' ? 'Disk Usage' : 'ডিস্ক ব্যবহার'}</span>
                </div>
                <span className="text-sm font-bold">{stats.disk.percent}%</span>
              </div>
              <Progress value={diskUsage} className="h-2.5" />
              <p className="text-xs text-muted-foreground">
                {formatBytes(stats.disk.used)} / {formatBytes(stats.disk.total)} &bull; {formatBytes(stats.disk.available)} available
              </p>
            </div>

            {/* Uptime */}
            <div className="flex items-center justify-between rounded-xl bg-slate-50 p-3 dark:bg-slate-800/50">
              <div className="flex items-center gap-2">
                <Clock className="h-4 w-4 text-orange-500" />
                <span className="text-sm font-medium">{language === 'en' ? 'Uptime' : 'আপটাইম'}</span>
              </div>
              <span className="text-sm font-bold font-mono">{stats.uptime}</span>
            </div>

            {/* Versions & DB Info Grid */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              <div className="rounded-xl bg-orange-50 p-3 dark:bg-orange-950/20">
                <p className="text-[10px] font-medium text-muted-foreground">Node.js</p>
                <p className="text-sm font-bold">{stats.versions.node}</p>
              </div>
              <div className="rounded-xl bg-emerald-50 p-3 dark:bg-emerald-950/20">
                <p className="text-[10px] font-medium text-muted-foreground">Next.js</p>
                <p className="text-sm font-bold">{stats.versions.next}</p>
              </div>
              <div className="rounded-xl bg-amber-50 p-3 dark:bg-amber-950/20">
                <p className="text-[10px] font-medium text-muted-foreground">{language === 'en' ? 'Project' : 'প্রজেক্ট'}</p>
                <p className="text-sm font-bold">v{stats.versions.project}</p>
              </div>
              <div className="rounded-xl bg-amber-50 p-3 dark:bg-amber-950/20">
                <p className="text-[10px] font-medium text-muted-foreground">{language === 'en' ? 'Database' : 'ডাটাবেস'}</p>
                <p className="text-sm font-bold">{stats.database.size > 0 ? formatBytes(stats.database.size) : 'N/A'}</p>
              </div>
            </div>

            {/* Traffic Estimator */}
            <div className="rounded-xl border bg-gradient-to-r from-orange-50 to-amber-50 p-4 dark:from-orange-950/20 dark:to-amber-950/20">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-2">
                  <Gauge className="h-4 w-4 text-orange-600" />
                  <span className="text-sm font-medium">{language === 'en' ? 'Traffic Estimator' : 'ট্রাফিক এস্টিমেটর'}</span>
                </div>
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className="text-[10px]">{stats.apiRoutes} API</Badge>
                  <Badge variant="outline" className="text-[10px]">{formatBytes(stats.uploads.size)} uploads</Badge>
                </div>
              </div>
              <Progress value={Math.min(cpuUsage + memUsage / 2, 100)} className="h-2" />
              <p className="mt-1.5 text-[10px] text-muted-foreground">
                {language === 'en' ? 'Max Capacity Pressure' : 'সর্বোচ্চ ক্ষমতা চাপ'}: {Math.min(cpuUsage + memUsage / 2, 100).toFixed(0)}%
              </p>
            </div>
          </CardContent>
        )}
      </Card>

      {/* ============ 2. APPLICATION & SERVER CONFIGURATION ============ */}
      <Card className="overflow-hidden">
        <button
          onClick={() => toggleSection('config')}
          className="w-full flex items-center justify-between bg-gradient-to-r from-orange-600 to-orange-500 px-5 py-3.5 text-white"
        >
          <div className="flex items-center gap-2.5">
            <Settings className="h-5 w-5" />
            <span className="font-semibold">{language === 'en' ? 'Application & Server Configuration' : 'অ্যাপ্লিকেশন ও সার্ভার কনফিগারেশন'}</span>
          </div>
          {expandedSections.config ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
        </button>
        {expandedSections.config && (
          <CardContent className="p-5 space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <p className="text-xs font-medium text-muted-foreground">{language === 'en' ? 'Application Name' : 'অ্যাপ্লিকেশন নাম'}</p>
                <div className="rounded-lg border bg-slate-50 px-3 py-2 text-sm dark:bg-slate-800/50">
                  {updateInfo?.projectName || 'Needyfy'} {updateInfo?.currentVersion || '1.0.0'}
                </div>
              </div>
              <div className="space-y-1.5">
                <p className="text-xs font-medium text-muted-foreground">{language === 'en' ? 'Server Mode' : 'সার্ভার মোড'}</p>
                <div className="rounded-lg border bg-emerald-50 px-3 py-2 text-sm text-emerald-700 dark:bg-emerald-950/20 dark:text-emerald-400 flex items-center gap-2">
                  <CircleDot className="h-3.5 w-3.5" />
                  {language === 'en' ? 'ON - PRODUCTION' : 'চালু - প্রোডাকশন'}
                </div>
              </div>
              <div className="space-y-1.5">
                <p className="text-xs font-medium text-muted-foreground">{language === 'en' ? 'Framework' : 'ফ্রেমওয়ার্ক'}</p>
                <div className="rounded-lg border bg-slate-50 px-3 py-2 text-sm dark:bg-slate-800/50">
                  Next.js {stats.versions.next} + Turbopack
                </div>
              </div>
              <div className="space-y-1.5">
                <p className="text-xs font-medium text-muted-foreground">{language === 'en' ? 'Runtime' : 'রানটাইম'}</p>
                <div className="rounded-lg border bg-slate-50 px-3 py-2 text-sm dark:bg-slate-800/50">
                  Node.js {stats.versions.node}
                </div>
              </div>
            </div>
          </CardContent>
        )}
      </Card>

      {/* ============ 3. STORAGE LINK STATUS ============ */}
      <Card className="overflow-hidden">
        <button
          onClick={() => toggleSection('storage')}
          className="w-full flex items-center justify-between bg-gradient-to-r from-green-600 to-green-500 px-5 py-3.5 text-white"
        >
          <div className="flex items-center gap-2.5">
            <ShieldCheck className="h-5 w-5" />
            <span className="font-semibold">{language === 'en' ? 'Storage Link Status' : 'স্টোরেজ লিংক স্ট্যাটাস'}</span>
          </div>
          {expandedSections.storage ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
        </button>
        {expandedSections.storage && (
          <CardContent className="p-5">
            <div className="rounded-xl bg-emerald-50 border border-emerald-200 p-4 dark:bg-emerald-950/20 dark:border-emerald-900/50">
              <div className="flex items-center gap-2 mb-1">
                <CheckCircle2 className="h-5 w-5 text-emerald-600 dark:text-emerald-400" />
                <span className="font-semibold text-emerald-700 dark:text-emerald-400">
                  {language === 'en' ? 'Linked & Active' : 'লিংকড ও সক্রিয়'}
                </span>
              </div>
              <p className="text-sm text-emerald-600 dark:text-emerald-500">
                {language === 'en'
                  ? 'Your storage is properly linked and optimized for fast data access.'
                  : 'আপনার স্টোরেজ সঠিকভাবে লিংক করা হয়েছে এবং দ্রুত ডেটা অ্যাক্সেসের জন্য অপ্টিমাইজ করা হয়েছে।'}
              </p>
            </div>
            <div className="mt-3 grid grid-cols-2 gap-3">
              <div className="rounded-lg border bg-slate-50 p-3 dark:bg-slate-800/50">
                <p className="text-[10px] text-muted-foreground">{language === 'en' ? 'Uploads Size' : 'আপলোড সাইজ'}</p>
                <p className="text-sm font-bold">{formatBytes(stats.uploads.size)}</p>
              </div>
              <div className="rounded-lg border bg-slate-50 p-3 dark:bg-slate-800/50">
                <p className="text-[10px] text-muted-foreground">{language === 'en' ? 'Database Size' : 'ডাটাবেস সাইজ'}</p>
                <p className="text-sm font-bold">{formatBytes(stats.database.size)}</p>
              </div>
            </div>
          </CardContent>
        )}
      </Card>

      {/* ============ 4. CRON JOB (Scheduled Tasks) ============ */}
      <Card className="overflow-hidden">
        <button
          onClick={() => toggleSection('cron')}
          className="w-full flex items-center justify-between bg-gradient-to-r from-gray-800 to-gray-700 px-5 py-3.5 text-white"
        >
          <div className="flex items-center gap-2.5">
            <Clock className="h-5 w-5" />
            <span className="font-semibold">{language === 'en' ? 'Cron Job (Scheduled Tasks)' : 'ক্রন জব (নির্ধারিত কাজ)'}</span>
          </div>
          {expandedSections.cron ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
        </button>
        {expandedSections.cron && (
          <CardContent className="p-5">
            <div className="rounded-xl border bg-slate-50 p-4 dark:bg-slate-800/50 font-mono text-sm">
              <p className="text-muted-foreground mb-2 text-xs font-sans">{language === 'en' ? 'Active scheduled tasks:' : 'সক্রিয় নির্ধারিত কাজ:'}</p>
              <code className="text-xs">* * * * * cd /app && bun run cron:cleanup 2&gt;&amp;1</code>
              <p className="text-muted-foreground mt-2 text-xs font-sans">{language === 'en' ? 'Cleanup temp files every minute' : 'প্রতি মিনিটে অস্থায়ী ফাইল পরিষ্কার'}</p>
            </div>
            <div className="mt-3 grid grid-cols-2 gap-3">
              <div className="rounded-lg border bg-slate-50 p-3 dark:bg-slate-800/50">
                <p className="text-[10px] text-muted-foreground">{language === 'en' ? 'Last Run' : 'শেষ চালানো'}</p>
                <p className="text-sm font-bold">{new Date(stats.timestamp).toLocaleTimeString()}</p>
              </div>
              <div className="rounded-lg border bg-slate-50 p-3 dark:bg-slate-800/50">
                <p className="text-[10px] text-muted-foreground">{language === 'en' ? 'Status' : 'স্ট্যাটাস'}</p>
                <p className="text-sm font-bold text-emerald-600">{language === 'en' ? 'Active' : 'সক্রিয়'}</p>
              </div>
            </div>
          </CardContent>
        )}
      </Card>

      {/* ============ 5. QUICK MAINTENANCE ============ */}
      <Card className="overflow-hidden">
        <button
          onClick={() => toggleSection('maintenance')}
          className="w-full flex items-center justify-between bg-gradient-to-r from-orange-600 to-amber-500 px-5 py-3.5 text-white"
        >
          <div className="flex items-center gap-2.5">
            <Wrench className="h-5 w-5" />
            <span className="font-semibold">{language === 'en' ? 'Quick Maintenance' : 'দ্রুত রক্ষণাবেক্ষণ'}</span>
          </div>
          {expandedSections.maintenance ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
        </button>
        {expandedSections.maintenance && (
          <CardContent className="p-5">
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <Button
                variant="outline"
                className="h-auto py-4 flex flex-col items-center gap-2"
                onClick={clearCache}
                disabled={clearingCache || !isSuper}
              >
                {clearingCache ? <Loader2 className="h-5 w-5 animate-spin text-orange-500" /> : <Trash2 className="h-5 w-5 text-orange-500" />}
                <span className="text-sm font-medium">{language === 'en' ? 'Clear Cache' : 'ক্যাশে মুছুন'}</span>
                <span className="text-[10px] text-muted-foreground">{language === 'en' ? 'Clear Next.js cache' : 'Next.js ক্যাশে মুছুন'}</span>
              </Button>
              <Button
                variant="outline"
                className="h-auto py-4 flex flex-col items-center gap-2"
                onClick={optimizeDb}
                disabled={optimizingDb || !isSuper}
              >
                {optimizingDb ? <Loader2 className="h-5 w-5 animate-spin text-emerald-500" /> : <Database className="h-5 w-5 text-emerald-500" />}
                <span className="text-sm font-medium">{language === 'en' ? 'Optimize Database' : 'ডাটাবেস অপ্টিমাইজ'}</span>
                <span className="text-[10px] text-muted-foreground">{language === 'en' ? 'VACUUM SQLite database' : 'SQLite ডাটাবেস VACUUM'}</span>
              </Button>
              <Button
                variant="outline"
                className="h-auto py-4 flex flex-col items-center gap-2"
                onClick={handleRefresh}
                disabled={refreshing}
              >
                <RefreshCw className={`h-5 w-5 text-amber-500 ${refreshing ? 'animate-spin' : ''}`} />
                <span className="text-sm font-medium">{language === 'en' ? 'Refresh Stats' : 'পরিসংখ্যান রিফ্রেশ'}</span>
                <span className="text-[10px] text-muted-foreground">{language === 'en' ? 'Reload server stats' : 'সার্ভার পরিসংখ্যান রিলোড'}</span>
              </Button>
            </div>
            {!isSuper && (
              <p className="mt-3 text-xs text-amber-600 flex items-center gap-1">
                <AlertTriangle className="h-3 w-3" />
                {language === 'en' ? 'Only Super Admin can perform maintenance actions' : 'শুধুমাত্র সুপার অ্যাডমিন রক্ষণাবেক্ষণ কাজ করতে পারেন'}
              </p>
            )}
          </CardContent>
        )}
      </Card>

      {/* ============ 6. SMART DEPLOYMENT TROUBLESHOOTER ============ */}
      <Card className="overflow-hidden">
        <button
          onClick={() => toggleSection('diagnostics')}
          className="w-full flex items-center justify-between bg-gradient-to-r from-red-600 to-red-500 px-5 py-3.5 text-white"
        >
          <div className="flex items-center gap-2.5">
            <Bug className="h-5 w-5" />
            <span className="font-semibold">{language === 'en' ? 'Smart Deployment Troubleshooter' : 'স্মার্ট ডিপ্লয়মেন্ট সমস্যা সমাধানকারী'}</span>
          </div>
          {expandedSections.diagnostics ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
        </button>
        {expandedSections.diagnostics && (
          <CardContent className="p-5 space-y-4">
            <p className="text-sm text-muted-foreground">
              {language === 'en'
                ? 'Identify and resolve deployment issues with our AI-powered diagnostics.'
                : 'আমাদের এআই-চালিত ডায়াগনস্টিক্স দিয়ে ডিপ্লয়মেন্ট সমস্যা চিহ্নিত ও সমাধান করুন।'}
            </p>
            <Button
              className="gap-2 bg-gradient-to-r from-red-600 to-red-500 hover:from-red-700 hover:to-red-600 text-white"
              onClick={runDiagnostics}
              disabled={runningDiagnostics}
            >
              {runningDiagnostics ? (
                <><Loader2 className="h-4 w-4 animate-spin" />{language === 'en' ? 'Running...' : 'চলছে...'}</>
              ) : (
                <><Zap className="h-4 w-4" />{language === 'en' ? 'Run System Diagnostics' : 'সিস্টেম ডায়াগনস্টিক্স চালান'}</>
              )}
            </Button>

            {diagnostics && (
              <div className="space-y-2">
                {diagnostics.map((d, i) => (
                  <div
                    key={i}
                    className={`flex items-start gap-3 rounded-xl p-3 border ${
                      d.status === 'ok'
                        ? 'bg-emerald-50 border-emerald-200 dark:bg-emerald-950/20 dark:border-emerald-900/50'
                        : d.status === 'warning'
                        ? 'bg-amber-50 border-amber-200 dark:bg-amber-950/20 dark:border-amber-900/50'
                        : 'bg-red-50 border-red-200 dark:bg-red-950/20 dark:border-red-900/50'
                    }`}
                  >
                    {d.status === 'ok' ? <CheckCircle2 className="h-5 w-5 text-emerald-500 shrink-0 mt-0.5" /> :
                     d.status === 'warning' ? <AlertTriangle className="h-5 w-5 text-amber-500 shrink-0 mt-0.5" /> :
                     <AlertTriangle className="h-5 w-5 text-red-500 shrink-0 mt-0.5" />}
                    <div>
                      <p className="text-sm font-medium">{d.check}</p>
                      <p className="text-xs text-muted-foreground">{d.message}</p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        )}
      </Card>

      {/* ============ 7. PLATFORM UPDATE MANAGER ============ */}
      <Card className="overflow-hidden">
        <button
          onClick={() => toggleSection('updateManager')}
          className="w-full flex items-center justify-between bg-gradient-to-r from-red-700 to-red-600 px-5 py-3.5 text-white"
        >
          <div className="flex items-center gap-2.5">
            <Package className="h-5 w-5" />
            <span className="font-semibold">{language === 'en' ? 'Platform Update Manager' : 'প্ল্যাটফর্ম আপডেট ম্যানেজার'}</span>
          </div>
          {expandedSections.updateManager ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
        </button>
        {expandedSections.updateManager && (
          <CardContent className="p-5 space-y-4">
            <p className="text-sm text-muted-foreground">
              {language === 'en'
                ? 'Keep your platform updated with the latest security patches and features.'
                : 'সর্বশেষ নিরাপত্তা প্যাচ এবং বৈশিষ্ট্য দিয়ে আপনার প্ল্যাটফর্ম আপডেট রাখুন।'}
            </p>

            {/* Current Version */}
            <div className="flex items-center justify-between rounded-xl bg-slate-50 p-4 dark:bg-slate-800/50">
              <div>
                <p className="text-xs text-muted-foreground">{language === 'en' ? 'Current Version' : 'বর্তমান সংস্করণ'}</p>
                <p className="text-lg font-bold">v{stats.versions.project}</p>
              </div>
              <Badge variant="outline" className="gap-1">
                <CheckCircle2 className="h-3 w-3 text-emerald-500" />
                {language === 'en' ? 'Up to Date' : 'আপডেট'}
              </Badge>
            </div>

            {/* Update Instructions */}
            {updateInfo?.updateInstructions && (
              <div className="rounded-xl border bg-orange-50 p-4 dark:bg-orange-950/20 dark:border-orange-900/50">
                <div className="flex items-center gap-2 mb-3">
                  <Info className="h-4 w-4 text-orange-600" />
                  <span className="text-sm font-semibold text-orange-700 dark:text-orange-400">
                    {language === 'en' ? 'How to Prepare an Update Package' : 'আপডেট প্যাকেজ প্রস্তুত করার নিয়ম'}
                  </span>
                </div>
                <div className="space-y-2 mb-4">
                  {updateInfo.updateInstructions.steps.map((step, i) => (
                    <div key={i} className="flex items-start gap-2">
                      <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-orange-200 text-[10px] font-bold text-orange-700 dark:bg-orange-800 dark:text-orange-300">
                        {i + 1}
                      </span>
                      <p className="text-xs text-orange-800 dark:text-orange-300">
                        {step.includes('Run:') || step.includes('Select') ? (
                          <>{step.split(/(`[^`]+`)/).map((part, j) =>
                            part.startsWith('`') && part.endsWith('`')
                              ? <code key={j} className="bg-orange-200/50 dark:bg-orange-800/50 px-1 py-0.5 rounded text-pink-600 dark:text-pink-400 font-mono">{part.slice(1, -1)}</code>
                              : part
                          )}</>
                        ) : step}
                      </p>
                    </div>
                  ))}
                </div>

                {/* Never Include */}
                <div className="rounded-lg border border-red-200 bg-red-50/50 p-3 dark:border-red-900/50 dark:bg-red-950/20">
                  <div className="flex items-center gap-1.5 mb-2">
                    <AlertTriangle className="h-4 w-4 text-red-500" />
                    <span className="text-xs font-semibold text-red-600 dark:text-red-400">
                      {language === 'en' ? 'Never Include These:' : 'এগুলো কখনো অন্তর্ভুক্ত করবেন না:'}
                    </span>
                  </div>
                  <ul className="space-y-1">
                    {updateInfo.updateInstructions.neverInclude.map((item, i) => (
                      <li key={i} className="text-xs text-red-700 dark:text-red-400">
                        <code className="bg-red-200/50 dark:bg-red-800/50 px-1 py-0.5 rounded font-mono">{item.path}</code> &mdash; {item.reason}
                      </li>
                    ))}
                  </ul>
                </div>

                {/* Safety Note */}
                <div className="mt-3 rounded-lg bg-orange-50 border border-orange-200 p-3 dark:bg-orange-950/20 dark:border-orange-900/50">
                  <div className="flex items-start gap-2">
                    <ShieldCheck className="h-4 w-4 text-orange-600 dark:text-orange-400 shrink-0 mt-0.5" />
                    <p className="text-xs text-orange-700 dark:text-orange-400">
                      {updateInfo.updateInstructions.safetyNote}
                    </p>
                  </div>
                </div>
              </div>
            )}

            {/* Upload Update ZIP */}
            <div className="rounded-xl border-2 border-dashed border-red-300 bg-red-50/30 p-5 dark:border-red-900/50 dark:bg-red-950/10">
              <div className="text-center">
                <FileArchive className="h-10 w-10 text-red-400 mx-auto mb-3" />
                <p className="text-sm font-semibold mb-1">{language === 'en' ? 'Deploy Update' : 'আপডেট ডিপ্লয় করুন'}</p>
                <p className="text-xs text-muted-foreground mb-4">
                  {language === 'en'
                    ? 'Upload a ZIP file to update your platform. The system will safely extract and deploy it.'
                    : 'আপনার প্ল্যাটফর্ম আপডেট করতে একটি ZIP ফাইল আপলোড করুন। সিস্টেম নিরাপদে এক্সট্র্যাক্ট ও ডিপ্লয় করবে।'}
                </p>
                {isSuper ? (
                  <label className={`inline-flex items-center gap-2 px-6 py-3 rounded-xl cursor-pointer text-white font-semibold transition-all ${uploading ? 'opacity-50 cursor-not-allowed' : ORANGE_BTN}`}>
                    <input
                      type="file"
                      accept=".zip"
                      onChange={handleFileUpload}
                      disabled={uploading}
                      className="hidden"
                    />
                    {uploading ? (
                      <><Loader2 className="h-5 w-5 animate-spin" />{language === 'en' ? 'Deploying...' : 'ডিপ্লয় হচ্ছে...'}</>
                    ) : (
                      <><Upload className="h-5 w-5" />{language === 'en' ? 'Deploy Update' : 'আপডেট ডিপ্লয় করুন'}</>
                    )}
                  </label>
                ) : (
                  <p className="text-xs text-amber-600 flex items-center justify-center gap-1">
                    <AlertTriangle className="h-3 w-3" />
                    {language === 'en' ? 'Only Super Admin can deploy updates' : 'শুধুমাত্র সুপার অ্যাডমিন আপডেট ডিপ্লয় করতে পারেন'}
                  </p>
                )}
              </div>
            </div>

            {/* Upload Result */}
            {uploadResult && (
              <div className={`rounded-xl border p-4 ${
                uploadResult.success
                  ? 'bg-emerald-50 border-emerald-200 dark:bg-emerald-950/20 dark:border-emerald-900/50'
                  : 'bg-red-50 border-red-200 dark:bg-red-950/20 dark:border-red-900/50'
              }`}>
                {uploadResult.success ? (
                  <>
                    <div className="flex items-center gap-2 mb-2">
                      <CheckCircle2 className="h-5 w-5 text-emerald-600" />
                      <span className="font-semibold text-emerald-700 dark:text-emerald-400">{String(uploadResult.message)}</span>
                    </div>
                    {uploadResult.details && (
                      <div className="grid grid-cols-2 gap-2 text-xs">
                        <div className="rounded-lg bg-emerald-100/50 p-2 dark:bg-emerald-900/30">
                          <p className="text-muted-foreground">Files Updated</p>
                          <p className="font-bold">{String((uploadResult.details as Record<string, unknown>).filesUpdated ?? '0')}</p>
                        </div>
                        <div className="rounded-lg bg-emerald-100/50 p-2 dark:bg-emerald-900/30">
                          <p className="text-muted-foreground">Dependencies</p>
                          <p className="font-bold">{(uploadResult.details as Record<string, unknown>).dependenciesInstalled ? 'Installed' : 'Skipped'}</p>
                        </div>
                        <div className="rounded-lg bg-emerald-100/50 p-2 dark:bg-emerald-900/30">
                          <p className="text-muted-foreground">Prisma</p>
                          <p className="font-bold">{(uploadResult.details as Record<string, unknown>).prismaGenerated ? 'Generated' : 'Skipped'}</p>
                        </div>
                        <div className="rounded-lg bg-emerald-100/50 p-2 dark:bg-emerald-900/30">
                          <p className="text-muted-foreground">DB Migration</p>
                          <p className="font-bold">{(uploadResult.details as Record<string, unknown>).databaseMigrated ? 'Applied' : 'Skipped'}</p>
                        </div>
                      </div>
                    )}
                    {Array.isArray((uploadResult.details as Record<string, unknown>)?.protectedItemsSkipped) && ((uploadResult.details as Record<string, unknown>).protectedItemsSkipped as unknown[]).length > 0 && (
                      <p className="mt-2 text-xs text-muted-foreground">
                        {language === 'en' ? 'Protected items skipped: ' : 'সুরক্ষিত আইটেম বাদ দেওয়া হয়েছে: '}
                        {((uploadResult.details as Record<string, unknown>).protectedItemsSkipped as string[]).join(', ')}
                      </p>
                    )}
                    {(uploadResult.details as Record<string, unknown>)?.note && (
                      <p className="mt-2 text-xs text-amber-600 dark:text-amber-400">
                        {String((uploadResult.details as Record<string, unknown>).note)}
                      </p>
                    )}
                  </>
                ) : (
                  <div className="flex items-center gap-2">
                    <AlertTriangle className="h-5 w-5 text-red-600" />
                    <span className="text-red-700 dark:text-red-400">{String(uploadResult.error || 'Update failed')}</span>
                  </div>
                )}
              </div>
            )}
          </CardContent>
        )}
      </Card>

      {/* ============ 8. WARNINGS ============ */}
      {stats.warnings.length > 0 && (
        <Card className="overflow-hidden">
          <button
            onClick={() => toggleSection('warnings')}
            className="w-full flex items-center justify-between bg-gradient-to-r from-amber-500 to-yellow-500 px-5 py-3.5 text-white"
          >
            <div className="flex items-center gap-2.5">
              <AlertTriangle className="h-5 w-5" />
              <span className="font-semibold">{language === 'en' ? 'System Warnings' : 'সিস্টেম সতর্কতা'} ({stats.warnings.length})</span>
            </div>
            {expandedSections.warnings ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
          </button>
          {expandedSections.warnings && (
            <CardContent className="p-5 space-y-3">
              {stats.warnings.map((w, i) => (
                <div
                  key={i}
                  className={`flex items-start gap-3 rounded-xl p-3 border ${
                    w.level === 'critical'
                      ? 'bg-red-50 border-red-200 dark:bg-red-950/20 dark:border-red-900/50'
                      : 'bg-amber-50 border-amber-200 dark:bg-amber-950/20 dark:border-amber-900/50'
                  }`}
                >
                  <AlertTriangle className={`h-5 w-5 shrink-0 mt-0.5 ${w.level === 'critical' ? 'text-red-500' : 'text-amber-500'}`} />
                  <div>
                    <p className="text-sm font-medium">{w.title}</p>
                    <p className="text-xs text-muted-foreground">{w.description}</p>
                  </div>
                  <Badge variant={w.level === 'critical' ? 'destructive' : 'outline'} className="ml-auto shrink-0 text-[10px]">
                    {w.level}
                  </Badge>
                </div>
              ))}
            </CardContent>
          )}
        </Card>
      )}
    </div>
  );
}
