'use client';

import { useReducer } from 'react';

// 地块数据接口
export interface DrawField {
  id: string;
  name: string;
  points: { x: number; y: number }[];
  color: string;
  area?: number;
  perimeter?: number;
}

// 绘制几何接口
export interface DrawGeometry {
  type: 'point' | 'line' | 'polygon' | 'rectangle' | 'circle';
  points: { x: number; y: number }[];
  area?: number;
  perimeter?: number;
  valid?: boolean;
}

// 绘制编辑状态接口
export interface DrawEditState {
  showAdvancedEditor: boolean;
  activeTab: 'draw' | 'edit' | 'guide';
  fields: DrawField[];
  showSaveDialog: boolean;
  pendingGeometry: DrawGeometry | null;
}

// Action类型
export type DrawEditAction =
  | { type: 'SET_SHOW_ADVANCED_EDITOR'; payload: boolean }
  | { type: 'SET_ACTIVE_TAB'; payload: 'draw' | 'edit' | 'guide' }
  | { type: 'SET_FIELDS'; payload: DrawField[] }
  | { type: 'UPDATE_FIELD'; payload: { id: string; updates: Partial<DrawField> } }
  | { type: 'ADD_FIELD'; payload: DrawField }
  | { type: 'DELETE_FIELD'; payload: string }
  | { type: 'SET_SHOW_SAVE_DIALOG'; payload: boolean }
  | { type: 'SET_PENDING_GEOMETRY'; payload: DrawGeometry | null };

// 计算面积的辅助函数
const calculateArea = (points: { x: number; y: number }[]): number => {
  if (points.length < 3) return 0;
  let area = 0;
  for (let i = 0; i < points.length; i++) {
    const j = (i + 1) % points.length;
    area += points[i].x * points[j].y;
    area -= points[j].x * points[i].y;
  }
  const squareMeters = Math.abs(area) * 0.25;
  return squareMeters / 666.67; // 转换为亩
};

// 计算周长的辅助函数
const calculatePerimeter = (points: { x: number; y: number }[]): number => {
  if (points.length < 2) return 0;
  let perimeter = 0;
  for (let i = 0; i < points.length; i++) {
    const j = (i + 1) % points.length;
    const dx = points[j].x - points[i].x;
    const dy = points[j].y - points[i].y;
    perimeter += Math.sqrt(dx * dx + dy * dy);
  }
  return perimeter * 0.5; // 转换为米
};

// 初始状态
const initialState: DrawEditState = {
  showAdvancedEditor: false,
  activeTab: 'draw',
  fields: [
    {
      id: 'field-1',
      name: '地块A',
      points: [
        { x: 200, y: 150 },
        { x: 350, y: 150 },
        { x: 350, y: 280 },
        { x: 200, y: 280 }
      ],
      color: '#22c55e',
      area: calculateArea([
        { x: 200, y: 150 },
        { x: 350, y: 150 },
        { x: 350, y: 280 },
        { x: 200, y: 280 }
      ]),
      perimeter: calculatePerimeter([
        { x: 200, y: 150 },
        { x: 350, y: 150 },
        { x: 350, y: 280 },
        { x: 200, y: 280 }
      ])
    },
    {
      id: 'field-2',
      name: '地块B',
      points: [
        { x: 380, y: 150 },
        { x: 520, y: 150 },
        { x: 520, y: 280 },
        { x: 380, y: 280 }
      ],
      color: '#3b82f6',
      area: calculateArea([
        { x: 380, y: 150 },
        { x: 520, y: 150 },
        { x: 520, y: 280 },
        { x: 380, y: 280 }
      ]),
      perimeter: calculatePerimeter([
        { x: 380, y: 150 },
        { x: 520, y: 150 },
        { x: 520, y: 280 },
        { x: 380, y: 280 }
      ])
    },
    {
      id: 'field-3',
      name: '地块C',
      points: [
        { x: 200, y: 310 },
        { x: 350, y: 310 },
        { x: 350, y: 440 },
        { x: 200, y: 440 }
      ],
      color: '#f97316',
      area: calculateArea([
        { x: 200, y: 310 },
        { x: 350, y: 310 },
        { x: 350, y: 440 },
        { x: 200, y: 440 }
      ]),
      perimeter: calculatePerimeter([
        { x: 200, y: 310 },
        { x: 350, y: 310 },
        { x: 350, y: 440 },
        { x: 200, y: 440 }
      ])
    }
  ],
  showSaveDialog: false,
  pendingGeometry: null,
};

// Reducer函数
export function drawEditReducer(state: DrawEditState, action: DrawEditAction): DrawEditState {
  switch (action.type) {
    case 'SET_SHOW_ADVANCED_EDITOR':
      return { ...state, showAdvancedEditor: action.payload };

    case 'SET_ACTIVE_TAB':
      return { ...state, activeTab: action.payload };

    case 'SET_FIELDS':
      return { ...state, fields: action.payload };

    case 'UPDATE_FIELD':
      return {
        ...state,
        fields: state.fields.map(field =>
          field.id === action.payload.id
            ? { ...field, ...action.payload.updates }
            : field
        )
      };

    case 'ADD_FIELD':
      return { ...state, fields: [...state.fields, action.payload] };

    case 'DELETE_FIELD':
      return {
        ...state,
        fields: state.fields.filter(field => field.id !== action.payload)
      };

    case 'SET_SHOW_SAVE_DIALOG':
      return { ...state, showSaveDialog: action.payload };

    case 'SET_PENDING_GEOMETRY':
      return { ...state, pendingGeometry: action.payload };

    default:
      return state;
  }
}

// 导出初始状态和类型
export { initialState };
export type { DrawEditAction, DrawField, DrawGeometry, DrawEditState };