'use client';

import { useReducer, useEffect } from 'react';
import { toast } from 'sonner';

type RiskLevel = '无风险' | '轻度风险' | '中度风险' | '高度风险';
type RiskType = '干旱' | '涝渍' | '低温' | '高温' | '病虫害' | '强风';
type DisposalStatus = '未查看' | '已查看' | '处理中' | '已完成';

interface DisposalTimeline {
  time: string;
  action: string;
  operator: string;
  details?: string;
}

interface WarningRecord {
  id: string;
  fieldId: string;
  fieldName: string;
  riskType: RiskType;
  riskLevel: RiskLevel;
  warningTime: string;
  recipients: string[];
  channels: ('消息中心' | '短信' | '邮件')[];
  status: DisposalStatus;
  viewTime?: string;
  disposalPlan?: string;
  disposalPlanSubmitTime?: string;
  disposalResult?: string;
  completedTime?: string;
  responsible: string;
  timeline?: DisposalTimeline[];
  processingNotes?: string;
  resources?: string;
  actualCost?: string;
  effectEvaluation?: string;
}

// 状态接口
export interface DisposalState {
  selectedField: string;
  warningRecords: WarningRecord[];
  selectedWarning: WarningRecord | null;
  showWarningDetail: boolean;
  disposalPlan: string;
  disposalResult: string;
  processingNotes: string;
  resources: string;
  actualCost: string;
  effectEvaluation: string;
  showRecordDetail: boolean;
  selectedRecord: WarningRecord | null;
  isInitializing: boolean;
}

// Action类型
export type DisposalAction =
  | { type: 'SET_SELECTED_FIELD'; payload: string }
  | { type: 'SET_WARNING_RECORDS'; payload: WarningRecord[] }
  | { type: 'SET_SELECTED_WARNING'; payload: WarningRecord | null }
  | { type: 'SET_SHOW_WARNING_DETAIL'; payload: boolean }
  | { type: 'SET_DISPOSAL_PLAN'; payload: string }
  | { type: 'SET_DISPOSAL_RESULT'; payload: string }
  | { type: 'SET_PROCESSING_NOTES'; payload: string }
  | { type: 'SET_RESOURCES'; payload: string }
  | { type: 'SET_ACTUAL_COST'; payload: string }
  | { type: 'SET_EFFECT_EVALUATION'; payload: string }
  | { type: 'SET_SHOW_RECORD_DETAIL'; payload: boolean }
  | { type: 'SET_SELECTED_RECORD'; payload: WarningRecord | null }
  | { type: 'SET_INITIALIZING'; payload: boolean }
  | { type: 'UPDATE_WARNING_STATUS'; payload: { id: string; status: DisposalStatus } }
  | { type: 'UPDATE_WARNING_DISPOSAL'; payload: { id: string; updates: Partial<WarningRecord> } }
  | { type: 'ADD_TIMELINE_ENTRY'; payload: { id: string; entry: DisposalTimeline } };

// 初始状态
const initialState: DisposalState = {
  selectedField: 'all',
  warningRecords: [],
  selectedWarning: null,
  showWarningDetail: false,
  disposalPlan: '',
  disposalResult: '',
  processingNotes: '',
  resources: '',
  actualCost: '',
  effectEvaluation: '',
  showRecordDetail: false,
  selectedRecord: null,
  isInitializing: true,
};

