import { useState, useCallback, useEffect } from 'react'

import { Badge } from "./components/ui/badge"
import { Tabs, TabsContent } from "./components/ui/tabs"
import { toast } from "sonner"
import {
  CheckCircle2,
  RefreshCw,
  UserPlus,
  Database,
  Server,
  Clock,
  Wrench,
  ShieldCheck,
  AlertCircle,
  Info,
  XCircle,
  ShieldAlert,
  Copy,
  Zap,
  Layout,
  ChevronUp,
  Activity
} from 'lucide-react'
import {
  SettingCard,
  FlatTabs,
  SettingsLayout,
  SettingsHeader,
  AdminButton,
  SecondaryButton,
  SuccessButton,
  ModernCardHeader
} from "./components/ui/settings-ui"

import type { DashboardData, SystemData } from './types';


export default function SystemInfo({ data: dashboardData }: { data: DashboardData }) {
  const [data, setData] = useState<SystemData | undefined>(dashboardData?.systemInfo)
  const [loading, setLoading] = useState(!dashboardData?.systemInfo)
  const [activeTab, setActiveTab] = useState('wordpress')
  const [activeAction, setActiveAction] = useState<string | null>(null)
  const [showAllIssues, setShowAllIssues] = useState(false)

  // Adjust state during render if props change
  const [prevDashboardData, setPrevDashboardData] = useState(dashboardData);
  if (dashboardData !== prevDashboardData) {
    setPrevDashboardData(dashboardData);
    if (dashboardData?.systemInfo) {
      setData(dashboardData.systemInfo);
      setLoading(false);
    }
  }

  const t = useCallback((key: string, fallback: string): string => {
    const val = (dashboardData.i18n as Record<string, unknown>)?.[key];
    return typeof val === 'string' ? val : fallback;
  }, [dashboardData.i18n]);

  const refreshStatus = useCallback(async () => {
    setLoading(true)
    setActiveAction('refresh')
    try {
      const res = await fetch(`${dashboardData.global.apiRestUrl}/system/status`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        }
      })
      const json = await res.json()
      if (json.success) {
        setData(json.data)
        toast.success(t('refreshSuccess', 'Status refreshed'))
      }
    } catch {
      toast.error('Failed to refresh status')
    } finally {
      setLoading(false)
      setActiveAction(null)
    }
  }, [dashboardData, t])

  useEffect(() => {
    if (!data && dashboardData?.ajaxUrl) {
      const timer = setTimeout(() => {
        refreshStatus();
      }, 0);
      return () => clearTimeout(timer);
    }
  }, [data, dashboardData?.ajaxUrl, refreshStatus])


  const isRtl = dashboardData?.rtl || document.documentElement.dir === 'rtl'

  if (!data) return null;

  const syncUsers = async () => {
    setLoading(true)
    setActiveAction('sync')
    try {
      const res = await fetch(`${dashboardData.global.apiRestUrl}/system/sync-users`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        }
      })
      await res.json()
      toast.success(t('syncSuccess', 'User sync complete'))
      refreshStatus()
    } catch {
      toast.error('User sync failed')
    } finally {
      setLoading(false)
      setActiveAction(null)
    }
  }

  const repairAll = async () => {
    setLoading(true)
    setActiveAction('repairAll')
    try {
      const res = await fetch(`${dashboardData.global.apiRestUrl}/system/repair`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        }
      })
      const json = await res.json()
      if (json.success) {
        setData(json.data)
        toast.success(t('repairSuccess', 'All issues repaired'))
      }
    } catch {
      toast.error('Failed to repair issues')
    } finally {
      setLoading(false)
      setActiveAction(null)
    }
  }

  const handleDbAction = async (action: 'truncate' | 'delete' | 'create' | 'repair', table: string) => {
    const confirmMsg = action === 'delete' ? t('confirmDeleteTable', 'Are you sure?') : t('confirmEmptyTable', 'Are you sure?');
    if (['truncate', 'delete'].includes(action) && !confirm(`${confirmMsg} (${table})`)) return

    setLoading(true)
    try {
      const res = await fetch(`${dashboardData.global.apiRestUrl}/system/db/${action === 'delete' ? 'drop' : action}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({ table })
      })
      const json = await res.json()
      if (json.success) {
        toast.success(json.data?.message || 'Action executed')
        refreshStatus()
      } else {
        toast.error(json.data?.message || 'Action failed')
      }
    } catch {
      toast.error('Network error executing database action')
    } finally {
      setLoading(false)
    }
  }

  const handleScheduleCron = async (hook: string) => {
    setLoading(true)
    try {
      const res = await fetch(`${dashboardData.global.apiRestUrl}/system/schedule-cron`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({ hook })
      })
      const json = await res.json()
      if (json.success) {
        toast.success(json.data?.message || 'Task scheduled')
        refreshStatus()
      } else {
        toast.error(json.data?.message || 'Failed to schedule task')
      }
    } catch {
      toast.error('Failed to schedule task')
    } finally {
      setLoading(false)
    }
  }

  const copyForSupport = () => {
    if (!data) return
    let text = `=== WAWP SYSTEM INFO REPORT ===\n`
    text += `Generated at: ${new Date().toLocaleString()}\n`
    text += `Status: ${data.status.toUpperCase()}\n\n`

    text += `### WordPress Environment ###\n`
    data.wp_env.forEach(i => text += `${i.label}: ${i.value} [${i.status}]\n`)

    text += `\n### Server Environment ###\n`
    data.server_env.forEach(i => text += `${i.label}: ${i.value} [${i.status}]\n`)

    text += `\n### WordPress Configuration ###\n`
    text += `Active Theme: ${data.wp_config.theme}\n`
    text += `Active Plugins:\n`
    data.wp_config.plugins.forEach(p => text += `- ${p}\n`)

    text += `\n### Wawp System Health Checks ###\n`
    data.health_checks.forEach(c => text += `${c.label}: ${c.status} - ${c.details} [${c.level}]\n`)

    text += `\n### WP-Cron Status ###\n`
    text += `Cron Engine: ${data.cron.enabled ? 'Enabled' : 'Disabled'}\n`
    data.cron.events.forEach(e => text += `- ${e.hook}: ${e.status} (Next: ${e.next_run})\n`)

    text += `\n### Database Tables Status ###\n`
    data.database.forEach(t => text += `${t.name}: ${t.status} ${t.missing ? '(' + t.missing + ')' : ''}\n`)

    text += `\n### Security & Core Configuration ###\n`
    data.security.forEach(s => text += `${s.label}: ${s.status} - ${s.message}\n`)

    text += `\n### Feature Status (Local) ###\n`
    const features = dashboardData.features || {}
    Object.keys(features).forEach(k => {
      text += `${k}: ${features[k].enabled ? 'Enabled' : 'Disabled'} (Allowed: ${features[k].allowed ? 'Yes' : 'No'})\n`
    })

    navigator.clipboard.writeText(text)
    toast.success(t('copied', 'Copied to clipboard'), {
      description: t('copySuccessMsg', 'Diagnostic report copied successfully.')
    })
  }


  const isIssue = (s: string) => {
    if (!s || typeof s !== 'string') return false;
    const l = s.toLowerCase();
    return l.includes('error') || l.includes('warning') || l.includes('misconfigured') || l.includes('failure') || l.includes('missing') || l.includes('disconnected') || l.includes('incomplete') || l.includes('issue');
  }

  const getStatusChip = (s: string) => {
    if (!s || typeof s !== 'string') return null;
    const s_lower = s.toLowerCase();
    const isOk = s_lower === 'ok' || s_lower === 'healthy' || s_lower === 'enabled' || s_lower === 'writable' || s_lower === 'accessible' || s_lower === 'scheduled' || s_lower === 'active';
    const isWarning = s_lower.includes('warning') || s_lower.includes('misconfigured') || s_lower.includes('pending');
    const isError = s_lower.includes('error') || s_lower.includes('critical') || s_lower.includes('disconnected') || s_lower.includes('disabled') || s_lower.includes('missing') || s_lower.includes('failure') || s_lower.includes('incomplete') || s_lower.includes('not scheduled');

    let bg = 'bg-gray-100/50 text-gray-600';
    let icon = <Info className="w-3 h-3" />;

    if (isOk) {
      bg = 'bg-emerald-50 text-emerald-700';
      icon = <CheckCircle2 className="w-3 h-3" />;
    } else if (isWarning) {
      bg = 'bg-amber-50 text-amber-700';
      icon = <AlertCircle className="w-3 h-3" />;
    } else if (isError) {
      bg = 'bg-rose-50 text-rose-700';
      icon = <XCircle className="w-3 h-3" />;
    }

    return (
      <Badge variant="secondary" className={`inline-flex items-center flex-row font-bold px-2.5 py-1 text-[10px] uppercase tracking-wider gap-2 border-none shadow-none whitespace-nowrap min-w-max h-auto ${bg}`}>
        {icon}
        <span className="leading-none">{s}</span>
      </Badge>
    )
  }

  const getItemDetails = (status: string, level?: string) => {
    const s_lower = status?.toLowerCase() || '';
    const isError = s_lower.includes('error') || s_lower.includes('critical') || s_lower.includes('disconnected') || s_lower.includes('disabled') || s_lower.includes('missing') || s_lower.includes('failure') || s_lower.includes('incomplete') || s_lower.includes('not scheduled') || level === 'error';
    const isWarning = s_lower.includes('warning') || s_lower.includes('misconfigured') || s_lower.includes('pending') || level === 'warning';
    
    if (isError) return {
      bg: 'bg-rose-50/70 border-rose-100/80',
      text: 'text-rose-800',
      subtext: 'text-rose-500',
      icon: <XCircle className="w-4 h-4 text-rose-500" />
    };
    if (isWarning) return {
      bg: 'bg-amber-50/70 border-amber-100/80',
      text: 'text-amber-800',
      subtext: 'text-amber-500',
      icon: <AlertCircle className="w-4 h-4 text-amber-500" />
    };
    return {
      bg: 'bg-emerald-50/70 border-emerald-100/80',
      text: 'text-emerald-800',
      subtext: 'text-emerald-600',
      icon: <CheckCircle2 className="w-4 h-4 text-emerald-500" />
    };
  };

  const getAllIssues = () => {
    interface Issue {
      label: string;
      detail: string;
      status: string;
      group: string;
      level: 'error' | 'warning' | 'info';
    }
    const issues: Issue[] = [];
    if (!data) return issues;

    (data.wp_env || []).filter(i => isIssue(i.status)).forEach(i => {
      const isWarn = i.label === 'WP_DEBUG';
      issues.push({ label: i.label, detail: i.message || i.value || '', status: isWarn ? 'Warning' : i.status, group: t('tabWordpress', 'WordPress'), level: isWarn ? 'warning' : 'error' });
    });
    (data.server_env || []).filter(i => isIssue(i.status)).forEach(i => issues.push({ label: i.label, detail: i.message || i.value || '', status: i.status || 'Issue', group: t('tabServer', 'Server'), level: 'error' }));
    (data.health_checks || []).filter(i => isIssue(i.status) || isIssue(i.level)).forEach(i => issues.push({ label: i.label, detail: i.details || '', status: i.status || 'Issue', group: 'Wawp', level: (i.level === 'warning' ? 'warning' : 'error') as 'error' | 'warning' }));
    (data.database || []).filter(i => isIssue(i.status)).forEach(i => issues.push({ label: i.name, detail: i.missing || 'Required tables are missing or incomplete.', status: i.status || 'Issue', group: t('tabDatabase', 'Database'), level: 'error' }));

    (data.security || []).forEach(i => {
      if (i.label === "WordPress Debug Mode" || i.label === "WP_DEBUG") return;
      if (isIssue(i.status)) {
        const isWarn = i.label === "Debug Log";
        issues.push({ label: i.label, detail: i.message || '', status: isWarn ? 'Warning' : i.status, group: t('tabSecurity', 'Security'), level: isWarn ? 'warning' : 'error' });
      }
    });

    if (!data.cron.enabled) {
      issues.push({ label: t('cronStatusTitle', 'Cron Engine'), detail: 'WP-Cron is disabled on this site.', status: t('disabled', 'Disabled'), group: 'Cron', level: 'warning' });
    }
    if (data.cron && data.cron.events) {
      data.cron.events.filter(e => isIssue(e.status) || e.status?.toLowerCase().includes('not scheduled') || e.state === 'disabled').forEach(e => {
        const isNotScheduled = e.status?.toLowerCase().includes('not scheduled');
        issues.push({ 
          label: e.hook, 
          detail: e.next_run || 'Task is not scheduled.', 
          status: e.status, 
          group: 'Cron', 
          level: isNotScheduled ? 'error' : 'warning' 
        });
      });
    }

    return issues;
  }

  const getStatusBanner = () => {
    const issuesList = getAllIssues();
    let status: 'healthy' | 'warning' | 'issues' = 'healthy';
    if (issuesList.length > 0) {
      const hasErrors = issuesList.some(i => i.status.toLowerCase().includes('error') || i.status.toLowerCase().includes('critical') || i.status.toLowerCase().includes('failure'));
      status = hasErrors ? 'issues' : 'warning';
    }

    const config = {
      healthy: {
        title: t('allSystemsOperational', 'System Infrastructure is Healthy'),
        desc: data.header.desc || t('healthyBannerDesc', 'Everything is running smoothly.')
      },
      warning: {
        title: t('attentionNeeded', 'Attention Needed'),
        desc: issuesList.length > 0
          ? `We found ${issuesList.length} system ${issuesList.length === 1 ? 'issue' : 'issues'} that could be optimized.`
          : (data.header.desc || t('warningBannerDesc', 'Some non-critical issues were found.'))
      },
      issues: {
        title: t('criticalIssuesFound', 'Attention Needed'),
        desc: issuesList.length > 0
          ? `We found ${issuesList.length} critical system ${issuesList.length === 1 ? 'issue' : 'issues'} that need fixing.`
          : (data.header.desc || t('issuesBannerDesc', 'Major components need your attention.'))
      }
    };

    const { title, desc } = config[status] || config.healthy;

    const hasRepairableContent = () => {
      if (!data) return false;
      const hasDbIssues = (data.database || []).some(t => t.can_create || t.can_repair || t.missing);
      const hasCronIssues = (data.cron?.events || []).some(e => e.status?.toLowerCase().includes('not scheduled'));
      const hasSenderIssues = (data.health_checks || []).some(c => c.status?.toLowerCase() === 'warning' || c.status?.toLowerCase() === 'error');
      const serverRepairable = (data.header?.repairable || 0) > 0;
      return serverRepairable || hasDbIssues || hasCronIssues || hasSenderIssues;
    };

    return (
      <SettingCard className="p-0 overflow-hidden mb-8 shadow-none">
        {/* ModernCardHeader-style header */}
        <div className="pt-4 pb-4 border-b border-slate-100 bg-slate-50/20 px-6 rounded-t-[5px]">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <div className="text-lg font-bold flex items-center gap-2 text-slate-800">
                {status === 'healthy' ? (
                  <ShieldCheck className="w-5 h-5 text-emerald-500" />
                ) : status === 'warning' ? (
                  <AlertCircle className="w-5 h-5 text-amber-500" />
                ) : (
                  <ShieldAlert className="w-5 h-5 text-rose-500" />
                )}
                {title}
              </div>
              <div className="text-xs font-medium text-slate-500 mt-1">{desc}</div>
            </div>
            <div className="shrink-0 grid grid-cols-2 md:flex md:items-center gap-2.5 w-full md:w-auto">
              <SecondaryButton onClick={refreshStatus} disabled={loading} className="w-full md:w-auto">
                <RefreshCw className={`w-3.5 h-3.5 mr-1.5 ${loading && activeAction === 'refresh' ? 'animate-spin' : ''}`} />
                {t('refreshStatus', 'Troubleshooting')}
              </SecondaryButton>
              {issuesList.length > 0 && !showAllIssues && (
                <SecondaryButton onClick={() => setShowAllIssues(true)} className="border-rose-200 text-rose-600 hover:bg-rose-50 w-full md:w-auto">
                  <AlertCircle className="w-3.5 h-3.5 mr-1.5" />
                  Report ({issuesList.length})
                </SecondaryButton>
              )}
              {hasRepairableContent() && (
                <AdminButton onClick={repairAll} loading={loading && activeAction === 'repairAll'} className={`bg-rose-600 hover:bg-rose-700 w-full md:w-auto ${issuesList.length > 0 && !showAllIssues ? 'col-span-2' : ''}`}>
                  <Wrench className="w-3.5 h-3.5 mr-1.5" />
                  {t('repairAll', 'Repair All Issues')}
                </AdminButton>
              )}
            </div>
          </div>
        </div>

        {/* Banner text */}
        {data.header.banner_text && (
          <div className="px-6 pt-4">
            <p className="text-[11px] text-[#004449] font-bold px-3 py-1.5 bg-[#004449]/5 rounded border border-[#004449]/10 w-fit">
              {data.header.banner_text}
            </p>
          </div>
        )}

        {/* Issues List — collapsed by default */}
        {issuesList.length > 0 && showAllIssues && (
          <div className="p-6 space-y-3 animate-in fade-in slide-in-from-top-2 duration-400">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <AlertCircle className="w-3.5 h-3.5 text-slate-400" />
                <span className="text-[12px] font-bold text-slate-500">{t('itemsNeededAttention', 'Items needing attention')}</span>
              </div>
              <button onClick={() => setShowAllIssues(false)} className="text-[11px] font-bold text-slate-400 hover:text-slate-600 transition-colors flex items-center gap-1.5">
                <ChevronUp className="w-3.5 h-3.5" />
                {t('hideList', 'Collapse')}
              </button>
            </div>

            <div className="space-y-2.5">
              {issuesList.map((issue, i) => (
                <div
                  key={i}
                  className={`px-5 py-3.5 rounded-lg border transition-all ${
                    issue.level === 'error'
                      ? 'bg-rose-50/70 border-rose-100/80'
                      : 'bg-amber-50/70 border-amber-100/80'
                  }`}
                >
                  <div className={`text-[13px] font-bold flex items-center gap-2 ${
                    issue.level === 'error' ? 'text-rose-800' : 'text-amber-800'
                  }`}>
                    {issue.level === 'error'
                      ? <XCircle className="w-4 h-4 text-rose-500" />
                      : <AlertCircle className="w-4 h-4 text-amber-500" />}
                    {issue.label}
                  </div>
                  <div className={`text-[12px] font-medium mt-1 ${
                    issue.level === 'error' ? 'text-rose-500' : 'text-amber-500'
                  }`}>{issue.detail || `${issue.status} — ${issue.group}`}</div>
                </div>
              ))}
            </div>
          </div>
        )}
      </SettingCard>
    )
  }

  return (
    <SettingsLayout
      id="wawp-system-info"
      dir={isRtl ? "rtl" : "ltr"}
      style={{ fontFamily: isRtl ? "'IBM Plex Sans Arabic', sans-serif" : "'Inter', sans-serif" }}
    >
      <div className="max-w-7xl mx-auto space-y-6">
        <SettingsHeader
        title={t('system_info_title', 'System Infrastructure')}
        description={t('system_info_desc', 'Comprehensive diagnostic reports and health monitoring for your environment.')}
      >
        <div className="grid grid-cols-2 md:flex items-center gap-2.5 w-full md:w-auto">
          <SecondaryButton onClick={syncUsers} disabled={loading} className="uppercase tracking-widest text-[11px] font-black w-full md:w-auto">
            <UserPlus className="w-4 h-4 mr-1.5 text-emerald-500" />
            {t('syncUsers', 'Sync Users')}
          </SecondaryButton>
          <SecondaryButton onClick={copyForSupport} className="uppercase tracking-widest text-[11px] font-black w-full md:w-auto">
            <Copy className="w-4 h-4 mr-1.5 text-indigo-500" />
            {t('copySupport', 'Copy for Support')}
          </SecondaryButton>
        </div>
      </SettingsHeader>

      {getStatusBanner()}

      {data?.update && (
        <SettingCard className="p-0 overflow-hidden mb-6 shadow-none border-emerald-200/50">
          <div className="pt-4 pb-4 border-b border-emerald-100 bg-emerald-50/30 px-6 rounded-t-[5px]">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div>
                <div className="text-lg font-bold flex items-center gap-2 text-slate-800">
                  <Info className="w-5 h-5 text-emerald-500" />
                  {t('updateAvailable', 'New Update Available')}
                  <Badge className="bg-emerald-50 text-emerald-700 border-none text-[10px] px-2 font-bold uppercase">v{data.update.new_version}</Badge>
                </div>
                <div className="text-xs font-medium text-slate-500 mt-1">
                  {t('updateNotice', 'A newer version of the platform is available with improvements and fixes.')}
                </div>
              </div>
              <div className="shrink-0">
                <SuccessButton className="font-black text-[11px] uppercase tracking-widest px-6 rounded-[5px] flex items-center gap-2" onClick={() => { if (data.update?.url) window.location.href = data.update.url; }}>
                  {t('updateNow', 'Update Now')} <Zap size={14} className="fill-white" />
                </SuccessButton>
              </div>
            </div>
          </div>
        </SettingCard>
      )}

      {data.banned_msg && (
        <SettingCard className="p-0 overflow-hidden mb-6 shadow-none border-orange-200/50">
          <div className="pt-4 pb-4 border-b border-orange-100 bg-orange-50/30 px-6 rounded-t-[5px]">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div>
                <div className="text-lg font-bold flex items-center gap-2 text-slate-800">
                  <ShieldAlert className="w-5 h-5 text-orange-500" />
                  {t('accountIssue', 'Account Issue Reported')}
                  <Badge className="bg-orange-50 text-orange-700 border-none text-[10px] px-2 font-bold uppercase">Restriction</Badge>
                </div>
                <div className="text-xs font-medium text-slate-500 mt-1 italic">
                  &quot;{data.banned_msg}&quot;
                </div>
              </div>
            </div>
          </div>
        </SettingCard>
      )}

      {data.not_logged_msg && (
        <SettingCard className="p-0 overflow-hidden mb-6 shadow-none border-indigo-200/50">
          <div className="pt-4 pb-4 border-b border-indigo-100 bg-indigo-50/30 px-6 rounded-t-[5px]">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div>
                <div className="text-lg font-bold flex items-center gap-2 text-slate-800">
                  <ShieldCheck className="w-5 h-5 text-indigo-500" />
                  {t('notLoggedIn', 'Platform Authentication Required')}
                  <Badge className="bg-indigo-50 text-indigo-700 border-none text-[10px] px-2 font-bold uppercase">Action Required</Badge>
                </div>
                <div className="text-xs font-medium text-slate-500 mt-1">
                  {data.not_logged_msg}
                </div>
              </div>
              {data.login_url && (
                <div className="shrink-0">
                  <SuccessButton className="font-black text-[11px] uppercase tracking-widest px-6 rounded-[5px] flex items-center gap-2" onClick={() => window.location.href = data.login_url}>
                    {t('signInNow', 'Sign In Now')} <Zap size={14} className="fill-white" />
                  </SuccessButton>
                </div>
              )}
            </div>
          </div>
        </SettingCard>
      )}

      <div className="flex justify-center w-full" dir={isRtl ? "rtl" : "ltr"}>
        <FlatTabs
          tabs={[
            { id: 'wordpress', label: t('tabWordpress', 'WordPress'), icon: Layout },
            { id: 'server', label: t('tabServer', 'Server'), icon: Server },
            { id: 'cron', label: 'Cron', icon: Clock },
            { id: 'health', label: t('tabHealth', 'Health'), icon: Activity },
            { id: 'database', label: t('tabDatabase', 'Database'), icon: Database },
            { id: 'security', label: t('tabSecurity', 'Security'), icon: ShieldCheck }
          ]}
          activeTab={activeTab}
          onTabChange={setActiveTab}
        />
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <div className="animate-in fade-in duration-500">
          <TabsContent value="wordpress" className="focus:outline-none space-y-8 animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t('wpConfigTitle', 'WordPress Configuration')}
                description="Detailed view of your WordPress environment and installation."
                icon={Layout}
                rightAction={
                  <div className="flex items-center gap-2">
                    <Badge variant="secondary" className="bg-indigo-50 text-indigo-700 border-none px-2.5 py-1 font-bold text-[10px]">{data.wp_config.theme}</Badge>
                    <span className="text-[9px] font-bold text-slate-400 uppercase tracking-widest">{t('themeLabel', 'Theme')}</span>
                  </div>
                }
              />
              <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-4">
                {data.wp_env.map((item, i: number) => {
                  const details = getItemDetails(item.status);
                  return (
                    <div key={i} className={`p-4 rounded-lg border transition-all ${details.bg}`}>
                      <div className="flex items-center justify-between gap-3">
                        <div className={`text-[13px] font-bold flex items-center gap-2 ${details.text}`}>
                          {details.icon}
                          {item.label}
                        </div>
                        {getStatusChip(item.status)}
                      </div>
                      <div className={`text-[12px] font-medium mt-1 ${details.subtext}`}>
                        {item.value} {item.message && <span className="opacity-70">— {item.message}</span>}
                      </div>
                    </div>
                  );
                })}
              </div>
            </SettingCard>
          </TabsContent>

          <TabsContent value="server" className="focus:outline-none animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t('tabServer', 'Server')}
                description="Server environment settings and values"
                icon={Server}
              />
              <div className="p-6 space-y-3">
                {data.server_env.map((item, i: number) => {
                  const details = getItemDetails(item.status);
                  return (
                    <div key={i} className={`p-4 rounded-lg border transition-all ${details.bg}`}>
                      <div className="flex items-center justify-between gap-3">
                        <div className={`text-[13px] font-bold flex items-center gap-2 ${details.text}`}>
                          {details.icon}
                          {item.label}
                        </div>
                        <div className="flex items-center gap-3">
                          <span className="text-[12px] font-mono font-bold text-gray-400 bg-white/50 px-2 py-0.5 rounded border border-gray-100/50">{item.value}</span>
                          {getStatusChip(item.status)}
                        </div>
                      </div>
                      {item.message && <p className={`text-[11px] font-medium mt-1 italic ${details.subtext}`}>{item.message}</p>}
                    </div>
                  );
                })}
              </div>
            </SettingCard>
          </TabsContent>

          <TabsContent value="cron" className="focus:outline-none space-y-8 animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t('cronStatusTitle', 'WP-Cron Engine')}
                description={data.cron.is_system ? t('systemCron', 'System Cron (Server-side)') : t('wpCron', 'WP-Cron (Internal)')}
                icon={Clock}
                rightAction={
                  <div className="flex items-center gap-3">
                    {data.cron.status && getStatusChip(data.cron.status)}
                    <Badge className={`rounded-[3px] px-3 py-1 font-bold uppercase text-[10px] border-none shadow-none tracking-tight ${data.cron.enabled ? 'bg-emerald-500 text-white' : 'bg-rose-500 text-white'}`}>
                      {data.cron.enabled ? t('scheduled', 'Scheduled') : t('disabled', 'Disabled')}
                    </Badge>
                  </div>
                }
              />
              <div className="p-8 space-y-8">
                {data.cron.message && (
                  <div className={`px-5 py-3.5 rounded-lg border transition-all ${
                    data.cron.level === 'error'
                      ? 'bg-rose-50/70 border-rose-100/80'
                      : data.cron.level === 'warning'
                        ? 'bg-amber-50/70 border-amber-100/80'
                        : 'bg-emerald-50/70 border-emerald-100/80'
                  }`}>
                    <div className={`text-[13px] font-bold flex items-center gap-2 ${
                      data.cron.level === 'error' ? 'text-rose-800' : data.cron.level === 'warning' ? 'text-amber-800' : 'text-emerald-800'
                    }`}>
                      {data.cron.level === 'error'
                        ? <XCircle className="w-4 h-4 text-rose-500" />
                        : data.cron.level === 'warning'
                          ? <AlertCircle className="w-4 h-4 text-amber-500" />
                          : <CheckCircle2 className="w-4 h-4 text-emerald-500" />}
                      {t('cronDiagnostics', 'Diagnostics')}
                    </div>
                    <div className={`text-[12px] font-medium mt-1 ${
                      data.cron.level === 'error' ? 'text-rose-500' : data.cron.level === 'warning' ? 'text-amber-500' : 'text-emerald-600'
                    }`}>
                      {data.cron.message}
                      {data.cron.last_hit && (
                        <div className="text-[11px] opacity-80 font-bold mt-1">{t('lastCronHit', 'Last fired')}: {data.cron.last_hit}</div>
                      )}
                    </div>
                  </div>
                )}

                {data.cron.url && (
                  <div className="space-y-2">
                    <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">{t('cronUrlLabel', 'System Cron URL (Host)')}</label>
                    <div className="flex items-center gap-2 p-3 bg-slate-50 border border-slate-100 rounded-[5px] group">
                      <code className="text-[11px] font-mono font-bold text-indigo-600 flex-1 truncate">{data.cron.url}</code>
                      <SecondaryButton size="sm" className="px-2 text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 rounded border-none" onClick={() => {
                        navigator.clipboard.writeText(data.cron.url || '');
                        toast.success('URL copied to clipboard');
                      }}>
                        <Copy className="w-3.5 h-3.5" />
                      </SecondaryButton>
                    </div>
                    <p className="text-[10px] text-gray-400 italic px-1">{t('cronUrlInstruction', 'Use this URL to set up a real CRON job in your hosting control panel (e.g. cPanel).')}</p>
                  </div>
                )}
              </div>
            </SettingCard>

            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t('cronEventsTitle', 'Scheduled Tasks Monitoring')}
                description="View and manage scheduled background tasks"
                icon={Clock}
              />
              <div className="p-6 space-y-3">
                {data.cron.events.map((event, i: number) => {
                  const details = getItemDetails(event.status, event.state === 'disabled' ? 'warning' : undefined);
                  return (
                    <div key={i} className={`p-4 rounded-lg border transition-all ${details.bg}`}>
                      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                        <div className="flex flex-col text-start min-w-0">
                          <div className={`text-[13px] md:text-[14px] font-bold flex items-center gap-2 ${details.text}`}>
                            {details.icon}
                            <span className="truncate sm:whitespace-normal">{event.hook}</span>
                          </div>
                          <span className={`text-[10px] font-medium mt-1 uppercase tracking-wider ${details.subtext}`}>{event.next_run}</span>
                        </div>
                        <div className="flex items-center justify-between sm:justify-end gap-3 shrink-0 border-t sm:border-none pt-3 sm:pt-0 mt-1 sm:mt-0">
                          {getStatusChip(event.status)}
                          {event.status?.toLowerCase().includes('not scheduled') ? (
                            <AdminButton className="text-[10px] h-7 px-3 font-bold bg-rose-600 hover:bg-rose-700 text-white rounded-[4px] border-none" onClick={() => handleScheduleCron(event.hook)}>
                              <Wrench className="w-3 h-3 mr-1.5" /> {t('btnFix', 'Fix')}
                            </AdminButton>
                          ) : event.state !== 'scheduled' && (
                            <SecondaryButton className="text-[10px] h-7 px-3 font-bold border-slate-200 text-slate-600 hover:bg-slate-50 rounded-[4px]" onClick={() => handleScheduleCron(event.hook)}>
                              <Zap className="w-3 h-3 mr-1.5" /> {t('btnRunNow', 'Run')}
                            </SecondaryButton>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </SettingCard>
          </TabsContent>

          <TabsContent value="health" className="focus:outline-none animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t('pluginHealthTitle', 'Wawp System Health')}
                description="Status of critical system components"
                icon={Activity}
              />
              <div className="p-6 space-y-3">
                {data.health_checks.map((check, i: number) => {
                  const details = getItemDetails(check.status, check.level as string);
                  return (
                    <div key={i} className={`p-4 rounded-lg border transition-all ${details.bg}`}>
                      <div className="flex items-center justify-between gap-3 text-start">
                        <div className={`text-[14px] font-bold flex items-center gap-2 ${details.text}`}>
                          {details.icon}
                          {check.label}
                        </div>
                        {getStatusChip(check.status)}
                      </div>
                      <p className={`text-[11px] font-medium mt-1 opacity-80 ${details.subtext}`}>{check.details}</p>
                    </div>
                  );
                })}
              </div>
            </SettingCard>
          </TabsContent>

          <TabsContent value="database" className="focus:outline-none animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t('databaseStatusTitle', 'Database Health')}
                description="Status and tools for database tables"
                icon={Database}
              />
              <div className="p-6 space-y-4">
                {data.database.map((table, i: number) => {
                  const details = getItemDetails(table.status, table.missing ? 'error' : undefined);
                  return (
                    <div key={i} className={`px-5 py-3.5 rounded-lg border transition-all ${details.bg} mb-3 last:mb-0`}>
                      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                        <div className={`text-[13px] font-bold flex items-center gap-2 ${details.text} truncate min-w-0 flex-1`}>
                          {details.icon}
                          {table.name}
                        </div>
                        
                        <div className="flex items-center gap-2 shrink-0">
                          {table.missing && <Badge className="text-[9px] h-5 px-1.5 bg-rose-500 text-white border-none font-bold uppercase tracking-widest rounded-[3px]">{table.missing}</Badge>}
                          {getStatusChip(table.status)}
                          
                          <div className="flex items-center gap-1.5 ml-1 pl-3 border-l border-black/5">
                            {table.can_create && (
                              <AdminButton className="h-7 px-3 text-[10px] font-bold bg-emerald-600 hover:bg-emerald-700" onClick={() => handleDbAction('create', table.name)}>
                                {t('btnCreate', 'Create')}
                              </AdminButton>
                            )}
                            {table.can_repair && (
                              <SecondaryButton className="h-7 px-3 text-[10px] font-bold border-amber-200 text-amber-700 hover:bg-amber-50" onClick={() => handleDbAction('repair', table.name)}>
                                {t('btnRepair', 'Repair')}
                              </SecondaryButton>
                            )}
                            {table.can_truncate && (
                              <SecondaryButton className="h-7 px-3 text-[10px] font-bold border-slate-200 text-slate-500 hover:bg-rose-50 hover:text-rose-600 hover:border-rose-100" onClick={() => handleDbAction('truncate', table.name)}>
                                {t('btnEmptyTable', 'EMPTY')}
                              </SecondaryButton>
                            )}
                            {table.can_delete && (
                              <SecondaryButton className="h-7 px-3 text-[10px] font-bold border-slate-200 text-rose-400 hover:bg-rose-600 hover:text-white hover:border-rose-600" onClick={() => handleDbAction('delete', table.name)}>
                                {t('btnDeleteTable', 'DROP')}
                              </SecondaryButton>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}

                <div className="p-4 bg-amber-50/60 border-t border-amber-100 flex items-center justify-between px-7 py-5">
                  <div className="flex items-center gap-4 text-start">
                    <div className="p-2.5 bg-amber-100 rounded-lg text-amber-600 border border-amber-200">
                      <RefreshCw size={20} />
                    </div>
                    <div>
                      <p className="text-[14px] font-bold text-amber-900 leading-tight mb-1">Legacy Data Migration</p>
                      <p className="text-[12px] text-amber-600 font-medium">Sync missing elements from old registration form layout to the new system.</p>
                    </div>
                  </div>
                  <SuccessButton
                    className="font-black text-[11px] uppercase px-6 transition-all shadow-none"
                    onClick={async () => {
                      setLoading(true);
                      try {
                        const res = await fetch(`${dashboardData.global.apiRestUrl}/system/migrate-signup`, {
                          method: 'POST',
                          headers: {
                            'Content-Type': 'application/json',
                            'X-WP-Nonce': dashboardData.global.wpRestNonce
                          }
                        });
                        const json = await res.json();
                        if (json.success) {
                          toast.success(json.data?.message || 'Migration complete');
                          refreshStatus();
                        } else {
                          toast.error(json.data?.message || 'Migration failed');
                        }
                      } catch {
                        toast.error('Network error during migration');
                      } finally {
                        setLoading(false);
                      }
                    }}
                    disabled={loading}
                  >
                    <Zap size={14} className="mr-2 fill-amber-500 text-amber-500" />
                    Migrate Now
                  </SuccessButton>
                </div>

                <div className="p-4 bg-indigo-50/60 border-t border-indigo-100 flex items-center justify-between px-7 py-5">
                  <div className="flex items-center gap-4 text-start">
                    <div className="p-2.5 bg-indigo-100 rounded-lg text-indigo-600 border border-indigo-200">
                      <Activity size={20} />
                    </div>
                    <div>
                      <p className="text-[14px] font-bold text-indigo-900 leading-tight mb-1">{t('migrateNotifications', 'Notifications Migration')}</p>
                      <p className="text-[12px] text-indigo-600 font-medium">{t('migrateNotificationsDesc', 'Sync all existing notification rules to the new Flow structure.')}</p>
                    </div>
                  </div>
                  <SuccessButton
                    className="font-black text-[11px] uppercase px-6 transition-all shadow-none"
                    onClick={async () => {
                      setLoading(true);
                      try {
                        const res = await fetch(`${dashboardData.global.apiRestUrl}/system/migrate-notifications`, {
                          method: 'POST',
                          headers: {
                            'Content-Type': 'application/json',
                            'X-WP-Nonce': dashboardData.global.wpRestNonce
                          }
                        });
                        const json = await res.json();
                        if (json.success) {
                          toast.success(json.data?.message || 'Migration complete');
                          refreshStatus();
                        } else {
                          toast.error(json.data?.message || 'Migration failed');
                        }
                      } catch {
                        toast.error('Network error during migration');
                      } finally {
                        setLoading(false);
                      }
                    }}
                    disabled={loading}
                  >
                    <Zap size={14} className="mr-2 fill-indigo-500 text-indigo-500" />
                    Migrate Now
                  </SuccessButton>
                </div>
              </div>
            </SettingCard>
          </TabsContent>

          <TabsContent value="security" className="focus:outline-none animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t('securityTitle', 'Core & Security Configuration')}
                description="Security checks and core configurations"
                icon={ShieldCheck}
              />
              <div className="p-6 space-y-3">
                {data.security.map((item, i: number) => {
                  const details = getItemDetails(item.status);
                  return (
                    <div key={i} className={`p-4 rounded-lg border transition-all ${details.bg}`}>
                      <div className="flex items-center justify-between gap-3 text-start">
                        <div className={`text-[14px] font-bold flex items-center gap-2 ${details.text}`}>
                          {details.icon}
                          {item.label}
                        </div>
                        {getStatusChip(item.status)}
                      </div>
                      <p className={`text-[11px] font-medium mt-1 opacity-90 text-start ${details.subtext}`}>{item.message}</p>
                    </div>
                  );
                })}
              </div>
            </SettingCard>
          </TabsContent>
        </div>
      </Tabs>
      </div>
    </SettingsLayout>
  );
}
