'use client';

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

// 地块数据接口
export interface FieldData {
  id: string;
  name: string;
  area: number;
  location: string;
  soilType: string;
  ph: number;
  organicMatter: number;
  nitrogen: number;
  phosphorus: number;
  potassium: number;
  soilDepth: number;
  slope: number;
  currentCrop: string;
  yield: number;
  suitabilityScore: number;
  suitabilityGrade: '高度适宜' | '一般适宜' | '不适宜';
  irrigation: string;
  drainage: string;
}

// 对比报告接口
export interface ComparisonReport {
  id: string;
  name: string;
  generatedTime: string;
  comparedFields: string[];
  fieldData: FieldData[];
}

// 状态接口
export interface ChartComparisonState {
  selectedFields: string[];
  fieldsData: FieldData[];
  isInitializing: boolean;
  reportGenerating: boolean;
  reportProgress: number;
  savedReports: ComparisonReport[];
}

// Action类型
export type ChartComparisonAction =
  | { type: 'SET_INITIALIZING'; payload: boolean }
  | { type: 'SET_SELECTED_FIELDS'; payload: string[] }
  | { type: 'ADD_FIELD'; payload: string }
  | { type: 'REMOVE_FIELD'; payload: string }
  | { type: 'SET_FIELDS_DATA'; payload: FieldData[] }
  | { type: 'SET_REPORT_GENERATING'; payload: boolean }
  | { type: 'SET_REPORT_PROGRESS'; payload: number }
  | { type: 'ADD_SAVED_REPORT'; payload: ComparisonReport }
  | { type: 'DELETE_REPORT'; payload: string };

// 初始状态
const initialState: ChartComparisonState = {
  selectedFields: ['field-1', 'field-2'],
  fieldsData: [],
  isInitializing: true,
  reportGenerating: false,
  reportProgress: 0,
  savedReports: [
    {
      id: 'report-1',
      name: '东区1号地 vs 西区2号地对比分析',
      generatedTime: '2024-10-15 14:35:22',
      comparedFields: ['东区1号地', '西区2号地'],
      fieldData: [],
    },
    {
      id: 'report-2',
      name: '东区1号地 vs 西区2号地 vs 南区3号地对比分析',
      generatedTime: '2024-10-14 09:20:15',
      comparedFields: ['东区1号地', '西区2号地', '南区3号地'],
      fieldData: [],
    },
  ],
};

// Reducer函数
export function chartComparisonReducer(
  state: ChartComparisonState,
  action: ChartComparisonAction
): ChartComparisonState {
  switch (action.type) {
    case 'SET_INITIALIZING':
      return {
        ...state,
        isInitializing: action.payload,
      };
    case 'SET_SELECTED_FIELDS':
      return {
        ...state,
        selectedFields: action.payload,
      };
    case 'ADD_FIELD':
      if (state.selectedFields.length >= 4) {
        toast.error('最多只能同时对比4个地块');
        return state;
      }
      return {
        ...state,
        selectedFields: [...state.selectedFields, action.payload],
      };
    case 'REMOVE_FIELD':
      if (state.selectedFields.length <= 2) {
        toast.error('至少需要选择2个地块进行对比');
        return state;
      }
      return {
        ...state,
        selectedFields: state.selectedFields.filter(id => id !== action.payload),
      };
    case 'SET_FIELDS_DATA':
      return {
        ...state,
        fieldsData: action.payload,
      };
    case 'SET_REPORT_GENERATING':
      return {
        ...state,
        reportGenerating: action.payload,
      };
    case 'SET_REPORT_PROGRESS':
      return {
        ...state,
        reportProgress: action.payload,
      };
    case 'ADD_SAVED_REPORT':
      return {
        ...state,
        savedReports: [action.payload, ...state.savedReports],
      };
    case 'DELETE_REPORT':
      return {
        ...state,
        savedReports: state.savedReports.filter(report => report.id !== action.payload),
      };
    default:
      return state;
  }
}