// 模拟预警记录数据
export const mockWarningRecords: WarningRecord[] = [
  {
    id: 'warn-1',
    fieldId: 'field-2',
    fieldName: '西区2号地',
    riskType: '涝渍',
    riskLevel: '高度风险',
    warningTime: '2024-10-15 14:33',
    recipients: ['张三', '李四', '王五'],
    channels: ['消息中心', '短信', '邮件'],
    status: '处理中',
    viewTime: '2024-10-15 14:35',
    disposalPlan: '已启动排水系统，派遣工作组前往现场清理排水沟渠',
    disposalPlanSubmitTime: '2024-10-15 14:40',
    responsible: '张三',
    processingNotes: '现场排水沟渠已清理完毕，正在使用水泵抽水',
    resources: '水泵2台，工作人员5人',
    timeline: [
      { time: '2024-10-15 14:33', action: '预警发出', operator: '系统', details: '检测到涝渍风险等级达到高度风险' },
      { time: '2024-10-15 14:35', action: '责任人查看', operator: '张三', details: '已确认接收预警信息' },
      { time: '2024-10-15 14:40', action: '提交处置方案', operator: '张三', details: '启动排水系统，派遣工作组清理沟渠' },
      { time: '2024-10-15 14:45', action: '开始处置', operator: '张三', details: '工作组已到达现场，开始清理作业' },
    ],
  },
  {
    id: 'warn-2',
    fieldId: 'field-1',
    fieldName: '东区1号地',
    riskType: '干旱',
    riskLevel: '中度风险',
    warningTime: '2024-10-15 14:35',
    recipients: ['张三', '李四'],
    channels: ['消息中心', '短信'],
    status: '已查看',
    viewTime: '2024-10-15 14:36',
    responsible: '李四',
    timeline: [
      { time: '2024-10-15 14:35', action: '预警发出', operator: '系统', details: '检测到干旱风险等级达到中度风险' },
      { time: '2024-10-15 14:36', action: '责任人查看', operator: '李四', details: '已确认接收预警信息' },
    ],
  },
  {
    id: 'warn-3',
    fieldId: 'field-3',
    fieldName: '南区3号地',
    riskType: '低温',
    riskLevel: '轻度风险',
    warningTime: '2024-10-15 14:30',
    recipients: ['王五'],
    channels: ['消息中心'],
    status: '已完成',
    viewTime: '2024-10-15 14:31',
    disposalPlan: '准备保温材料，延迟夜间灌溉',
    disposalPlanSubmitTime: '2024-10-15 14:33',
    disposalResult: '已完成保温材料准备，作物情况良好',
    completedTime: '2024-10-15 15:20',
    responsible: '王五',
    processingNotes: '已覆盖保温膜，调整灌溉时间至白天进行',
    resources: '保温膜200平方米，人员3人',
    actualCost: '1200元',
    effectEvaluation: '处置及时有效，作物未受低温影响，长势良好',
    timeline: [
      { time: '2024-10-15 14:30', action: '预警发出', operator: '系统', details: '检测到低温风险' },
      { time: '2024-10-15 14:31', action: '责任人查看', operator: '王五', details: '已确认接收预警' },
      { time: '2024-10-15 14:33', action: '提交处置方案', operator: '王五', details: '准备保温材料，调整灌溉计划' },
      { time: '2024-10-15 14:35', action: '开始处置', operator: '王五', details: '开始准备保温材料' },
      { time: '2024-10-15 15:20', action: '处置完成', operator: '王五', details: '保温措施实施完成，作物情况良好' },
    ],
  },
  {
    id: 'warn-4',
    fieldId: 'field-4',
    fieldName: '北区4号地',
    riskType: '病虫害',
    riskLevel: '中度风险',
    warningTime: '2024-10-15 14:28',
    recipients: ['张三', '赵六'],
    channels: ['消息中心', '短信', '邮件'],
    status: '未查看',
    responsible: '赵六',
    timeline: [
      { time: '2024-10-15 14:28', action: '预警发出', operator: '系统', details: '检测到病虫害风险等级达到中度风险' },
    ],
  },
];

// Reducer函数
export function disposalReducer(
  state: DisposalState,
  action: DisposalAction
): DisposalState {
  switch (action.type) {
    case 'SET_INITIALIZING':
      return {
        ...state,
        isInitializing: action.payload,
      };
    case 'SET_SELECTED_FIELD':
      return {
        ...state,
        selectedField: action.payload,
      };
    case 'SET_WARNING_RECORDS':
      return {
        ...state,
        warningRecords: action.payload,
      };
    case 'SET_SELECTED_WARNING':
      return {
        ...state,
        selectedWarning: action.payload,
      };
    case 'SET_SHOW_WARNING_DETAIL':
      return {
        ...state,
        showWarningDetail: action.payload,
      };
    case 'SET_DISPOSAL_PLAN':
      return {
        ...state,
        disposalPlan: action.payload,
      };
    case 'SET_DISPOSAL_RESULT':
      return {
        ...state,
        disposalResult: action.payload,
      };
    case 'SET_PROCESSING_NOTES':
      return {
        ...state,
        processingNotes: action.payload,
      };
    case 'SET_RESOURCES':
      return {
        ...state,
        resources: action.payload,
      };
    case 'SET_ACTUAL_COST':
      return {
        ...state,
        actualCost: action.payload,
      };
    case 'SET_EFFECT_EVALUATION':
      return {
        ...state,
        effectEvaluation: action.payload,
      };
    case 'SET_SHOW_RECORD_DETAIL':
      return {
        ...state,
        showRecordDetail: action.payload,
      };
    case 'SET_SELECTED_RECORD':
      return {
        ...state,
        selectedRecord: action.payload,
      };
    case 'UPDATE_WARNING_STATUS':
      return {
        ...state,
        warningRecords: state.warningRecords.map(record =>
          record.id === action.payload.id
            ? { ...record, status: action.payload.status }
            : record
        ),
      };
    case 'UPDATE_WARNING_DISPOSAL':
      return {
        ...state,
        warningRecords: state.warningRecords.map(record =>
          record.id === action.payload.id
            ? { ...record, ...action.payload.updates }
            : record
        ),
      };
    case 'ADD_TIMELINE_ENTRY':
      return {
        ...state,
        warningRecords: state.warningRecords.map(record =>
          record.id === action.payload.id
            ? {
                ...record,
                timeline: [...(record.timeline || []), action.payload.entry],
              }
            : record
        ),
      };
    default:
      return state;
  }
}

