'use client';

import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from '@/hooks/useTranslation';
import { usePermissions } from '@/hooks/usePermissions';
import { PageState } from '@/components/common/feedback/PageState';
import {
  Bell,
  RefreshCw,
  AlertCircle,
  Save,
  CheckCircle,
  Send,
  Clock,
  AlertTriangle,
  HardDrive,
  Shield,
} from 'lucide-react';
import {
  getAlertHistory,
  getAlertConfig,
  updateAlertConfig,
  testAlert,
  AlertItem,
  AlertConfigResponse,
  AlertType,
  AlertStatus,
  AlertSeverity,
  QueryAlertHistoryParams,
  UpdateAlertConfigParams,
  getAlertTypeLabel,
  getAlertTypeColor,
  getAlertSeverityLabel,
  getAlertSeverityColor,
  getAlertStatusLabel,
  getAlertStatusColor,
} from '@/services/api/logs';
import { Pagination } from '../_components/Pagination';

/**
 * 告警管理页面
 * 配置和查看告警
 */
export default function AlertsPage() {
  const { t } = useTranslation();
  const { hasPermission, isAdmin } = usePermissions();
  
  const [activeTab, setActiveTab] = useState<'history' | 'config'>('history');
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isTesting, setIsTesting] = useState<string | null>(null);
  
  // 告警历史
  const [alerts, setAlerts] = useState<AlertItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [historySummary, setHistorySummary] = useState<{
    total: number;
    byType: Record<AlertType, number>;
    byStatus: Record<AlertStatus, number>;
  } | null>(null);
  
  // 告警配置
  const [config, setConfig] = useState<AlertConfigResponse | null>(null);
  
  const [error, setError] = useState<string | null>(null);
  const [saveSuccess, setSaveSuccess] = useState(false);
  const [testResult, setTestResult] = useState<{ channel: string; success: boolean; message?: string } | null>(null);

  // 筛选条件
  const [filters, setFilters] = useState<QueryAlertHistoryParams>({
    startTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
    endTime: new Date().toISOString(),
  });

  const canAccess = isAdmin || hasPermission('log:alert');

  // 加载告警历史
  const loadHistory = useCallback(async () => {
    if (!canAccess) return;
    
    setIsLoading(true);
    setError(null);
    
    try {
      const params: QueryAlertHistoryParams = {
        ...filters,
        page,
        limit,
      };
      
      const response = await getAlertHistory(params);
      setAlerts(response.items || []);
      setTotal(response.total || 0);
      setHistorySummary(response.summary || null);
    } catch (err) {
      console.error('Failed to load alert history:', err);
      setError(t.logs.error.loadFailed);
    } finally {
      setIsLoading(false);
    }
  }, [canAccess, filters, page, limit, t]);

  // 加载告警配置
  const loadConfig = async () => {
    if (!canAccess) return;
    
    setIsLoading(true);
    setError(null);
    
    try {
      const response = await getAlertConfig();
      setConfig(response);
    } catch (err) {
      console.error('Failed to load alert config:', err);
      setError(t.logs.error.loadFailed);
    } finally {
      setIsLoading(false);
    }
  };

  // 切换 tab 时加载数据
  useEffect(() => {
    if (activeTab === 'history') {
      loadHistory();
    } else {
      loadConfig();
    }
  }, [activeTab, loadHistory]);

  // 保存配置
  const handleSave = async () => {
    if (!config || !canAccess) return;
    
    setIsSaving(true);
    setError(null);
    setSaveSuccess(false);
    
    try {
      const params: UpdateAlertConfigParams = {
        slowRequest: config.slowRequest,
        errorRate: config.errorRate,
        ipAnomaly: config.ipAnomaly,
        diskSpace: config.diskSpace,
      };
      
      const response = await updateAlertConfig(params);
      setConfig(response);
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 3000);
    } catch (err) {
      console.error('Failed to save config:', err);
      setError(t.logs.error.saveFailed);
    } finally {
      setIsSaving(false);
    }
  };

  // 测试告警通道
  const handleTest = async (channel: 'slack' | 'feishu' | 'email') => {
    setIsTesting(channel);
    setTestResult(null);
    
    try {
      const result = await testAlert({ channel });
      setTestResult({
        channel,
        success: result.status === 'SUCCESS',
        message: result.errorMessage,
      });
    } catch (err) {
      console.error('Failed to test alert:', err);
      setTestResult({
        channel,
        success: false,
        message: t.logs?.alerts?.config?.notifications?.testFailed || '测试失败',
      });
    } finally {
      setIsTesting(null);
    }
  };

  // 无权限提示
  if (!canAccess) {
    return (
      <div className="p-6 flex items-center justify-center">
        <PageState
          variant="error"
          title={t.common.permissionDenied}
          description={t.common.permissionDeniedDetail}
          layout="center"
          className="mx-auto w-full max-w-2xl border-0 bg-transparent"
        />
      </div>
    );
  }

  const totalPages = Math.ceil(total / limit);

  return (
    <div className="h-full flex flex-col bg-[#f7f8fa]">

      {/* 主内容区域 - 可滚动 */}
      <div className="flex-1 overflow-y-auto p-6">
        <div className="max-w-[1400px] mx-auto space-y-4">
          {/* Tab 切换 */}
          <div className="flex gap-2">
            <button
              onClick={() => setActiveTab('history')}
              className={`h-8 px-4 text-sm font-medium rounded-md transition-colors ${
                activeTab === 'history'
                  ? 'bg-[#3370ff] text-white'
                  : 'bg-white text-[#1f2329] border border-[#e5e6eb] hover:bg-[#f2f3f5]'
              }`}
            >
              {t.logs.alerts.tabs.history}
            </button>
            <button
              onClick={() => setActiveTab('config')}
              className={`h-8 px-4 text-sm font-medium rounded-md transition-colors ${
                activeTab === 'config'
                  ? 'bg-[#3370ff] text-white'
                  : 'bg-white text-[#1f2329] border border-[#e5e6eb] hover:bg-[#f2f3f5]'
              }`}
            >
              {t.logs.alerts.tabs.config}
            </button>
          </div>

          {/* 错误提示 */}
          {error && (
            <div className="bg-[#fff3f2] border border-[#ffccc7] rounded-lg p-3">
              <div className="flex items-center gap-2">
                <AlertCircle className="w-4 h-4 text-[#f54a45] flex-shrink-0" />
                <span className="text-sm text-[#f54a45]">{error}</span>
              </div>
            </div>
          )}

          {/* 告警历史 */}
          {activeTab === 'history' && (
            <div className="space-y-4">
              {/* 摘要统计 */}
              {historySummary && (
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                    <p className="text-xs text-[#646a73] mb-1">{t.logs?.alerts?.history?.summary?.total || '总告警数'}</p>
                    <p className="text-2xl font-semibold text-[#1f2329]">{historySummary.total}</p>
                  </div>
                  {Object.entries(historySummary.byType).slice(0, 3).map(([type, count]) => {
                    const colors = getAlertTypeColor(type as AlertType);
                    return (
                      <div key={type} className={`rounded-lg border p-4 shadow-sm ${colors.bg} ${colors.border}`}>
                        <p className={`text-xs mb-1 ${colors.text}`}>
                          {getAlertTypeLabel(type as AlertType, t)}
                        </p>
                        <p className={`text-2xl font-semibold ${colors.text}`}>{count}</p>
                      </div>
                    );
                  })}
                </div>
              )}

              {/* 告警列表 */}
              <div className="bg-white rounded-lg border border-[#e5e6eb] shadow-sm overflow-hidden">
                {/* 加载中 */}
                {isLoading && (
                  <div className="flex items-center justify-center py-12">
                    <RefreshCw className="w-6 h-6 text-[#8f959e] animate-spin" />
                  </div>
                )}

                {/* 告警行 */}
                {!isLoading && alerts.length > 0 && (
                  <div className="divide-y divide-[#e5e6eb]">
                    {alerts.map((alert, index) => {
                      const typeColors = getAlertTypeColor(alert.type);
                      const severityColors = getAlertSeverityColor(alert.severity);
                      const statusColors = getAlertStatusColor(alert.status);
                      
                      return (
                        <div key={index} className="p-4 hover:bg-[#f7f8fa] transition-colors">
                          <div className="flex items-start justify-between">
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center gap-2 mb-2">
                                <span className={`px-2 py-0.5 rounded text-xs font-medium ${typeColors.bg} ${typeColors.text}`}>
                                  {getAlertTypeLabel(alert.type, t)}
                                </span>
                                <span className={`px-2 py-0.5 rounded text-xs font-medium ${severityColors.bg} ${severityColors.text}`}>
                                  {getAlertSeverityLabel(alert.severity, t)}
                                </span>
                                <span className={`px-2 py-0.5 rounded text-xs font-medium ${statusColors.bg} ${statusColors.text}`}>
                                  {getAlertStatusLabel(alert.status, t)}
                                </span>
                              </div>
                              <p className="text-sm text-[#1f2329] mb-2">{alert.message}</p>
                              <div className="flex items-center gap-3 text-xs text-[#646a73]">
                                <span>通知渠道: {alert.channels.join(', ')}</span>
                                {alert.context.traceId && (
                                  <span className="font-mono">Trace: {alert.context.traceId.substring(0, 20)}...</span>
                                )}
                              </div>
                            </div>
                            <div className="text-right ml-4">
                              <p className="text-xs text-[#8f959e]">
                                {new Date(alert.sentAt).toLocaleString()}
                              </p>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}

                {/* 空状态 */}
                {!isLoading && alerts.length === 0 && (
                  <div className="py-12 flex items-center justify-center">
                    <PageState
                      variant="empty"
                      title={t.logs?.alerts?.history?.empty || t.common.noData}
                      layout="center"
                      className="border-0 bg-transparent"
                    />
                  </div>
                )}
              </div>

              <Pagination
                page={page}
                totalPages={totalPages}
                total={total}
                summary={
                  t.common.totalRecords.replace('{total}', total.toLocaleString()) +
                  '，' +
                  t.common.currentPage
                    .replace('{current}', String(page))
                    .replace('{total}', String(totalPages))
                }
                prevLabel={t.common.prevPage}
                nextLabel={t.common.nextPage}
                onPageChange={setPage}
              />

            </div>
          )}

          {/* 告警配置 */}
          {activeTab === 'config' && config && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {/* 慢请求告警 */}
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-2">
                    <Clock className="w-4 h-4 text-[#ff7d00]" />
                    <h3 className="text-sm font-medium text-[#1f2329]">
                      {t.logs?.alerts?.config?.slowRequest?.title || '慢请求告警'}
                    </h3>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={config.slowRequest.enabled}
                      onChange={(e) => setConfig(prev => prev ? {
                        ...prev,
                        slowRequest: { ...prev.slowRequest, enabled: e.target.checked }
                      } : null)}
                      className="sr-only peer"
                    />
                    <div className="w-9 h-5 bg-[#e5e6eb] peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#ff7d00]/20 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#ff7d00]"></div>
                  </label>
                </div>
                
                <div>
                  <label className="block text-xs font-medium text-[#646a73] mb-1.5">
                    {t.logs?.alerts?.config?.slowRequest?.thresholdMs || '阈值（毫秒）'}
                  </label>
                  <input
                    type="number"
                    value={config.slowRequest.thresholdMs}
                    onChange={(e) => setConfig(prev => prev ? {
                      ...prev,
                      slowRequest: { ...prev.slowRequest, thresholdMs: parseInt(e.target.value) || 2000 }
                    } : null)}
                    min={100}
                    className="w-full h-8 px-3 text-sm border border-[#e5e6eb] rounded-md focus:ring-1 focus:ring-[#ff7d00] focus:border-[#ff7d00] transition-all"
                  />
                  <p className="text-xs text-[#8f959e] mt-1">
                    {t.logs?.alerts?.config?.slowRequest?.thresholdMsDesc || '响应时间超过此值触发告警'}
                  </p>
                </div>
              </div>

              {/* 高错误率告警 */}
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-2">
                    <AlertTriangle className="w-4 h-4 text-[#f54a45]" />
                    <h3 className="text-sm font-medium text-[#1f2329]">
                      {t.logs?.alerts?.config?.errorRate?.title || '高错误率告警'}
                    </h3>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={config.errorRate.enabled}
                      onChange={(e) => setConfig(prev => prev ? {
                        ...prev,
                        errorRate: { ...prev.errorRate, enabled: e.target.checked }
                      } : null)}
                      className="sr-only peer"
                    />
                    <div className="w-9 h-5 bg-[#e5e6eb] peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#f54a45]/20 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#f54a45]"></div>
                  </label>
                </div>
                
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-[#646a73] mb-1.5">
                      {t.logs?.alerts?.config?.errorRate?.thresholdPercent || '阈值（%）'}
                    </label>
                    <input
                      type="number"
                      value={config.errorRate.thresholdPercent}
                      onChange={(e) => setConfig(prev => prev ? {
                        ...prev,
                        errorRate: { ...prev.errorRate, thresholdPercent: parseInt(e.target.value) || 5 }
                      } : null)}
                      min={1}
                      max={100}
                      className="w-full h-8 px-3 text-sm border border-[#e5e6eb] rounded-md focus:ring-1 focus:ring-[#f54a45] focus:border-[#f54a45] transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-[#646a73] mb-1.5">
                      {t.logs?.alerts?.config?.errorRate?.windowMinutes || '窗口（分钟）'}
                    </label>
                    <input
                      type="number"
                      value={config.errorRate.windowMinutes}
                      onChange={(e) => setConfig(prev => prev ? {
                        ...prev,
                        errorRate: { ...prev.errorRate, windowMinutes: parseInt(e.target.value) || 5 }
                      } : null)}
                      min={1}
                      className="w-full h-8 px-3 text-sm border border-[#e5e6eb] rounded-md focus:ring-1 focus:ring-[#f54a45] focus:border-[#f54a45] transition-all"
                    />
                  </div>
                </div>
              </div>

              {/* 磁盘空间告警 */}
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-2">
                    <HardDrive className="w-4 h-4 text-[#ff7d00]" />
                    <h3 className="text-sm font-medium text-[#1f2329]">
                      {t.logs?.alerts?.config?.diskSpace?.title || '磁盘空间告警'}
                    </h3>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={config.diskSpace.enabled}
                      onChange={(e) => setConfig(prev => prev ? {
                        ...prev,
                        diskSpace: { ...prev.diskSpace, enabled: e.target.checked }
                      } : null)}
                      className="sr-only peer"
                    />
                    <div className="w-9 h-5 bg-[#e5e6eb] peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#ff7d00]/20 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#ff7d00]"></div>
                  </label>
                </div>
                
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-[#646a73] mb-1.5">
                      {t.logs?.alerts?.config?.diskSpace?.warningPercent || '警告阈值（%）'}
                    </label>
                    <input
                      type="number"
                      value={config.diskSpace.warningPercent}
                      onChange={(e) => setConfig(prev => prev ? {
                        ...prev,
                        diskSpace: { ...prev.diskSpace, warningPercent: parseInt(e.target.value) || 80 }
                      } : null)}
                      min={1}
                      max={100}
                      className="w-full h-8 px-3 text-sm border border-[#e5e6eb] rounded-md focus:ring-1 focus:ring-[#ff7d00] focus:border-[#ff7d00] transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-[#646a73] mb-1.5">
                      {t.logs?.alerts?.config?.diskSpace?.criticalPercent || '严重阈值（%）'}
                    </label>
                    <input
                      type="number"
                      value={config.diskSpace.criticalPercent}
                      onChange={(e) => setConfig(prev => prev ? {
                        ...prev,
                        diskSpace: { ...prev.diskSpace, criticalPercent: parseInt(e.target.value) || 90 }
                      } : null)}
                      min={1}
                      max={100}
                      className="w-full h-8 px-3 text-sm border border-[#e5e6eb] rounded-md focus:ring-1 focus:ring-[#ff7d00] focus:border-[#ff7d00] transition-all"
                    />
                  </div>
                </div>
              </div>

              {/* 通知渠道 */}
              <div className="bg-white rounded-lg border border-[#e5e6eb] p-4 shadow-sm">
                <div className="flex items-center gap-2 mb-4">
                  <Shield className="w-4 h-4 text-[#00b42a]" />
                  <h3 className="text-sm font-medium text-[#1f2329]">
                    {t.logs?.alerts?.config?.notifications?.title || '通知渠道'}
                  </h3>
                </div>
                
                <div className="space-y-3">
                  {/* Slack */}
                  <div className="flex items-center justify-between p-2.5 bg-[#f7f8fa] rounded-md">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium text-[#1f2329]">Slack</span>
                      <span className={`px-1.5 py-0.5 text-xs rounded ${
                        config.notifications.slack.webhookConfigured 
                          ? 'bg-[#e8ffea] text-[#00b42a]' 
                          : 'bg-[#f2f3f5] text-[#8f959e]'
                      }`}>
                        {config.notifications.slack.webhookConfigured 
                          ? (t.logs?.alerts?.config?.notifications?.configured || '已配置')
                          : (t.logs?.alerts?.config?.notifications?.notConfigured || '未配置')
                        }
                      </span>
                    </div>
                    <button
                      onClick={() => handleTest('slack')}
                      disabled={!config.notifications.slack.webhookConfigured || isTesting === 'slack'}
                      className="flex items-center gap-1 h-6 px-2 text-xs bg-white border border-[#e5e6eb] rounded hover:bg-[#f2f3f5] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                      {isTesting === 'slack' ? (
                        <RefreshCw className="w-3 h-3 animate-spin" />
                      ) : (
                        <Send className="w-3 h-3" />
                      )}
                      <span>{t.logs?.alerts?.config?.notifications?.test || '测试'}</span>
                    </button>
                  </div>

                  {/* 飞书 */}
                  <div className="flex items-center justify-between p-2.5 bg-[#f7f8fa] rounded-md">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium text-[#1f2329]">
                        {t.logs?.alerts?.config?.notifications?.feishu || '飞书'}
                      </span>
                      <span className={`px-1.5 py-0.5 text-xs rounded ${
                        config.notifications.feishu.webhookConfigured 
                          ? 'bg-[#e8ffea] text-[#00b42a]' 
                          : 'bg-[#f2f3f5] text-[#8f959e]'
                      }`}>
                        {config.notifications.feishu.webhookConfigured 
                          ? (t.logs?.alerts?.config?.notifications?.configured || '已配置')
                          : (t.logs?.alerts?.config?.notifications?.notConfigured || '未配置')
                        }
                      </span>
                    </div>
                    <button
                      onClick={() => handleTest('feishu')}
                      disabled={!config.notifications.feishu.webhookConfigured || isTesting === 'feishu'}
                      className="flex items-center gap-1 h-6 px-2 text-xs bg-white border border-[#e5e6eb] rounded hover:bg-[#f2f3f5] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                      {isTesting === 'feishu' ? (
                        <RefreshCw className="w-3 h-3 animate-spin" />
                      ) : (
                        <Send className="w-3 h-3" />
                      )}
                      <span>{t.logs?.alerts?.config?.notifications?.test || '测试'}</span>
                    </button>
                  </div>

                  {/* Email */}
                  <div className="flex items-center justify-between p-2.5 bg-[#f7f8fa] rounded-md">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium text-[#1f2329]">
                        {t.logs?.alerts?.config?.notifications?.email || '邮件'}
                      </span>
                      <span className={`px-1.5 py-0.5 text-xs rounded ${
                        config.notifications.email.recipientCount > 0
                          ? 'bg-[#e8ffea] text-[#00b42a]' 
                          : 'bg-[#f2f3f5] text-[#8f959e]'
                      }`}>
                        {config.notifications.email.recipientCount > 0
                          ? `${config.notifications.email.recipientCount} ${t.logs?.alerts?.config?.notifications?.recipients || '收件人'}`
                          : (t.logs?.alerts?.config?.notifications?.notConfigured || '未配置')
                        }
                      </span>
                    </div>
                    <button
                      onClick={() => handleTest('email')}
                      disabled={config.notifications.email.recipientCount === 0 || isTesting === 'email'}
                      className="flex items-center gap-1 h-6 px-2 text-xs bg-white border border-[#e5e6eb] rounded hover:bg-[#f2f3f5] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                      {isTesting === 'email' ? (
                        <RefreshCw className="w-3 h-3 animate-spin" />
                      ) : (
                        <Send className="w-3 h-3" />
                      )}
                      <span>{t.logs?.alerts?.config?.notifications?.test || '测试'}</span>
                    </button>
                  </div>

                  {/* 测试结果 */}
                  {testResult && (
                    <div className={`p-2.5 rounded-md ${testResult.success ? 'bg-[#e8ffea] border border-[#9fdb1d]' : 'bg-[#fff3f2] border border-[#ffccc7]'}`}>
                      <div className="flex items-center gap-2">
                        {testResult.success ? (
                          <CheckCircle className="w-3.5 h-3.5 text-[#00b42a]" />
                        ) : (
                          <AlertCircle className="w-3.5 h-3.5 text-[#f54a45]" />
                        )}
                        <span className={`text-xs ${testResult.success ? 'text-[#00b42a]' : 'text-[#f54a45]'}`}>
                          {testResult.channel}: {testResult.success 
                            ? (t.logs?.alerts?.config?.notifications?.testSuccess || '测试成功')
                            : (testResult.message || t.logs?.alerts?.config?.notifications?.testFailed || '测试失败')
                          }
                        </span>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* 加载中 */}
          {isLoading && activeTab === 'config' && (
            <div className="flex items-center justify-center py-12">
              <RefreshCw className="w-8 h-8 text-[#8f959e] animate-spin" />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
