'use client';

import { ExternalDataSource, DataSourceType, DataSourceStatus, AccessMethod } from '../types';

export interface ExternalDataState {
  dataSources: ExternalDataSource[];
  filters: {
    type: string[];
    status: string[];
    provider: string[];
    searchTerm: string;
  };
  selectedDataSource: ExternalDataSource | null;
  showAddDialog: boolean;
  showUploadDialog: boolean;
  showEditDialog: boolean;
  showDataPreviewDialog: boolean;
  uploadedFile: File | null;
  uploadProgress: number;
  selectedAccessMethod: AccessMethod;
  statistics: {
    totalSources: number;
    activeSources: number;
    totalDataPoints: number;
    lastUpdateTime: string;
  };
}

export type ExternalDataAction =
  | { type: 'SET_DATA_SOURCES'; payload: ExternalDataSource[] }
  | { type: 'SET_FILTERS'; payload: Partial<ExternalDataState['filters']> }
  | { type: 'UPDATE_FILTER'; payload: { key: keyof ExternalDataState['filters']; value: any } }
  | { type: 'TOGGLE_ARRAY_FILTER'; payload: { key: 'type' | 'status' | 'provider'; value: string } }
  | { type: 'CLEAR_FILTERS' }
  | { type: 'SET_SELECTED_DATA_SOURCE'; payload: ExternalDataSource | null }
  | { type: 'SHOW_ADD_DIALOG'; payload: boolean }
  | { type: 'SHOW_UPLOAD_DIALOG'; payload: boolean }
  | { type: 'SHOW_EDIT_DIALOG'; payload: boolean }
  | { type: 'SHOW_DATA_PREVIEW_DIALOG'; payload: boolean }
  | { type: 'SET_UPLOADED_FILE'; payload: File | null }
  | { type: 'SET_UPLOAD_PROGRESS'; payload: number }
  | { type: 'SET_SELECTED_ACCESS_METHOD'; payload: AccessMethod }
  | { type: 'ADD_DATA_SOURCE'; payload: ExternalDataSource }
  | { type: 'UPDATE_DATA_SOURCE'; payload: { id: string; updates: Partial<ExternalDataSource> } }
  | { type: 'DELETE_DATA_SOURCE'; payload: string }
  | { type: 'SET_STATISTICS'; payload: Partial<ExternalDataState['statistics']> };

export const initialState: ExternalDataState = {
  dataSources: [],
  filters: {
    type: [],
    status: [],
    provider: [],
    searchTerm: '',
  },
  selectedDataSource: null,
  showAddDialog: false,
  showUploadDialog: false,
  showEditDialog: false,
  showDataPreviewDialog: false,
  uploadedFile: null,
  uploadProgress: 0,
  selectedAccessMethod: 'API对接',
  statistics: {
    totalSources: 0,
    activeSources: 0,
    totalDataPoints: 0,
    lastUpdateTime: '',
  },
};

export function externalDataReducer(state: ExternalDataState, action: ExternalDataAction): ExternalDataState {
  switch (action.type) {
    case 'SET_DATA_SOURCES':
      return {
        ...state,
        dataSources: action.payload,
      };

    case 'SET_FILTERS':
      return {
        ...state,
        filters: {
          ...state.filters,
          ...action.payload,
        },
      };

    case 'UPDATE_FILTER':
      return {
        ...state,
        filters: {
          ...state.filters,
          [action.payload.key]: action.payload.value,
        },
      };

    case 'TOGGLE_ARRAY_FILTER':
      const { key, value } = action.payload;
      const currentArray = state.filters[key];
      const newArray = currentArray.includes(value)
        ? currentArray.filter(v => v !== value)
        : [...currentArray, value];
      return {
        ...state,
        filters: {
          ...state.filters,
          [key]: newArray,
        },
      };

    case 'CLEAR_FILTERS':
      return {
        ...state,
        filters: {
          type: [],
          status: [],
          provider: [],
          searchTerm: '',
        },
      };

    case 'SET_SELECTED_DATA_SOURCE':
      return {
        ...state,
        selectedDataSource: action.payload,
      };

    case 'SHOW_ADD_DIALOG':
      return {
        ...state,
        showAddDialog: action.payload,
      };

    case 'SHOW_UPLOAD_DIALOG':
      return {
        ...state,
        showUploadDialog: action.payload,
      };

    case 'SHOW_EDIT_DIALOG':
      return {
        ...state,
        showEditDialog: action.payload,
      };

    case 'SHOW_DATA_PREVIEW_DIALOG':
      return {
        ...state,
        showDataPreviewDialog: action.payload,
      };

    case 'SET_UPLOADED_FILE':
      return {
        ...state,
        uploadedFile: action.payload,
      };

    case 'SET_UPLOAD_PROGRESS':
      return {
        ...state,
        uploadProgress: action.payload,
      };

    case 'SET_SELECTED_ACCESS_METHOD':
      return {
        ...state,
        selectedAccessMethod: action.payload,
      };

    case 'ADD_DATA_SOURCE':
      return {
        ...state,
        dataSources: [...state.dataSources, action.payload],
      };

    case 'UPDATE_DATA_SOURCE':
      return {
        ...state,
        dataSources: state.dataSources.map(ds =>
          ds.id === action.payload.id
            ? { ...ds, ...action.payload.updates }
            : ds
        ),
      };

    case 'DELETE_DATA_SOURCE':
      return {
        ...state,
        dataSources: state.dataSources.filter(ds => ds.id !== action.payload),
      };

    case 'SET_STATISTICS':
      return {
        ...state,
        statistics: {
          ...state.statistics,
          ...action.payload,
        },
      };

    default:
      return state;
  }
}

export function calculateStatistics(dataSources: ExternalDataSource[]): ExternalDataState['statistics'] {
  const totalSources = dataSources.length;
  const activeSources = dataSources.filter(ds => ds.status === '正常').length;
  const totalDataPoints = dataSources.reduce((sum, ds) => sum + ds.dataPoints, 0);
  const lastUpdateTime = dataSources
    .filter(ds => ds.status === '正常')
    .map(ds => ds.lastUpdateTime)
    .sort()
    .pop() || '';

  return {
    totalSources,
    activeSources,
    totalDataPoints,
    lastUpdateTime,
  };
}