import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
  StyleSheet,
  Text,
  View,
  FlatList,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
  TextInput,
} from 'react-native';
import { Picker } from '@react-native-picker/picker';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { TaskStatus } from '../types/task';
import { getTaskRunList, terminateTask } from '../services/taskService';

// 任务状态选项
const statusOptions = [
  { label: '全部', value: undefined },
  { label: '待分配', value: TaskStatus.WAITING },
  { label: '执行中', value: TaskStatus.RUNNING },
  { label: '已暂停', value: TaskStatus.PAUSED },
  { label: '已完成', value: TaskStatus.COMPLETED },
  { label: '已失败', value: TaskStatus.FAILED },
  { label: '已终止', value: TaskStatus.TERMINATED },
];

interface TaskRunItem {
  id: string;
  parentId: string;
  vwedTaskId: string;
  vwedTaskParentId: string;
  sceneId: string;
  name: string;
  description?: string;
  priority: number;
  isPeriodic: number;
  needAmr: number;
  amrName: string;
  status: TaskStatus;
  stopReason?: string;
  createBy: string;
  createTime: string;
  startTime?: string;
  endTime?: string;
  runDuration: number;
}

// 提取任务项组件并使用 memo 优化
const TaskItem = React.memo<{
  item: TaskRunItem;
  isSelectionMode: boolean;
  isSelected: boolean;
  isOperating: boolean;
  onToggleSelection: (taskId: string) => void;
  onTaskOperation: (taskId: string) => void;
  statusDisplayMap: { [key: number]: { text: string; color: string } };
}>(
  ({
    item,
    isSelectionMode,
    isSelected,
    isOperating,
    onToggleSelection,
    onTaskOperation,
    statusDisplayMap,
  }) => {
    const statusInfo =
      statusDisplayMap[item.status] || statusDisplayMap[TaskStatus.WAITING];

    // 格式化时间 - 移到组件内部避免重复计算
    const formatTime = useCallback((timeString?: string) => {
      if (!timeString) return '--';
      try {
        return new Date(timeString).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
        });
      } catch {
        return timeString;
      }
    }, []);

    const handlePress = useCallback(() => {
      if (isSelectionMode) {
        onToggleSelection(item.id);
      }
    }, [isSelectionMode, onToggleSelection, item.id]);

    const handleCheckboxPress = useCallback(() => {
      onToggleSelection(item.id);
    }, [onToggleSelection, item.id]);

    const handleOperationPress = useCallback(() => {
      onTaskOperation(item.id);
    }, [onTaskOperation, item.id]);

    return (
      <TouchableOpacity
        style={[styles.taskItem, isSelected ? styles.taskItemSelected : null]}
        onPress={handlePress}
        activeOpacity={isSelectionMode ? 0.7 : 1}
      >
        <View style={styles.taskHeader}>
          <View style={styles.taskTitleContainer}>
            {isSelectionMode && (
              <TouchableOpacity
                style={styles.checkboxContainer}
                onPress={handleCheckboxPress}
              >
                <MaterialIcons
                  name={isSelected ? 'check-box' : 'check-box-outline-blank'}
                  size={20}
                  color={isSelected ? '#4CAF50' : '#666'}
                />
              </TouchableOpacity>
            )}
            <Text
              style={[
                styles.taskName,
                isSelectionMode ? styles.taskNameWithCheckbox : null,
              ]}
              numberOfLines={1}
            >
              {item.name}
            </Text>
            <View
              style={[
                styles.statusBadge,
                { backgroundColor: statusInfo.color },
              ]}
            >
              <Text style={styles.statusText}>{statusInfo.text}</Text>
            </View>
          </View>
        </View>

        <View style={styles.taskDetails}>
          <Text style={styles.taskDescription} numberOfLines={2}>
            {item.description || '暂无描述'}
          </Text>

          <View style={styles.timeContainer}>
            <Text style={styles.timeLabel}>创建时间: </Text>
            <Text style={styles.timeValue}>{formatTime(item.createTime)}</Text>
          </View>

          {item.startTime && (
            <View style={styles.timeContainer}>
              <Text style={styles.timeLabel}>开始时间: </Text>
              <Text style={styles.timeValue}>{formatTime(item.startTime)}</Text>
            </View>
          )}

          {item.endTime && (
            <View style={styles.timeContainer}>
              <Text style={styles.timeLabel}>结束时间: </Text>
              <Text style={styles.timeValue}>{formatTime(item.endTime)}</Text>
            </View>
          )}
        </View>

        {!isSelectionMode && (
          <View style={styles.actionContainer}>
            {(item.status === TaskStatus.WAITING ||
              item.status === TaskStatus.RUNNING ||
              item.status === TaskStatus.PAUSED) && (
              <TouchableOpacity
                style={[styles.actionButton, styles.terminateButton]}
                onPress={handleOperationPress}
                disabled={isOperating}
              >
                {isOperating ? (
                  <ActivityIndicator size="small" color="#ffffff" />
                ) : (
                  <>
                    <MaterialIcons name="stop" size={16} color="#ffffff" />
                    <Text style={styles.actionButtonText}>终止</Text>
                  </>
                )}
              </TouchableOpacity>
            )}
          </View>
        )}
      </TouchableOpacity>
    );
  },
);

