import { Button, Dialog, DialogActions, DialogContent, DialogTitle } from '@mui/material';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { create } from 'zustand';
import { useAppVersionStore, useUserAppStore } from '../store';
import { useShallow } from 'zustand/shallow';

type AppDeleteModalStore = {
  open: boolean;
  setOpen: (open: boolean) => void;
  app: any;
  setApp: (app: any) => void;
  type: 'user-app' | 'app-version';
  setType: (type: 'user-app' | 'app-version') => void;
  onClickDelete: (type: 'user-app' | 'app-version', data: any) => void;
};
export const useAppDeleteModalStore = create<AppDeleteModalStore>((set) => ({
  open: false,
  setOpen: (open) => set({ open }),
  app: null,
  setApp: (app) => set({ app }),
  type: 'user-app',
  setType: (type) => set({ type }),
  onClickDelete: (type, data) => {
    set({ open: true, type, app: data });
  },
}));

export const AppDeleteModal = () => {
  const { t } = useTranslation();
  const { open, setOpen, app, type, setType } = useAppDeleteModalStore();
  const userAppStore = useUserAppStore(
    useShallow((state) => {
      return {
        deleteData: state.deleteData,
      };
    }),
  );
  const appVersionStore = useAppVersionStore(
    useShallow((state) => {
      return {
        deleteData: state.deleteData,
      };
    }),
  );
  const onClose = () => {
    setOpen(false);
  };
  const onDelete = (deleteFile = false) => {
    if (type === 'user-app') {
      userAppStore.deleteData(app.id, deleteFile);
    } else {
      appVersionStore.deleteData(app.id, deleteFile);
    }
    setOpen(false);
  };

  return (
    <Dialog open={open} onClose={onClose}>
      <DialogTitle>{t('Tips')}</DialogTitle>
      <DialogContent>
        <div className='w-[400px]'>
          <p className='text-sm text-gray-500'>{t('Delete App Introduce')}</p>
        </div>
      </DialogContent>
      <DialogActions>
        <Button variant='contained' onClick={() => onDelete()}>{t('Delete')}</Button>
        <Button onClick={onClose}>{t('Cancel')}</Button>
        <Button
          color='error'
          onClick={() => {
            onDelete(true);
          }}>
          {t('Delete and remove file')}
        </Button>
      </DialogActions>
    </Dialog>
  );
};
