import { create } from 'zustand';
import { query } from '@kevisual/resources/modules/query';
import { sortBy } from 'lodash-es';
import { toast } from 'react-toastify';
import { useSettingsStore } from './settings';

export type Resource = {
  name: string;
  lastModified: string;
  etag: string;
  metaData: Record<string, string>;
  size: number;
  prefix?: string;
};
interface ResourceStore {
  resources: Resource[];
  loading: boolean;
  setLoading: (loading: boolean) => void;
  list: Resource[];
  setList: (list: Resource[]) => void;
  prefix: string;
  setPrefix: (prefix: string) => void;
  download: (resource: Resource) => void;
  listType: 'table' | 'card';
  setListType: (listType: 'table' | 'card') => void;
  init: () => void;
  /**
   * 打开前缀
   * @param prefix 前缀
   */
  onOpenPrefix: (prefix: string) => void;
  getList: () => Promise<void>;
  deleteFile: (resource: Resource) => Promise<void>;
}

export const useResourceStore = create<ResourceStore>((set, get) => ({
  resources: [],
  loading: false,
  setLoading: (loading: boolean) => set({ loading }),
  list: [],
  setList: (list: any[]) => set({ list }),
  prefix: '',
  setPrefix: (prefix: string) => set({ prefix }),
  getList: async () => {
    set({ loading: true });
    const { prefix, getList } = get();
    if (!prefix) {
      setTimeout(() => {
        getList();
      }, 2000);
      return;
    }
    const res = await query.post({
      path: 'file',
      key: 'list',
      data: {
        prefix,
      },
    });
    set({ loading: false });
    console.log(res);
    if (res.code === 200) {
      const list = res.data;
      const sortedList = sortBy(list, [(item) => !item.prefix]);
      set({ list: sortedList });
    } else {
      toast.error(res.message || 'Request failed');
    }
  },
  download: (resource: Resource) => {
    const { baseUrl, settings } = useSettingsStore.getState();
    const username = settings?.username;
    const _url = new URL(`${baseUrl}/api/s1/share/${username}/${resource?.name}`);
    _url.searchParams.set('download', 'true');
    const downloadUrl = _url.toString();
    console.log('downloadUrl', downloadUrl);
    const a = document.createElement('a');
    a.href = downloadUrl;
    a.download = resource.name;
    a.click();
  },
  listType: 'table',
  setListType: (listType: 'table' | 'card') => {
    localStorage.setItem('listType', listType);
    set({ listType });
  },
  init: () => {
    const listType = localStorage.getItem('listType');
    if (listType) {
      set({ listType: listType as 'table' | 'card' });
    }
  },
  onOpenPrefix: (prefix: string) => {
    set({ prefix });
    get().getList();
  },
  deleteFile: async (resource: Resource) => {
    console.log('deleteFile', resource);
    const name = resource.name;
    if (!name) {
      toast.error('Resource is not a file');
      return;
    }
    const res = await query.post({
      path: 'file',
      key: 'delete',
      data: {
        prefix: name,
      },
    });
    if (res.code === 200) {
      get().getList();
      toast.success('Delete file success');
    } else {
      toast.error(res.message || 'Request failed');
    }
  },
}));