// 模拟地块数据
export const mockFieldsData: FieldData[] = [
  {
    id: 'field-1',
    name: '东区1号地',
    area: 50.5,
    location: '东经120.15°, 北纬30.25°',
    soilType: '壤土',
    ph: 6.5,
    organicMatter: 32,
    nitrogen: 1.8,
    phosphorus: 1.2,
    potassium: 18,
    soilDepth: 85,
    slope: 3,
    currentCrop: '水稻',
    yield: 750,
    suitabilityScore: 87,
    suitabilityGrade: '高度适宜',
    irrigation: '喷灌',
    drainage: '良好',
  },
  {
    id: 'field-2',
    name: '西区2号地',
    area: 45.2,
    location: '东经120.12°, 北纬30.28°',
    soilType: '粘土',
    ph: 7.8,
    organicMatter: 22,
    nitrogen: 1.3,
    phosphorus: 0.9,
    potassium: 14,
    soilDepth: 55,
    slope: 5,
    currentCrop: '玉米',
    yield: 650,
    suitabilityScore: 72,
    suitabilityGrade: '一般适宜',
    irrigation: '滴灌',
    drainage: '中等',
  },
  {
    id: 'field-3',
    name: '南区3号地',
    area: 38.8,
    location: '东经120.18°, 北纬30.22°',
    soilType: '砂土',
    ph: 8.5,
    organicMatter: 15,
    nitrogen: 0.8,
    phosphorus: 0.6,
    potassium: 10,
    soilDepth: 42,
    slope: 8,
    currentCrop: '小麦',
    yield: 480,
    suitabilityScore: 58,
    suitabilityGrade: '不适宜',
    irrigation: '漫灌',
    drainage: '较差',
  },
  {
    id: 'field-4',
    name: '北区4号地',
    area: 55.0,
    location: '东经120.20°, 北纬30.30°',
    soilType: '壤土',
    ph: 6.8,
    organicMatter: 28,
    nitrogen: 1.6,
    phosphorus: 1.0,
    potassium: 16,
    soilDepth: 75,
    slope: 2,
    currentCrop: '大豆',
    yield: 380,
    suitabilityScore: 82,
    suitabilityGrade: '高度适宜',
    irrigation: '喷灌',
    drainage: '良好',
  },
];

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

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

    initializeData();
  }, []);

  // 计算可用地块和已选地块
  const availableFields = state.fieldsData.filter(f => !state.selectedFields.includes(f.id));
  const comparisonFields = state.fieldsData.filter(f => state.selectedFields.includes(f.id));

  // 添加地块
  const handleAddField = (fieldId: string) => {
    dispatch({ type: 'ADD_FIELD', payload: fieldId });
  };

  // 移除地块
  const handleRemoveField = (fieldId: string) => {
    dispatch({ type: 'REMOVE_FIELD', payload: fieldId });
  };

  // 生成报告
  const handleGenerateReport = () => {
    dispatch({ type: 'SET_REPORT_GENERATING', payload: true });
    dispatch({ type: 'SET_REPORT_PROGRESS', payload: 0 });

    let currentProgress = 0;
    const interval = setInterval(() => {
      currentProgress += 10;
      dispatch({ type: 'SET_REPORT_PROGRESS', payload: currentProgress });

      if (currentProgress >= 100) {
        clearInterval(interval);

        // 保存新报告
        const reportName = comparisonFields.map(f => f.name).join(' vs ') + '对比分析';
        const newReport: ComparisonReport = {
          id: `report-${Date.now()}`,
          name: reportName,
          generatedTime: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }).replace(/\//g, '-'),
          comparedFields: comparisonFields.map(f => f.name),
          fieldData: comparisonFields,
        };

        // 延迟一下再设置生成完成，让用户看到100%
        setTimeout(() => {
          dispatch({ type: 'SET_REPORT_GENERATING', payload: false });
          dispatch({ type: 'ADD_SAVED_REPORT', payload: newReport });
          toast.success('对比分析报告已生成！');
        }, 300);
      }
    }, 200);
  };

  // 删除报告
  const handleDeleteReport = (reportId: string) => {
    dispatch({ type: 'DELETE_REPORT', payload: reportId });
    toast.success('报告已删除');
  };

  // 下载PDF报告
  const handleDownloadPDF = async (report?: ComparisonReport) => {
    const reportData = report || {
      name: comparisonFields.map(f => f.name).join(' vs ') + '对比分析',
      generatedTime: new Date().toLocaleString('zh-CN'),
      comparedFields: comparisonFields.map(f => f.name),
      fieldData: comparisonFields,
    };

    toast.success(`PDF报告"${reportData.name}"已生成完成！`, {
      description: '报告包含执行摘要、详细数据对比和智能分析建议',
      duration: 4000,
    });
  };

  // 下载Word报告
  const handleDownloadWord = async (report?: ComparisonReport) => {
    const reportData = report || {
      name: comparisonFields.map(f => f.name).join(' vs ') + '对比分析',
      generatedTime: new Date().toLocaleString('zh-CN'),
      comparedFields: comparisonFields.map(f => f.name),
      fieldData: comparisonFields,
    };

    toast.success(`Word报告"${reportData.name}"已生成完成！`, {
      description: '报告包含执行摘要、详细数据对比和智能分析建议',
      duration: 4000,
    });
  };

  return {
    state,
    dispatch,
    availableFields,
    comparisonFields,
    handleAddField,
    handleRemoveField,
    handleGenerateReport,
    handleDeleteReport,
    handleDownloadPDF,
    handleDownloadWord,
  };
}