TaskItem.displayName = 'TaskItem';

export default function RunScreen() {
  const [tasks, setTasks] = useState<TaskRunItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  // 筛选状态
  const [filterStatus, setFilterStatus] = useState<TaskStatus | undefined>(
    undefined,
  );
  const [filterName, setFilterName] = useState('');

  // 操作状态
  const [operatingTaskId, setOperatingTaskId] = useState<string | null>(null);

  // 批量操作状态
  const [selectedTasks, setSelectedTasks] = useState<Set<string>>(new Set());
  const [isSelectionMode, setIsSelectionMode] = useState(false);
  const [batchOperating, setBatchOperating] = useState(false);

  // 使用 useMemo 缓存状态显示配置
  const statusDisplayMap = useMemo(
    () => ({
      [TaskStatus.WAITING]: { text: '待分配', color: '#9E9E9E' },
      [TaskStatus.RUNNING]: { text: '执行中', color: '#2196F3' },
      [TaskStatus.PAUSED]: { text: '已暂停', color: '#FF9800' },
      [TaskStatus.COMPLETED]: { text: '已完成', color: '#4CAF50' },
      [TaskStatus.FAILED]: { text: '已失败', color: '#F44336' },
      [TaskStatus.TERMINATED]: { text: '已终止', color: '#9C27B0' },
    }),
    [],
  );

  // 加载任务列表
  const loadTasks = useCallback(
    async (isRefresh = false) => {
      if (isRefresh) {
        setRefreshing(true);
      } else {
        setLoading(true);
      }

      try {
        const params = {
          status: filterStatus,
          name: filterName.trim() || undefined,
          pageNum: 1,
          pageSize: 100,
        };

        const response = await getTaskRunList(params);
        setTasks(response || []);
      } catch (error) {
        console.error('加载任务列表失败:', error);
        Alert.alert('错误', '加载任务列表失败，请重试');
        setTasks([]);
      } finally {
        setLoading(false);
        setRefreshing(false);
      }
    },
    [filterStatus, filterName],
  );

  // 初始加载
  useEffect(() => {
    loadTasks();
  }, [loadTasks]);

  // 刷新任务列表
  const handleRefresh = useCallback(() => {
    loadTasks(true);
  }, [loadTasks]);

  // 重置筛选
  const handleResetFilter = useCallback(() => {
    setFilterStatus(undefined);
    setFilterName('');
  }, []);

  // 切换选择模式
  const toggleSelectionMode = useCallback(() => {
    setIsSelectionMode(!isSelectionMode);
    setSelectedTasks(new Set());
  }, [isSelectionMode]);

  // 选择/取消选择任务
  const toggleTaskSelection = useCallback((taskId: string) => {
    setSelectedTasks(prev => {
      const newSelection = new Set(prev);
      if (newSelection.has(taskId)) {
        newSelection.delete(taskId);
      } else {
        newSelection.add(taskId);
      }
      return newSelection;
    });
  }, []);

  // 全选/取消全选
  const toggleSelectAll = useCallback(() => {
    if (selectedTasks.size === tasks.length) {
      setSelectedTasks(new Set());
    } else {
      setSelectedTasks(new Set(tasks.map(task => task.id)));
    }
  }, [selectedTasks.size, tasks]);

  // 批量终止任务
  const handleBatchTerminate = useCallback(async () => {
    if (selectedTasks.size === 0) {
      Alert.alert('提示', '请先选择要终止的任务');
      return;
    }

    Alert.alert(
      '确认操作',
      `确定要终止选中的 ${selectedTasks.size} 个任务吗？`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          style: 'destructive',
          onPress: async () => {
            setBatchOperating(true);
            try {
              const promises = Array.from(selectedTasks).map(taskId =>
                terminateTask(taskId),
              );
              await Promise.all(promises);
              Alert.alert('成功', `已成功终止 ${selectedTasks.size} 个任务`);
              setSelectedTasks(new Set());
              setIsSelectionMode(false);
              loadTasks();
            } catch (error) {
              console.error('批量终止任务失败:', error);
              Alert.alert('错误', '批量终止任务失败，请重试');
            } finally {
              setBatchOperating(false);
            }
          },
        },
      ],
    );
  }, [selectedTasks, loadTasks]);

  // 任务操作 - 只保留终止操作
  const handleTaskOperation = useCallback(
    async (taskId: string) => {
      setOperatingTaskId(taskId);

      try {
        await terminateTask(taskId);
        Alert.alert('成功', '终止任务成功');
        // 重新加载任务列表
        loadTasks();
      } catch (error) {
        console.error('终止任务失败:', error);
        Alert.alert('错误', '终止任务失败，请重试');
      } finally {
        setOperatingTaskId(null);
      }
    },
    [loadTasks],
  );

  // 优化的渲染任务项函数
  const renderTaskItem = useCallback(
    ({ item }: { item: TaskRunItem }) => {
      const isOperating = operatingTaskId === item.id;
      const isSelected = selectedTasks.has(item.id);

      return (
        <TaskItem
          item={item}
          isSelectionMode={isSelectionMode}
          isSelected={isSelected}
          isOperating={isOperating}
          onToggleSelection={toggleTaskSelection}
          onTaskOperation={handleTaskOperation}
          statusDisplayMap={statusDisplayMap}
        />
      );
    },
    [
      operatingTaskId,
      selectedTasks,
      isSelectionMode,
      toggleTaskSelection,
      handleTaskOperation,
      statusDisplayMap,
    ],
  );

  // 优化 keyExtractor
  const keyExtractor = useCallback((item: TaskRunItem) => item.id, []);

  // 渲染分隔符
  const renderSeparator = useCallback(
    () => <View style={styles.separator} />,
    [],
  );

  // 渲染空列表组件
  const renderEmptyComponent = useCallback(
    () => (
      <View style={styles.emptyContainer}>
        <MaterialIcons name="assignment" size={48} color="#666" />
        <Text style={styles.emptyText}>暂无任务数据</Text>
      </View>
    ),
    [],
  );

  return (
    <View style={styles.container}>
      {/* 顶部操作区域 */}
      <View style={styles.topActionContainer}>
        <View style={styles.actionButtonsContainer}>
          <TouchableOpacity
            style={[
              styles.actionBtn,
              isSelectionMode ? styles.actionBtnActive : null,
            ]}
            onPress={toggleSelectionMode}
          >
            <MaterialIcons
              name={isSelectionMode ? 'check-circle' : 'radio-button-unchecked'}
              size={16}
              color="#ffffff"
            />
            <Text style={styles.actionBtnText}>
              {isSelectionMode ? '取消选择' : '批量选择'}
            </Text>
          </TouchableOpacity>

          {isSelectionMode && (
            <>
              <TouchableOpacity
                style={styles.actionBtn}
                onPress={toggleSelectAll}
              >
                <MaterialIcons
                  name={
                    selectedTasks.size === tasks.length
                      ? 'deselect'
                      : 'select-all'
                  }
                  size={16}
                  color="#ffffff"
                />
                <Text style={styles.actionBtnText}>
                  {selectedTasks.size === tasks.length ? '取消全选' : '全选'}
                </Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.actionBtn, styles.terminateBtn]}
                onPress={handleBatchTerminate}
                disabled={selectedTasks.size === 0 || batchOperating}
              >
                {batchOperating ? (
                  <ActivityIndicator size="small" color="#ffffff" />
                ) : (
                  <MaterialIcons name="stop" size={16} color="#ffffff" />
                )}
                <Text style={styles.actionBtnText}>
                  终止 ({selectedTasks.size})
                </Text>
              </TouchableOpacity>
            </>
          )}
        </View>
      </View>

      {/* 筛选区域 */}
      <View style={styles.filterContainer}>
        <View style={styles.filterRow}>
          <View style={styles.statusFilterContainer}>
            <Text style={styles.filterLabel}>任务状态:</Text>
            <View style={styles.pickerContainer}>
              <Picker
                selectedValue={filterStatus}
                onValueChange={value => setFilterStatus(value)}
                style={styles.picker}
                dropdownIconColor="#ffffff"
                mode="dropdown"
              >
                {statusOptions.map(option => (
                  <Picker.Item
                    key={option.label}
                    label={option.label}
                    value={option.value}
                  />
                ))}
              </Picker>
            </View>
          </View>

          <TouchableOpacity
            style={styles.resetButton}
            onPress={handleResetFilter}
          >
            <MaterialIcons name="refresh" size={16} color="#ffffff" />
            <Text style={styles.resetButtonText}>重置</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.nameFilterContainer}>
          <TextInput
            style={styles.nameInput}
            placeholder="输入任务名称筛选..."
            placeholderTextColor="#999"
            value={filterName}
            onChangeText={setFilterName}
            returnKeyType="search"
            onSubmitEditing={() => loadTasks()}
          />
          <TouchableOpacity
            style={styles.searchButton}
            onPress={() => loadTasks()}
          >
            <MaterialIcons name="search" size={20} color="#ffffff" />
          </TouchableOpacity>
        </View>
      </View>

      {/* 任务列表 */}
      {loading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#2196F3" />
          <Text style={styles.loadingText}>加载中...</Text>
        </View>
      ) : (
        <FlatList
          data={tasks}
          renderItem={renderTaskItem}
          keyExtractor={keyExtractor}
          refreshing={refreshing}
          onRefresh={handleRefresh}
          ItemSeparatorComponent={renderSeparator}
          ListEmptyComponent={renderEmptyComponent}
          contentContainerStyle={
            tasks.length === 0 ? styles.emptyList : undefined
          }
          // 性能优化配置
          removeClippedSubviews={true}
          maxToRenderPerBatch={10}
          windowSize={10}
          initialNumToRender={10}
          updateCellsBatchingPeriod={50}
          // 避免重复渲染
          extraData={{
            selectedTasks: selectedTasks.size,
            isSelectionMode,
            operatingTaskId,
          }}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#121212',
  },
  filterContainer: {
    backgroundColor: '#1a1a1a',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#333',
  },
  filterRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  statusFilterContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  filterLabel: {
    color: '#ffffff',
    fontSize: 14,
    marginRight: 8,
  },
  pickerContainer: {
    flex: 1,
    backgroundColor: '#333',
    borderRadius: 4,
    marginRight: 12,
    height: 40,
    justifyContent: 'center',
  },
  picker: {
    color: '#ffffff',
    height: 60,
    width: '100%',
  },

  resetButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#666',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 4,
    height: 40,
    justifyContent: 'center',
  },
  resetButtonText: {
    color: '#ffffff',
    fontSize: 12,
    marginLeft: 4,
  },
  nameFilterContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  nameInput: {
    flex: 1,
    backgroundColor: '#333',
    color: '#ffffff',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 4,
    marginRight: 8,
  },
  searchButton: {
    backgroundColor: '#2196F3',
    padding: 8,
    borderRadius: 4,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    color: '#ffffff',
    marginTop: 8,
  },
  taskItem: {
    backgroundColor: '#1a1a1a',
    padding: 16,
  },
  taskHeader: {
    marginBottom: 8,
  },
  taskTitleContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  taskName: {
    flex: 1,
    color: '#ffffff',
    fontSize: 16,
    fontWeight: 'bold',
    marginRight: 8,
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  statusText: {
    color: '#ffffff',
    fontSize: 12,
    fontWeight: 'bold',
  },
  taskDetails: {
    marginBottom: 12,
  },
  taskDescription: {
    color: '#ccc',
    fontSize: 14,
    marginBottom: 8,
  },
  timeContainer: {
    flexDirection: 'row',
    marginBottom: 4,
  },
  timeLabel: {
    color: '#999',
    fontSize: 12,
    minWidth: 60,
  },
  timeValue: {
    color: '#ccc',
    fontSize: 12,
    flex: 1,
  },
  actionContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  actionButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 4,
    marginLeft: 8,
  },
  pauseButton: {
    backgroundColor: '#FF9800',
  },
  continueButton: {
    backgroundColor: '#4CAF50',
  },
  terminateButton: {
    backgroundColor: '#F44336',
  },
  actionButtonText: {
    color: '#ffffff',
    fontSize: 12,
    marginLeft: 4,
  },
  separator: {
    height: 1,
    backgroundColor: '#333',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: 100,
  },
  emptyText: {
    color: '#666',
    fontSize: 16,
    marginTop: 16,
  },
  emptyList: {
    flex: 1,
  },
  topActionContainer: {
    backgroundColor: '#1a1a1a',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#333',
  },
  actionButtonsContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    flexWrap: 'wrap',
  },
  actionBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#2196F3',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 4,
    marginRight: 8,
    marginBottom: 4,
  },
  actionBtnActive: {
    backgroundColor: '#4CAF50',
  },
  actionBtnText: {
    color: '#ffffff',
    fontSize: 12,
    marginLeft: 4,
  },
  terminateBtn: {
    backgroundColor: '#F44336',
  },
  taskItemSelected: {
    backgroundColor: '#2a2a2a',
    borderLeftWidth: 4,
    borderLeftColor: '#4CAF50',
  },
  checkboxContainer: {
    marginRight: 12,
    padding: 4,
  },
  taskNameWithCheckbox: {
    flex: 1,
  },
});
