'use client';

import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { useTranslation } from '@/hooks/useTranslation';
import { PermissionGuard } from '@/components/common/PermissionGuard';
import { API_URL } from '@/lib/api';
import {
  ArrowLeft,
  Clock,
  CheckCircle,
  XCircle,
  RefreshCw,
  AlertTriangle,
  FileText,
  Settings,
  Activity,
} from 'lucide-react';

interface TaskDetail {
  id: string;
  name: string;
  code: string;
  description: string | null;
  type: string;
  status: string;
  scheduleType: string;
  scheduleConfig: any;
  config: any;
  timeout: number;
  retryCount: number;
  lastRunAt: string | null;
  lastStatus: string | null;
  nextRunAt: string | null;
  totalRuns: number;
  successRuns: number;
  failedRuns: number;
  createdAt: string;
  updatedAt: string;
  createdBy: { displayName: string; username: string } | null;
}

interface Execution {
  id: string;
  status: string;
  startedAt: string;
  completedAt: string | null;
  duration: number | null;
  error: string | null;
  triggerType: string;
}

export default function AutomationDetailPage() {
  const router = useRouter();
  const params = useParams();
  const { t } = useTranslation();
  const taskId = params.id as string;

  const [task, setTask] = useState<TaskDetail | null>(null);
  const [executions, setExecutions] = useState<Execution[]>([]);
  const [selectedExecution, setSelectedExecution] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'info' | 'history' | 'logs'>('info');

  useEffect(() => {
    if (taskId) {
      loadTaskDetail();
      loadExecutions();
    }
  }, [taskId]);

  const loadTaskDetail = async () => {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`${API_URL}/automation/tasks/${taskId}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (response.ok) {
        const result = await response.json();
        setTask(result.data || result);
      }
    } catch (error) {
      console.error('Failed to load task:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadExecutions = async () => {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`${API_URL}/automation/tasks/${taskId}/executions`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (response.ok) {
        const result = await response.json();
        const data = result.data?.data || result.data || result;
        setExecutions(Array.isArray(data) ? data : []);
      }
    } catch (error) {
      console.error('Failed to load executions:', error);
    }
  };

  const loadExecutionDetail = async (executionId: string) => {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`${API_URL}/automation/executions/${executionId}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (response.ok) {
        const result = await response.json();
        setSelectedExecution(result.data || result);
        setActiveTab('logs');
      }
    } catch (error) {
      console.error('Failed to load execution detail:', error);
    }
  };

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

  const getStatusBgColor = (status: string) => {
    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)';
      default: return '#f7f8fa';
    }
  };

  const getStatusIcon = (status: string) => {
    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) => {
    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 map[status] || status;
  };

  const formatDuration = (ms: number | null) => {
    if (!ms) return '-';
    if (ms < 1000) return `${ms}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
    return `${Math.floor(ms / 60000)}m ${Math.floor((ms % 60000) / 1000)}s`;
  };

  const tabs = [
    { key: 'info' as const, label: t.automation.taskInfo, icon: Settings },
    { key: 'history' as const, label: `${t.automation.executionHistory} (${executions.length})`, icon: Activity },
    { key: 'logs' as const, label: t.automation.executionLogs, icon: FileText },
  ];

  if (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>
    );
  }

  if (!task) {
    return (
      <PermissionGuard permissions={['system:read']}>
        <div className="h-full flex flex-col items-center justify-center" style={{ backgroundColor: '#f7f8fa' }}>
          <AlertTriangle className="w-10 h-10 mb-3" style={{ color: '#c9cdd4' }} />
          <p className="text-sm mb-4" style={{ color: '#8f959e' }}>{t.automation.taskNotFound}</p>
          <button
            onClick={() => router.push('/automation')}
            className="flex items-center gap-1.5 px-4 h-8 rounded-md text-sm font-medium"
            style={{ backgroundColor: '#3370ff', color: '#ffffff' }}
          >
            <ArrowLeft className="w-3.5 h-3.5" />
            {t.automation.back}
          </button>
        </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 gap-3">
            <button
              onClick={() => router.push('/automation')}
              className="p-1.5 rounded-md transition-colors"
              onMouseEnter={e => (e.currentTarget.style.backgroundColor = '#f7f8fa')}
              onMouseLeave={e => (e.currentTarget.style.backgroundColor = '')}
            >
              <ArrowLeft className="w-4 h-4" style={{ color: '#646a73' }} />
            </button>
            <h1 className="text-base font-semibold" style={{ color: '#1f2329' }}>{task.name}</h1>
            <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: '#f7f8fa', color: '#8f959e' }}>{task.code}</span>
            <span
              className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs"
              style={{
                backgroundColor: task.status === 'ACTIVE' ? 'rgba(0, 180, 42, 0.1)' : '#f7f8fa',
                color: task.status === 'ACTIVE' ? '#00b42a' : '#8f959e',
              }}
            >
              {task.status === 'ACTIVE' ? t.automation.statusActive : t.automation.statusPaused}
            </span>
          </div>
        </div>

        {/* 内容区域 */}
        <div className="flex-1 overflow-auto px-6 py-6">
          <div className="max-w-7xl mx-auto">
            {/* 标签页 */}
            <div className="bg-white rounded-lg" style={{ border: '1px solid #e5e6eb' }}>
              <div className="flex" style={{ borderBottom: '1px solid #e5e6eb' }}>
                {tabs.map(tab => {
                  const Icon = tab.icon;
                  const isActive = activeTab === tab.key;
                  return (
                    <button
                      key={tab.key}
                      onClick={() => setActiveTab(tab.key)}
                      className="flex items-center gap-1.5 px-5 py-3 text-sm font-medium transition-colors"
                      style={{
                        color: isActive ? '#3370ff' : '#646a73',
                        borderBottom: isActive ? '2px solid #3370ff' : '2px solid transparent',
                        marginBottom: '-1px',
                      }}
                    >
                      <Icon className="w-4 h-4" />
                      {tab.label}
                    </button>
                  );
                })}
              </div>

              <div className="p-6">
                {/* 任务信息 */}
                {activeTab === 'info' && (
                  <div className="space-y-6">
                    <div className="grid grid-cols-2 gap-6">
                      <InfoItem label={t.automation.description} value={task.description || '-'} />
                      <InfoItem label={t.automation.type} value={task.type} />
                    </div>
                    <div className="grid grid-cols-2 gap-6">
                      <InfoItem label={t.automation.scheduleType} value={task.scheduleType} />
                      <InfoItem label={t.automation.scheduleConfig} value={JSON.stringify(task.scheduleConfig)} mono />
                    </div>
                    <div className="grid grid-cols-3 gap-6">
                      <InfoItem label={t.automation.timeout} value={`${task.timeout}ms`} />
                      <InfoItem label={t.automation.retryCount} value={String(task.retryCount)} />
                      <InfoItem label={t.automation.creator} value={task.createdBy?.displayName || '-'} />
                    </div>

                    {/* 统计 */}
                    <div>
                      <p className="text-sm font-medium mb-3" style={{ color: '#646a73' }}>{t.automation.statistics}</p>
                      <div className="grid grid-cols-3 gap-4">
                        <div className="text-center p-4 rounded-lg" style={{ backgroundColor: '#f7f8fa' }}>
                          <p className="text-2xl font-semibold" style={{ color: '#1f2329' }}>{task.totalRuns}</p>
                          <p className="text-xs mt-1" style={{ color: '#8f959e' }}>{t.automation.total}</p>
                        </div>
                        <div className="text-center p-4 rounded-lg" style={{ backgroundColor: 'rgba(0, 180, 42, 0.05)' }}>
                          <p className="text-2xl font-semibold" style={{ color: '#00b42a' }}>{task.successRuns}</p>
                          <p className="text-xs mt-1" style={{ color: '#8f959e' }}>{t.automation.success}</p>
                        </div>
                        <div className="text-center p-4 rounded-lg" style={{ backgroundColor: 'rgba(245, 63, 63, 0.05)' }}>
                          <p className="text-2xl font-semibold" style={{ color: task.failedRuns > 0 ? '#f53f3f' : '#c9cdd4' }}>{task.failedRuns}</p>
                          <p className="text-xs mt-1" style={{ color: '#8f959e' }}>{t.automation.failed}</p>
                        </div>
                      </div>
                    </div>

                    {task.config && (
                      <div>
                        <p className="text-sm font-medium mb-2" style={{ color: '#646a73' }}>{t.automation.taskConfig}</p>
                        <pre className="p-4 rounded-lg text-xs overflow-auto" style={{ backgroundColor: '#1f2329', color: '#e8e9eb' }}>
                          {JSON.stringify(task.config, null, 2)}
                        </pre>
                      </div>
                    )}
                  </div>
                )}

                {/* 执行历史 */}
                {activeTab === 'history' && (
                  <div>
                    {executions.length > 0 ? (
                      <table className="w-full">
                        <thead>
                          <tr style={{ backgroundColor: '#fafafa', borderBottom: '1px solid #e5e6eb' }}>
                            <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.startTime}</th>
                            <th className="px-4 py-3 text-left text-xs font-medium" style={{ color: '#646a73' }}>{t.automation.duration}</th>
                            <th className="px-4 py-3 text-left text-xs font-medium" style={{ color: '#646a73' }}>{t.automation.triggerType}</th>
                            <th className="px-4 py-3 text-right text-xs font-medium" style={{ color: '#646a73' }}>{t.automation.actions}</th>
                          </tr>
                        </thead>
                        <tbody>
                          {executions.map(exec => (
                            <tr
                              key={exec.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-4 py-3">
                                <span
                                  className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs"
                                  style={{ backgroundColor: getStatusBgColor(exec.status), color: getStatusColor(exec.status) }}
                                >
                                  {getStatusIcon(exec.status)}
                                  {getStatusLabel(exec.status)}
                                </span>
                              </td>
                              <td className="px-4 py-3 text-sm" style={{ color: '#646a73' }}>
                                {new Date(exec.startedAt).toLocaleString('zh-CN')}
                              </td>
                              <td className="px-4 py-3 text-sm" style={{ color: '#646a73' }}>
                                {formatDuration(exec.duration)}
                              </td>
                              <td className="px-4 py-3">
                                <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: '#f7f8fa', color: '#646a73' }}>
                                  {exec.triggerType}
                                </span>
                              </td>
                              <td className="px-4 py-3 text-right">
                                <button
                                  onClick={() => loadExecutionDetail(exec.id)}
                                  className="text-xs px-2.5 py-1 rounded transition-colors"
                                  style={{ color: '#3370ff' }}
                                  onMouseEnter={e => (e.currentTarget.style.backgroundColor = 'rgba(51, 112, 255, 0.05)')}
                                  onMouseLeave={e => (e.currentTarget.style.backgroundColor = '')}
                                >
                                  {t.automation.viewLogs}
                                </button>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    ) : (
                      <div className="py-16 text-center">
                        <Clock className="w-10 h-10 mx-auto mb-3" style={{ color: '#c9cdd4' }} />
                        <p className="text-sm" style={{ color: '#8f959e' }}>{t.automation.noExecutions}</p>
                      </div>
                    )}
                  </div>
                )}

                {/* 执行日志 */}
                {activeTab === 'logs' && (
                  <div>
                    {selectedExecution ? (
                      <div className="space-y-4">
                        <div className="flex items-center justify-between pb-4" style={{ borderBottom: '1px solid #f0f1f5' }}>
                          <div>
                            <div className="text-sm font-medium" style={{ color: '#1f2329' }}>
                              {t.automation.executionId}: <span className="font-mono">{selectedExecution.id.slice(0, 8)}</span>
                            </div>
                            <div className="text-xs mt-1" style={{ color: '#8f959e' }}>
                              {new Date(selectedExecution.startedAt).toLocaleString('zh-CN')}
                            </div>
                          </div>
                          <span
                            className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs"
                            style={{ backgroundColor: getStatusBgColor(selectedExecution.status), color: getStatusColor(selectedExecution.status) }}
                          >
                            {getStatusIcon(selectedExecution.status)}
                            {getStatusLabel(selectedExecution.status)}
                          </span>
                        </div>

                        {selectedExecution.error && (
                          <div className="p-4 rounded-lg" style={{ backgroundColor: 'rgba(245, 63, 63, 0.05)', border: '1px solid rgba(245, 63, 63, 0.2)' }}>
                            <div className="flex items-center gap-1.5 mb-2">
                              <XCircle className="w-4 h-4" style={{ color: '#f53f3f' }} />
                              <span className="text-sm font-medium" style={{ color: '#f53f3f' }}>{t.automation.errorMessage}</span>
                            </div>
                            <pre className="text-xs whitespace-pre-wrap" style={{ color: '#f53f3f' }}>
                              {selectedExecution.error}
                            </pre>
                          </div>
                        )}

                        {selectedExecution.logs && (
                          <div>
                            <p className="text-sm font-medium mb-2" style={{ color: '#646a73' }}>{t.automation.executionLogs}</p>
                            <pre className="p-4 rounded-lg text-xs overflow-auto max-h-96" style={{ backgroundColor: '#1f2329', color: '#e8e9eb' }}>
                              {selectedExecution.logs}
                            </pre>
                          </div>
                        )}

                        {selectedExecution.result && (
                          <div>
                            <p className="text-sm font-medium mb-2" style={{ color: '#646a73' }}>{t.automation.executionResult}</p>
                            <pre className="p-4 rounded-lg text-xs overflow-auto" style={{ backgroundColor: '#fafafa', color: '#1f2329' }}>
                              {JSON.stringify(selectedExecution.result, null, 2)}
                            </pre>
                          </div>
                        )}
                      </div>
                    ) : (
                      <div className="py-16 text-center">
                        <FileText className="w-10 h-10 mx-auto mb-3" style={{ color: '#c9cdd4' }} />
                        <p className="text-sm" style={{ color: '#8f959e' }}>{t.automation.selectExecution}</p>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </PermissionGuard>
  );
}

function InfoItem({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
  return (
    <div>
      <p className="text-xs mb-1.5" style={{ color: '#8f959e' }}>{label}</p>
      <p className={`text-sm ${mono ? 'font-mono' : ''}`} style={{ color: '#1f2329' }}>{value}</p>
    </div>
  );
}