// 自定义Hook
export function useDisposalTracking() {
  const [state, dispatch] = useReducer(disposalReducer, initialState);

  // 初始化数据
  useEffect(() => {
    const initializeData = () => {
      dispatch({ type: 'SET_INITIALIZING', payload: true });
      dispatch({ type: 'SET_WARNING_RECORDS', payload: mockWarningRecords });
      dispatch({ type: 'SET_INITIALIZING', payload: false });
    };

    initializeData();
  }, []);

  // 获取风险类型图标
  const getRiskTypeIcon = (type: RiskType) => {
    switch (type) {
      case '干旱': return '☀️';
      case '涝渍': return '🌧️';
      case '低温': return '❄️';
      case '高温': return '🌡️';
      case '病虫害': return '🐛';
      case '强风': return '💨';
      default: return '⚠️';
    }
  };

  // 获取状态图标
  const getStatusIcon = (status: DisposalStatus) => {
    switch (status) {
      case '未查看': return '⭕';
      case '已查看': return '👁️';
      case '处理中': return '🔄';
      case '已完成': return '✅';
      default: return '⏰';
    }
  };

  // 获取状态颜色
  const getStatusColor = (status: DisposalStatus) => {
    switch (status) {
      case '未查看': return 'text-red-600 bg-red-50';
      case '已查看': return 'text-blue-600 bg-blue-50';
      case '处理中': return 'text-orange-600 bg-orange-50';
      case '已完成': return 'text-green-600 bg-green-50';
      default: return 'text-gray-600 bg-gray-50';
    }
  };

  // 获取风险等级颜色
  const getRiskLevelColor = (level: RiskLevel) => {
    switch (level) {
      case '无风险': return 'bg-gray-500 text-white';
      case '轻度风险': return 'bg-yellow-500 text-white';
      case '中度风险': return 'bg-orange-500 text-white';
      case '高度风险': return 'bg-red-500 text-white';
      default: return 'bg-gray-500 text-white';
    }
  };

  // 查看预警详情
  const handleViewWarning = (warning: WarningRecord) => {
    dispatch({ type: 'SET_SELECTED_WARNING', payload: warning });
    dispatch({ type: 'SET_DISPOSAL_PLAN', payload: warning.disposalPlan || '' });
    dispatch({ type: 'SET_DISPOSAL_RESULT', payload: warning.disposalResult || '' });
    dispatch({ type: 'SET_PROCESSING_NOTES', payload: warning.processingNotes || '' });
    dispatch({ type: 'SET_RESOURCES', payload: warning.resources || '' });
    dispatch({ type: 'SET_ACTUAL_COST', payload: warning.actualCost || '' });
    dispatch({ type: 'SET_EFFECT_EVALUATION', payload: warning.effectEvaluation || '' });
    dispatch({ type: 'SET_SHOW_WARNING_DETAIL', payload: true });
  };

  // 更新状态
  const handleUpdateStatus = (status: DisposalStatus) => {
    if (!state.selectedWarning) return;

    const now = new Date().toLocaleString('zh-CN');
    const timeline = [...(state.selectedWarning.timeline || [])];

    if (status === '已查看' && !state.selectedWarning.viewTime) {
      dispatch({
        type: 'UPDATE_WARNING_DISPOSAL',
        payload: {
          id: state.selectedWarning.id,
          updates: { viewTime: now, status }
        }
      });
      timeline.push({
        time: now,
        action: '责任人查看',
        operator: state.selectedWarning.responsible,
        details: '已确认接收预警信息',
      });
    } else if (status === '处理中') {
      dispatch({
        type: 'UPDATE_WARNING_DISPOSAL',
        payload: {
          id: state.selectedWarning.id,
          updates: {
            disposalPlan: state.disposalPlan,
            disposalPlanSubmitTime: now,
            processingNotes: state.processingNotes,
            resources: state.resources,
            status
          }
        }
      });
      timeline.push({
        time: now,
        action: '提交处置方案',
        operator: state.selectedWarning.responsible,
        details: state.disposalPlan,
      });
      timeline.push({
        time: now,
        action: '开始处置',
        operator: state.selectedWarning.responsible,
        details: '开始执行处置方案',
      });
    } else if (status === '已完成') {
      dispatch({
        type: 'UPDATE_WARNING_DISPOSAL',
        payload: {
          id: state.selectedWarning.id,
          updates: {
            completedTime: now,
            disposalResult: state.disposalResult,
            actualCost: state.actualCost,
            effectEvaluation: state.effectEvaluation,
            status
          }
        }
      });
      timeline.push({
        time: now,
        action: '处置完成',
        operator: state.selectedWarning.responsible,
        details: state.disposalResult,
      });
    }

    dispatch({
      type: 'ADD_TIMELINE_ENTRY',
      payload: { id: state.selectedWarning.id, entry: timeline[timeline.length - 1] }
    });

    // 更新选中的预警记录
    const updatedWarning = {
      ...state.selectedWarning,
      status,
      timeline,
      ...(status === '已查看' && { viewTime: now }),
      ...(status === '处理中' && {
        disposalPlan: state.disposalPlan,
        disposalPlanSubmitTime: now,
        processingNotes: state.processingNotes,
        resources: state.resources,
      }),
      ...(status === '已完成' && {
        completedTime: now,
        disposalResult: state.disposalResult,
        actualCost: state.actualCost,
        effectEvaluation: state.effectEvaluation,
      }),
    };

    dispatch({ type: 'SET_SELECTED_WARNING', payload: updatedWarning });
    toast.success(`预警状态已更新为：${status}`);
  };

  // 查看记录
  const handleViewRecord = (record: WarningRecord) => {
    dispatch({ type: 'SET_SELECTED_RECORD', payload: record });
    dispatch({ type: 'SET_DISPOSAL_PLAN', payload: record.disposalPlan || '' });
    dispatch({ type: 'SET_DISPOSAL_RESULT', payload: record.disposalResult || '' });
    dispatch({ type: 'SET_SHOW_RECORD_DETAIL', payload: true });

    // 如果是未查看状态，自动更新为已查看
    if (record.status === '未查看') {
      handleUpdateRecordStatus(record, '已查看');
    }
  };

  // 更新记录状态
  const handleUpdateRecordStatus = (record: WarningRecord, status: DisposalStatus) => {
    const now = new Date().toLocaleString('zh-CN');
    dispatch({
      type: 'UPDATE_WARNING_DISPOSAL',
      payload: {
        id: record.id,
        updates: { status, ...(status === '已查看' && !record.viewTime ? { viewTime: now } : {}) }
      }
    });
    toast.success(`状态已更新为：${status}`);
  };

  // 保存记录处置
  const handleSaveRecordDisposal = () => {
    if (!state.selectedRecord) return;

    dispatch({
      type: 'UPDATE_WARNING_DISPOSAL',
      payload: {
        id: state.selectedRecord.id,
        updates: {
          disposalPlan: state.disposalPlan,
          disposalResult: state.disposalResult,
          status: state.disposalResult ? '已完成' : '处理中',
          completedTime: state.disposalResult ? new Date().toLocaleString('zh-CN') : undefined,
        }
      }
    });

    dispatch({ type: 'SET_SHOW_RECORD_DETAIL', payload: false });
    toast.success('处置信息已保存');
  };

  // 过滤后的预警记录
  const filteredWarnings = state.selectedField === 'all'
    ? state.warningRecords
    : state.warningRecords.filter(w => w.fieldId === state.selectedField);

  return {
    state,
    dispatch,
    filteredWarnings,
    getRiskTypeIcon,
    getStatusIcon,
    getStatusColor,
    getRiskLevelColor,
    handleViewWarning,
    handleUpdateStatus,
    handleViewRecord,
    handleUpdateRecordStatus,
    handleSaveRecordDisposal,
  };
}