'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthGuard } from '@/hooks/useAuthGuard';
import { useTranslation } from '@/hooks/useTranslation';
import { PermissionGuard } from '@/components/common/PermissionGuard';
import apiClient from '@/lib/api-client';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Activity,
  Clock,
  CheckCircle,
  XCircle,
  Play,
  Pause,
  Eye,
  Search,
  TrendingUp,
  RefreshCw,
  Zap,
  AlertTriangle,
  BarChart3,
} from 'lucide-react';
import { toast } from '@/lib/toast';
import { formatDate } from '@/utils/format';
import { useConfirm } from '@/components/common/feedback/ConfirmProvider';

interface AutomationTask {
  id: string;
  name: string;
  code: string;
  description: string | null;
  type: string;
  status: string;
  scheduleType: string;
  lastRunAt: string | null;
  lastStatus: string | null;
  nextRunAt: string | null;
  totalRuns: number;
  successRuns: number;
  failedRuns: number;
  _count?: { executions: number };
}

interface Statistics {
  totalTasks: number;
  activeTasks: number;
  totalExecutions: number;
  recentFailures: number;
}

export default function AutomationPage() {
  const router = useRouter();
  const { isReady } = useAuthGuard();
  const { t, locale } = useTranslation();
  const confirm = useConfirm();

  const [tasks, setTasks] = useState<AutomationTask[]>([]);
  const [statistics, setStatistics] = useState<Statistics | null>(null);
  const [loading, setLoading] = useState(true);
  const [filterType, setFilterType] = useState<string>('');
  const [filterStatus, setFilterStatus] = useState<string>('');
  const [searchTerm, setSearchTerm] = useState('');
  const [executingTasks, setExecutingTasks] = useState<Set<string>>(new Set());

  useEffect(() => {
    if (!isReady) return;
    loadData();
  }, [isReady, filterType, filterStatus]);

  const loadData = async () => {
    try {
      setLoading(true);
      const [statsRes, tasksRes] = await Promise.all([
        apiClient.get('/automation/statistics').catch(() => null),
        apiClient.get('/automation/tasks', {
          params: {
            type: filterType || undefined,
            status: filterStatus || undefined,
          },
        }),
      ]);

      if (statsRes) {
        setStatistics(statsRes.data || statsRes);
      }

      const tasksData = Array.isArray(tasksRes) ? tasksRes : (tasksRes?.data || []);
      setTasks(tasksData);
    } catch (error) {
      console.error('[Automation] Load data error:', error);
      toast.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleExecuteTask = async (taskId: string, taskName: string) => {
    const confirmed = await confirm({
      title: t.automation.confirmExecute,
      variant: 'primary',
    });
    if (!confirmed) return;

    try {
      setExecutingTasks(prev => new Set(prev).add(taskId));
      await apiClient.post(`/automation/tasks/${taskId}/execute`, {});
      toast.success(t.automation.executeStarted);
      loadData();
    } catch (error: any) {
      toast.error(error.message || t.automation.executeFailed);
    } finally {
      setExecutingTasks(prev => {
        const next = new Set(prev);
        next.delete(taskId);
        return next;
      });
    }
  };

  const handleToggleStatus = async (taskId: string, currentStatus: string, taskName: string) => {
    const action = currentStatus === 'ACTIVE' ? 'pause' : 'enable';
    const actionText = action === 'pause' ? t.automation.pause : t.automation.resume;

    try {
      await apiClient.post(`/automation/tasks/${taskId}/${action}`);
      toast.success(`${actionText} ${taskName} ${t.automation.success}`);
      loadData();
    } catch (error: any) {
      toast.error(error.message || `${actionText}${t.common.operationFailed}`);
    }
  };

  const getStatusColor = (status: string | null) => {
    switch (status) {
      case 'SUCCESS': return '#00b42a';
      case 'FAILED': return '#f53f3f';
      case 'RUNNING': return '#3370ff';
      case 'TIMEOUT': return '#ff7d00';
      case 'PENDING': return '#ff7d00';
      case 'CANCELLED': return '#8f959e';
      default: return '#8f959e';
    }
  };

  const getStatusBgColor = (status: string | null) => {
    switch (status) {
      case 'SUCCESS': return 'rgba(0, 180, 42, 0.1)';
      case 'FAILED': return 'rgba(245, 63, 63, 0.1)';
      case 'RUNNING': return 'rgba(51, 112, 255, 0.1)';
      case 'TIMEOUT': return 'rgba(255, 125, 0, 0.1)';
      case 'PENDING': return 'rgba(255, 125, 0, 0.1)';
      default: return '#f7f8fa';
    }
  };

  const getStatusIcon = (status: string | null) => {
    switch (status) {
      case 'SUCCESS': return <CheckCircle className="w-3.5 h-3.5" />;
      case 'FAILED': return <XCircle className="w-3.5 h-3.5" />;
      case 'RUNNING': return <RefreshCw className="w-3.5 h-3.5 animate-spin" />;
      default: return <Clock className="w-3.5 h-3.5" />;
    }
  };

  const getStatusLabel = (status: string | null) => {
    const map: Record<string, string> = {
      SUCCESS: t.automation.execSuccess,
      FAILED: t.automation.execFailed,
      RUNNING: t.automation.execRunning,
      PENDING: t.automation.execPending,
      TIMEOUT: t.automation.execTimeout,
      CANCELLED: t.automation.execCancelled,
    };
    return status ? (map[status] || status) : '-';
  };

  const getTaskStatusLabel = (status: string) => {
    const map: Record<string, string> = {
      ACTIVE: t.automation.statusActive,
      PAUSED: t.automation.statusPaused,
      DISABLED: t.automation.statusDisabled,
    };
    return map[status] || status;
  };

  const getTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      LDAP_SYNC: t.automation.typeLdapSync,
      DINGTALK_SYNC: '钉钉同步',
      DATA_CLEANUP: t.automation.typeDataCleanup,
      REPORT_GENERATION: t.automation.typeReportGeneration,
      NOTIFICATION: t.automation.typeNotification,
      BACKUP: t.automation.typeBackup,
      CUSTOM: t.automation.typeCustom,
    };
    return labels[type] || type;
  };

  const getSuccessRate = (task: AutomationTask) => {
    if (task.totalRuns === 0) return null;
    return Math.round((task.successRuns / task.totalRuns) * 100);
  };

  const filteredTasks = tasks.filter(task => {
    if (!searchTerm) return true;
    const term = searchTerm.toLowerCase();
    return (
      task.name.toLowerCase().includes(term) ||
      task.code.toLowerCase().includes(term) ||
      task.description?.toLowerCase().includes(term) ||
      getTypeLabel(task.type).toLowerCase().includes(term)
    );
  });

  if (!isReady || loading) {
    return (
      <PermissionGuard permissions={['system:read']}>
        <div className="h-full flex items-center justify-center" style={{ backgroundColor: '#f7f8fa' }}>
          <div className="w-8 h-8 rounded-full animate-spin" style={{ borderTop: '2px solid #3370ff', borderRight: '2px solid transparent' }} />
        </div>
      </PermissionGuard>
    );
  }

  return (
    <PermissionGuard permissions={['system:read']}>
      <div className="h-full flex flex-col" style={{ backgroundColor: '#f7f8fa' }}>
        {/* 标题栏 */}
        <div className="bg-white border-b" style={{ borderColor: '#e5e6eb' }}>
          <div className="px-6 h-12 flex items-center justify-between">
            <h1 className="text-base font-semibold flex items-center" style={{ color: '#1f2329' }}>
              <Zap className="w-5 h-5 mr-2" style={{ color: '#3370ff' }} />
              {t.automation.title}
            </h1>
            <button
              onClick={loadData}
              className="flex items-center gap-1.5 px-3 h-8 rounded-md text-sm transition-colors"
              style={{ color: '#646a73', border: '1px solid #e5e6eb' }}
            >
              <RefreshCw className="w-3.5 h-3.5" />
              刷新
            </button>
          </div>
        </div>

        {/* 内容区域 */}
        <div className="flex-1 overflow-auto px-6 py-6">
          <div className="max-w-7xl mx-auto space-y-6">
            {/* 统计卡片 */}
            {statistics && (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="bg-white rounded-lg p-4" style={{ border: '1px solid #e5e6eb' }}>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm" style={{ color: '#8f959e' }}>{t.automation.totalTasks}</p>
                      <p className="text-2xl font-semibold mt-1" style={{ color: '#1f2329' }}>{statistics.totalTasks}</p>
                      <p className="text-xs mt-1 flex items-center gap-1" style={{ color: '#3370ff' }}>
                        <Activity className="w-3 h-3" />
                        {statistics.activeTasks} {t.automation.active}
                      </p>
                    </div>
                    <div className="w-10 h-10 rounded-full flex items-center justify-center" style={{ backgroundColor: 'rgba(51, 112, 255, 0.08)' }}>
                      <BarChart3 className="w-5 h-5" style={{ color: '#3370ff' }} />
                    </div>
                  </div>
                </div>

                <div className="bg-white rounded-lg p-4" style={{ border: '1px solid #e5e6eb' }}>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm" style={{ color: '#8f959e' }}>{t.automation.totalExecutions}</p>
                      <p className="text-2xl font-semibold mt-1" style={{ color: '#1f2329' }}>{statistics.totalExecutions}</p>
                    </div>
                    <div className="w-10 h-10 rounded-full flex items-center justify-center" style={{ backgroundColor: 'rgba(0, 180, 42, 0.08)' }}>
                      <TrendingUp className="w-5 h-5" style={{ color: '#00b42a' }} />
                    </div>
                  </div>
                </div>

                <div className="bg-white rounded-lg p-4" style={{ border: '1px solid #e5e6eb' }}>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm" style={{ color: '#8f959e' }}>{t.automation.recentFailures}</p>
                      <p className="text-2xl font-semibold mt-1" style={{ color: statistics.recentFailures > 0 ? '#f53f3f' : '#00b42a' }}>
                        {statistics.recentFailures}
                      </p>
                    </div>
                    <div className="w-10 h-10 rounded-full flex items-center justify-center"
                      style={{ backgroundColor: statistics.recentFailures > 0 ? 'rgba(245, 63, 63, 0.08)' : 'rgba(0, 180, 42, 0.08)' }}
                    >
                      {statistics.recentFailures > 0 ? (
                        <AlertTriangle className="w-5 h-5" style={{ color: '#f53f3f' }} />
                      ) : (
                        <CheckCircle className="w-5 h-5" style={{ color: '#00b42a' }} />
                      )}
                    </div>
                  </div>
                </div>

                <div className="bg-white rounded-lg p-4" style={{ border: '1px solid #e5e6eb' }}>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm" style={{ color: '#8f959e' }}>{t.automation.successRate}</p>
                      <p className="text-2xl font-semibold mt-1" style={{ color: '#00b42a' }}>
                        {statistics.totalExecutions > 0
                          ? Math.round(((statistics.totalExecutions - statistics.recentFailures) / statistics.totalExecutions) * 100)
                          : 100}%
                      </p>
                    </div>
                    <div className="w-10 h-10 rounded-full flex items-center justify-center" style={{ backgroundColor: 'rgba(0, 180, 42, 0.08)' }}>
                      <Activity className="w-5 h-5" style={{ color: '#00b42a' }} />
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* 筛选栏 */}
            <div className="bg-white rounded-lg px-4 py-3 flex flex-col sm:flex-row gap-3" style={{ border: '1px solid #e5e6eb' }}>
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4" style={{ color: '#8f959e' }} />
                <Input
                  placeholder={t.common.search}
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-9 h-8"
                />
              </div>
              <Select value={filterType || 'ALL'} onValueChange={(value) => setFilterType(value === 'ALL' ? '' : value)}>
                <SelectTrigger className="w-full sm:w-44 h-8">
                  <SelectValue placeholder={t.automation.allTypes} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="ALL">{t.automation.allTypes}</SelectItem>
                  <SelectItem value="DINGTALK_SYNC">钉钉同步</SelectItem>
                  <SelectItem value="LDAP_SYNC">{t.automation.typeLdapSync}</SelectItem>
                  <SelectItem value="DATA_CLEANUP">{t.automation.typeDataCleanup}</SelectItem>
                  <SelectItem value="NOTIFICATION">{t.automation.typeNotification}</SelectItem>
                  <SelectItem value="CUSTOM">{t.automation.typeCustom}</SelectItem>
                </SelectContent>
              </Select>
              <Select value={filterStatus || 'ALL'} onValueChange={(value) => setFilterStatus(value === 'ALL' ? '' : value)}>
                <SelectTrigger className="w-full sm:w-36 h-8">
                  <SelectValue placeholder={t.automation.allStatuses} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="ALL">{t.automation.allStatuses}</SelectItem>
                  <SelectItem value="ACTIVE">{t.automation.statusActive}</SelectItem>
                  <SelectItem value="PAUSED">{t.automation.statusPaused}</SelectItem>
                  <SelectItem value="DISABLED">{t.automation.statusDisabled}</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 任务表格 */}
            <div className="bg-white rounded-lg overflow-hidden" style={{ border: '1px solid #e5e6eb' }}>
              <table className="w-full">
                <thead>
                  <tr style={{ backgroundColor: '#fafafa', borderBottom: '1px solid #e5e6eb' }}>
                    <th className="px-5 py-3 text-left text-xs font-medium" style={{ color: '#646a73' }}>{t.automation.taskName}</th>
                    <th className="px-4 py-3 text-left text-xs font-medium" style={{ color: '#646a73' }}>{t.automation.type}</th>
                    <th className="px-4 py-3 text-left text-xs font-medium" style={{ color: '#646a73' }}>{t.automation.status}</th>
                    <th className="px-4 py-3 text-left text-xs font-medium" style={{ color: '#646a73' }}>{t.automation.lastRun}</th>
                    <th className="px-4 py-3 text-left text-xs font-medium" style={{ color: '#646a73' }}>{t.automation.lastResult}</th>
                    <th className="px-4 py-3 text-left text-xs font-medium" style={{ color: '#646a73' }}>{t.automation.statistics}</th>
                    <th className="px-4 py-3 text-right text-xs font-medium" style={{ color: '#646a73' }}>{t.common.actions}</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredTasks.map((task) => {
                    const rate = getSuccessRate(task);
                    return (
                      <tr
                        key={task.id}
                        className="transition-colors"
                        style={{ borderBottom: '1px solid #f0f1f5' }}
                        onMouseEnter={e => (e.currentTarget.style.backgroundColor = '#fafbfc')}
                        onMouseLeave={e => (e.currentTarget.style.backgroundColor = '')}
                      >
                        {/* 任务名称 */}
                        <td className="px-5 py-4">
                          <div className="text-sm font-medium" style={{ color: '#1f2329' }}>{task.name}</div>
                          <div className="text-xs mt-0.5" style={{ color: '#8f959e' }}>{task.code}</div>
                        </td>

                        {/* 类型 */}
                        <td className="px-4 py-4">
                          <span className="inline-flex items-center px-2 py-0.5 rounded text-xs" style={{ backgroundColor: '#f7f8fa', color: '#646a73' }}>
                            {getTypeLabel(task.type)}
                          </span>
                        </td>

                        {/* 状态 */}
                        <td className="px-4 py-4">
                          <div className="flex items-center gap-2">
                            <Switch
                              checked={task.status === 'ACTIVE'}
                              onCheckedChange={() => handleToggleStatus(task.id, task.status, task.name)}
                            />
                            <span className="text-xs" style={{ color: task.status === 'ACTIVE' ? '#00b42a' : '#8f959e' }}>
                              {getTaskStatusLabel(task.status)}
                            </span>
                          </div>
                        </td>

                        {/* 最后运行 */}
                        <td className="px-4 py-4">
                          <div className="text-sm flex items-center gap-1" style={{ color: '#646a73' }}>
                            <Clock className="w-3 h-3" />
                            {task.lastRunAt ? formatDate(task.lastRunAt, locale) : '-'}
                          </div>
                        </td>

                        {/* 运行结果 */}
                        <td className="px-4 py-4">
                          {task.lastStatus ? (
                            <span
                              className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs"
                              style={{ backgroundColor: getStatusBgColor(task.lastStatus), color: getStatusColor(task.lastStatus) }}
                            >
                              {getStatusIcon(task.lastStatus)}
                              {getStatusLabel(task.lastStatus)}
                            </span>
                          ) : (
                            <span className="text-xs" style={{ color: '#c9cdd4' }}>-</span>
                          )}
                        </td>

                        {/* 统计 */}
                        <td className="px-4 py-4">
                          <div className="flex items-center gap-3 text-xs">
                            <span style={{ color: '#646a73' }}>{task.totalRuns} 次</span>
                            <span style={{ color: '#00b42a' }}>{task.successRuns} 成功</span>
                            <span style={{ color: task.failedRuns > 0 ? '#f53f3f' : '#c9cdd4' }}>{task.failedRuns} 失败</span>
                            {rate !== null && (
                              <span
                                className="font-medium"
                                style={{ color: rate >= 80 ? '#00b42a' : rate >= 50 ? '#ff7d00' : '#f53f3f' }}
                              >
                                {rate}%
                              </span>
                            )}
                          </div>
                        </td>

                        {/* 操作 */}
                        <td className="px-4 py-4">
                          <div className="flex items-center justify-end gap-2">
                            <button
                              className="flex items-center gap-1 px-2.5 py-1.5 rounded-md text-xs transition-colors"
                              style={{ color: '#646a73' }}
                              onClick={() => router.push(`/automation/${task.id}`)}
                              onMouseEnter={e => (e.currentTarget.style.backgroundColor = '#f7f8fa')}
                              onMouseLeave={e => (e.currentTarget.style.backgroundColor = '')}
                            >
                              <Eye className="w-3.5 h-3.5" />
                              查看
                            </button>
                            <button
                              className="flex items-center gap-1 px-3 py-1.5 rounded-md text-xs font-medium transition-colors disabled:cursor-not-allowed"
                              style={{
                                backgroundColor: (task.status !== 'ACTIVE' || executingTasks.has(task.id)) ? '#f2f3f5' : '#3370ff',
                                color: (task.status !== 'ACTIVE' || executingTasks.has(task.id)) ? '#86909c' : '#ffffff',
                              }}
                              disabled={task.status !== 'ACTIVE' || executingTasks.has(task.id)}
                              onClick={() => handleExecuteTask(task.id, task.name)}
                            >
                              {executingTasks.has(task.id) ? (
                                <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                              ) : (
                                <Play className="w-3.5 h-3.5" />
                              )}
                              {t.automation.execute}
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>

              {filteredTasks.length === 0 && (
                <div className="py-16 text-center">
                  <BarChart3 className="w-10 h-10 mx-auto mb-3" style={{ color: '#c9cdd4' }} />
                  <p className="text-sm" style={{ color: '#8f959e' }}>
                    {searchTerm || filterType || filterStatus ? t.common.noData : t.automation.noTasks}
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </PermissionGuard>
  );
}
