import { create } from "zustand";
import { devtools } from "zustand/middleware";
import type {
  SheetData,
  FileUploadResult,
  SelectedRange,
} from "../types/sheet";
import type { AIHistory } from "../types/ai";
import type { User } from "../types/user";

interface AppState {
  // 사용자 상태
  user: User | null;
  isAuthenticated: boolean;

  // 파일 및 시트 상태
  currentFile: {
    name: string;
    size: number;
    uploadedAt: Date;
    xlsxBuffer?: ArrayBuffer; // 변환된 XLSX ArrayBuffer
  } | null;
  sheets: SheetData[];
  activeSheetId: string | null;
  selectedRange: SelectedRange | null;

  // UI 상태
  isLoading: boolean;
  loadingMessage: string;
  isHistoryPanelOpen: boolean;

  // 에러 상태
  error: string | null;
  fileUploadErrors: Array<{ fileName: string; error: string }>;

  // AI 상태
  aiHistory: AIHistory[];
  isProcessingAI: boolean;

  // 액션들
  setUser: (user: User | null) => void;
  setAuthenticated: (authenticated: boolean) => void;

  setCurrentFile: (
    file: {
      name: string;
      size: number;
      uploadedAt: Date;
      xlsxBuffer?: ArrayBuffer;
    } | null,
  ) => void;
  setSheets: (sheets: SheetData[]) => void;
  setActiveSheetId: (sheetId: string | null) => void;
  setSelectedRange: (range: SelectedRange | null) => void;

  setLoading: (loading: boolean, message?: string) => void;
  setHistoryPanelOpen: (open: boolean) => void;

  // 에러 관리
  setError: (error: string | null) => void;
  addFileUploadError: (fileName: string, error: string) => void;
  clearFileUploadErrors: () => void;

  addAIHistory: (history: AIHistory) => void;
  setProcessingAI: (processing: boolean) => void;

  // 복합 액션들
  uploadFile: (result: FileUploadResult) => void;
  resetApp: () => void;
}

const initialState = {
  user: null,
  isAuthenticated: false,
  currentFile: null,
  sheets: [],
  activeSheetId: null,
  selectedRange: null,
  isLoading: false,
  loadingMessage: "",
  isHistoryPanelOpen: false,
  error: null,
  fileUploadErrors: [],
  aiHistory: [],
  isProcessingAI: false,
};

export const useAppStore = create<AppState>()(
  devtools(
    (set, get) => ({
      ...initialState,

      // 사용자 액션
      setUser: (user) => set({ user }),
      setAuthenticated: (authenticated) =>
        set({ isAuthenticated: authenticated }),

      // 파일 및 시트 액션
      setCurrentFile: (file) => set({ currentFile: file }),
      setSheets: (sheets) => set({ sheets }),
      setActiveSheetId: (sheetId) => set({ activeSheetId: sheetId }),
      setSelectedRange: (range) => set({ selectedRange: range }),

      // UI 액션
      setLoading: (loading, message = "") =>
        set({
          isLoading: loading,
          loadingMessage: message,
        }),
      setHistoryPanelOpen: (open) => set({ isHistoryPanelOpen: open }),

      // 에러 관리
      setError: (error) => set({ error }),
      addFileUploadError: (fileName, error) =>
        set((state) => ({
          fileUploadErrors: [...state.fileUploadErrors, { fileName, error }],
        })),
      clearFileUploadErrors: () => set({ fileUploadErrors: [] }),

      // AI 액션
      addAIHistory: (history) =>
        set((state) => ({
          aiHistory: [history, ...state.aiHistory].slice(0, 50), // 최대 50개 유지
        })),
      setProcessingAI: (processing) => set({ isProcessingAI: processing }),

      // 복합 액션
      uploadFile: (result) => {
        if (result.success && result.data) {
          set({
            currentFile: {
              name: result.fileName || "Unknown",
              size: result.fileSize || 0,
              uploadedAt: new Date(),
              xlsxBuffer: result.xlsxBuffer,
            },
            sheets: result.data,
            activeSheetId: result.data[0]?.id || null,
            error: null, // 성공 시 에러 클리어
          });
        } else if (result.error) {
          set({
            error: result.error,
          });

          // 파일 업로드 에러 추가
          if (result.fileName) {
            get().addFileUploadError(result.fileName, result.error);
          }
        }
      },

      resetApp: () => set(initialState),
    }),
    {
      name: "app-store",
    },
  ),
);
