import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  StyleSheet,
  Alert,
  ScrollView,
  ActivityIndicator,
  Text,
  TouchableOpacity,
  TextInput,
  Animated,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { useRoute, useNavigation } from '@react-navigation/native';
import { RouteProp } from '@react-navigation/native';
import { useTasks } from '../context/TasksContext';
import TaskForm from '../components/TaskForm';
import BottomActionBar from '../components/BottomActionBar';
import { Task, RunTaskRequest, RunTaskApiResponse } from '../types/task';
import { runTask as runTaskService } from '../services/taskService';

type RootStackParamList = {
  TaskEdit: { taskId: string };
};

type TaskEditRouteProp = RouteProp<RootStackParamList, 'TaskEdit'>;

export default function TaskEditScreen() {
  const route = useRoute<TaskEditRouteProp>();
  const navigation = useNavigation();
  const { taskId } = route.params;

  const { getTaskById, updateTask, tasks, fetchTaskDetail } = useTasks();

  const [task, setTask] = useState<Task | null>(null);
  const [originalTask, setOriginalTask] = useState<Task | null>(null);
  const [isModified, setIsModified] = useState(false);
  const [isRunLoading, setIsRunLoading] = useState(false);
  const [runResponse, setRunResponse] = useState<RunTaskApiResponse | null>(
    null,
  );

  // 添加二维码相关状态
  const [qrCodeInfo, setQrCodeInfo] = useState<string>('');
  const [isWaitingForQrCode, setIsWaitingForQrCode] = useState(true); // 默认为等待扫描状态
  const qrCodeInputRef = useRef<TextInput>(null);

  // 添加动画相关状态
  const rotateAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    const loadTask = async () => {
      let taskData = getTaskById(taskId);
      console.log('taskData', taskData);

      if (taskData && !taskData.detail) {
        await fetchTaskDetail(taskId);
        taskData = getTaskById(taskId);
      }
      if (taskData) {
        // 在这里处理 detail 字段
        let processedTask = { ...taskData };
        if (processedTask.detail && typeof processedTask.detail === 'string') {
          try {
            processedTask.detail = JSON.parse(processedTask.detail);
          } catch (e) {
            console.error('解析任务详情失败:', e);
            // 解析失败，可以根据业务需求决定如何处理，比如清空detail
            processedTask.detail = undefined;
          }
        }
        setTask(processedTask);
        setOriginalTask(processedTask);
      }
    };
    loadTask();
  }, [taskId, getTaskById, tasks, fetchTaskDetail]);

  // 聚焦到二维码输入框和启动动画
  useEffect(() => {
    if (isWaitingForQrCode && qrCodeInputRef.current) {
      // 清空二维码信息输入框
      setQrCodeInfo('');
      setTimeout(() => {
        qrCodeInputRef.current?.focus();
      }, 500);
    }

    // 启动或停止旋转动画
    if (isWaitingForQrCode) {
      // 启动旋转动画
      const rotateAnimation = Animated.loop(
        Animated.timing(rotateAnim, {
          toValue: 1,
          duration: 2000,
          useNativeDriver: true,
        }),
      );
      rotateAnimation.start();

      return () => {
        rotateAnimation.stop();
      };
    } else {
      // 停止动画并重置
      rotateAnim.setValue(0);
    }
  }, [isWaitingForQrCode, rotateAnim]);

  // 解析二维码信息并填充表单
  const parseQrCodeAndFillForm = (qrContent: string) => {
    if (
      !task ||
      !task.detail ||
      !task.detail.inputParams ||
      !qrContent.trim()
    ) {
      return;
    }

    try {
      // 清理二维码内容：移除换行符和多余空格
      const cleanedContent = qrContent
        .replace(/[\r\n\t]/g, '') // 移除所有换行符和制表符
        .replace(/\s+/g, ' ') // 多个空格替换为单个空格
        .trim();

      const qrData = JSON.parse(cleanedContent);
      console.log('二维码解析成功:', qrData);

      // 创建新的任务对象，保持原有数据不变
      const updatedTask = { ...task };

      // 确保parameters对象存在
      if (!updatedTask.parameters) {
        updatedTask.parameters = {};
      }

      // 先清空所有表单字段为空字符串
      task.detail!.inputParams.forEach(param => {
        const currentParam = updatedTask.parameters[param.name] || {};
        updatedTask.parameters[param.name] = {
          ...currentParam,
          value: '', // 清空为空字符串
        };
      });

      // 然后用二维码数据填充匹配的字段
      Object.keys(qrData).forEach(qrKey => {
        const matchingParam = task.detail!.inputParams.find(
          param => param.name === qrKey,
        );

        if (matchingParam) {
          // 根据字段类型转换值
          let convertedValue = qrData[qrKey];
          if (matchingParam.type.toLowerCase() === 'string') {
            convertedValue = String(qrData[qrKey]);
          } else if (matchingParam.type.toLowerCase() === 'number') {
            convertedValue = Number(qrData[qrKey]);
          }

          // 如果找到匹配的参数，更新其值
          const currentParam = updatedTask.parameters[qrKey] || {};
          updatedTask.parameters[qrKey] = {
            ...currentParam,
            value: convertedValue,
          };
          console.log(`二维码填充: ${qrKey} = ${convertedValue}`);
        }
      });

      setTask(updatedTask);
      if (!isModified) {
        setIsModified(true);
      }

      // 扫描成功后，按钮状态变回"扫描二维码获取信息"
      setIsWaitingForQrCode(false);
    } catch (error) {
      // 解析失败不报错，按照需求静默处理
      console.log('二维码信息解析失败，但不影响使用:', error);
    }
  };

  // 处理二维码输入框内容变化
  const handleQrCodeChange = (text: string) => {
    setQrCodeInfo(text);
    if (text.trim()) {
      parseQrCodeAndFillForm(text);
    }
  };

  const handleTaskChange = (updatedTask: Task) => {
    setTask(updatedTask);
    if (!isModified) {
      setIsModified(true);
    }
  };

  // 处理二维码扫描按钮点击
  const handleQrCodeScanButton = () => {
    if (!isWaitingForQrCode) {
      setIsWaitingForQrCode(true);
      // 聚焦到二维码输入框 (清空操作已在useEffect中处理)
      setTimeout(() => {
        qrCodeInputRef.current?.focus();
      }, 100);
    }
  };

  const handleSave = () => {
    if (task) {
      updateTask(task);
      setOriginalTask(task);
      setIsModified(false);
      Alert.alert('已保存', `任务 "${task.label}" 已被保存。`);
    }
  };

  const handleRun = async () => {
    if (!task || !task.detail || !task.detail.inputParams) {
      Alert.alert('错误', '任务数据不完整，无法运行。');
      return;
    }

    setIsRunLoading(true);
    setRunResponse(null);

    try {
      const params = task.detail.inputParams.map(p => {
        // 获取用户设置的实际值，如果用户没有设置任何值才使用默认值
        const parameter = task.parameters?.[p.name];
        const hasUserInput = parameter !== undefined;
        const actualValue = hasUserInput ? parameter.value : p.defaultValue;

        console.log(
          `运行参数 ${p.name}: 用户是否输入=${hasUserInput}, 实际值="${actualValue}" (原默认值="${p.defaultValue}")`,
        );

        return {
          name: p.name,
          type: p.type,
          label: p.label,
          required: p.required,
          defaultValue: actualValue, // 如果用户有输入（包括空值）就用用户值，否则用默认值
          remark: p.remark,
        };
      });

      const request: RunTaskRequest = {
        taskId: task.id,
        params: params,
        source_type: 1,
        source_system: 'SYSTEM',
        source_device: '666',
      };

      const result = await runTaskService(request);
      setRunResponse(result);
      Alert.alert('成功', `任务已启动, 记录ID: ${result.taskRecordId}`);
    } catch (error: any) {
      Alert.alert('运行失败', error.message || '发生未知错误');
    } finally {
      setIsRunLoading(false);
    }
  };

  const handleUndo = () => {
    setTask(originalTask);
    setIsModified(false);
    // 重置二维码相关状态
    setQrCodeInfo('');
    setIsWaitingForQrCode(true); // 重置为默认的等待扫描状态
  };

  if (!task) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#00ff00" />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <ScrollView contentContainerStyle={styles.scrollContainer}>
        {/* 二维码扫描按钮 */}
        <TouchableOpacity
          style={[
            styles.qrCodeButton,
            isWaitingForQrCode
              ? styles.qrCodeButtonWaiting
              : styles.qrCodeButtonReady,
          ]}
          onPress={handleQrCodeScanButton}
        >
          <View style={styles.qrCodeButtonContent}>
            {isWaitingForQrCode ? (
              <Animated.View
                style={[
                  styles.qrCodeButtonIcon,
                  {
                    transform: [
                      {
                        rotate: rotateAnim.interpolate({
                          inputRange: [0, 1],
                          outputRange: ['0deg', '360deg'],
                        }),
                      },
                    ],
                  },
                ]}
              >
                <Icon name="hourglass-empty" size={20} color="#ffffff" />
              </Animated.View>
            ) : (
              <Icon
                name="qr-code"
                size={20}
                color="#ffffff"
                style={styles.qrCodeButtonIcon}
              />
            )}
            <Text style={styles.qrCodeButtonText}>
              {isWaitingForQrCode ? '等待扫描二维码' : '点击启动扫码'}
            </Text>
          </View>
        </TouchableOpacity>

        {/* 隐藏的二维码信息输入框 */}
        <TextInput
          ref={qrCodeInputRef}
          style={styles.hiddenQrCodeInput}
          value={qrCodeInfo}
          onChangeText={handleQrCodeChange}
          onFocus={() => setIsWaitingForQrCode(true)}
          onBlur={() => setIsWaitingForQrCode(false)}
          placeholder="二维码信息将在此处显示"
          multiline={true}
          autoFocus={isWaitingForQrCode}
          showSoftInputOnFocus={false}
          caretHidden={true}
          editable={true}
        />

        <TaskForm task={task} onTaskChange={handleTaskChange} />
        {runResponse && (
          <View style={styles.responseContainer}>
            <Text style={styles.responseTitle}>运行结果:</Text>
            <Text style={styles.responseText}>
              {JSON.stringify(runResponse, null, 2)}
            </Text>
          </View>
        )}
      </ScrollView>
      <BottomActionBar
        onRun={handleRun}
        onSave={handleSave}
        onUndo={handleUndo}
        onBack={() => navigation.goBack()}
        isSaveDisabled={!isModified}
        isRunLoading={isRunLoading}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a1a',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#1a1a1a',
  },
  scrollContainer: {
    padding: 16,
    paddingBottom: 80,
  },
  qrCodeButton: {
    padding: 12,
    borderRadius: 8,
    marginBottom: 16,
    alignItems: 'center',
  },
  qrCodeButtonWaiting: {
    backgroundColor: '#2196F3',
  },
  qrCodeButtonReady: {
    backgroundColor: '#4CAF50',
  },
  qrCodeButtonContent: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  qrCodeButtonIcon: {
    marginRight: 8,
  },
  qrCodeButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  hiddenQrCodeInput: {
    position: 'absolute',
    top: -1000,
    left: -1000,
    width: 1,
    height: 1,
    opacity: 0,
  },
  responseContainer: {
    marginTop: 20,
    padding: 15,
    backgroundColor: '#2c2c2c',
    borderRadius: 8,
  },
  responseTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#ffffff',
    marginBottom: 10,
  },
  responseText: {
    fontSize: 14,
    color: '#e0e0e0',
    fontFamily: 'monospace',
  },
});
