import { Button, Dialog, DialogActions, DialogContent, DialogTitle } from '@mui/material';
import { useHomeStore } from '../store';
import { Controller, useForm } from 'react-hook-form';
import { TextField } from '@mui/material';
import { useEffect } from 'react';
import { customAlphabet } from 'nanoid';
import { useTranslation } from 'react-i18next';
import { toast } from 'react-toastify';
import { uploadFile } from './upload-file';
import { useAppVersionStore } from '@/pages/app/store';
import { useShallow } from 'zustand/shallow';

export const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz', 10);
export const UploadModal = () => {
  const { appKey, version, filename, openUploadModal, text, setOpenUploadModal, setAppKey, setVersion, setFilename, setOpenSuccessModal } = useHomeStore();
  const { control, handleSubmit, reset } = useForm();
  const { publishVersion } = useAppVersionStore(useShallow((state) => ({ publishVersion: state.publishVersion })));
  useEffect(() => {
    if (openUploadModal) {
      const randomAppKey = nanoid(4) + nanoid(4);
      reset({ appKey: appKey || randomAppKey, version: version || '1.0.0', filename: filename || 'index.html' });
    }
  }, [openUploadModal]);
  const onSubmit = async (data: any) => {
    console.log(data);
    if (!text) {
      toast.error('代码不能为空');
      return;
    }
    if (!data.appKey) {
      toast.error('应用key不能为空');
      return;
    }
    if (!data.version) {
      toast.error('版本不能为空');
      return;
    }
    if (!data.filename) {
      toast.error('文件名不能为空');
      return;
    }
    setAppKey(data.appKey);
    setVersion(data.version);
    setFilename(data.filename);
    const res = await uploadFile({
      appKey: data.appKey,
      version: data.version,
      filename: data.filename,
      text,
    });
    if (res?.code === 200) {
      toast.success('部署成功');
      const toastId = toast.loading('发布中...');
      await new Promise((resolve) => setTimeout(resolve, 2000));
      const res = await publishVersion({ appKey: data.appKey, version: data.version }, { showToast: false });
      toast.dismiss(toastId);
      if (res?.code === 200) {
        toast.success('发布成功');
        setOpenSuccessModal(true);
      } else {
        toast.error(res?.message || '发布失败');
      }
    } else {
      toast.error(res?.message || '部署失败');
    }
  };
  const { t } = useTranslation();
  return (
    <Dialog open={openUploadModal} onClose={() => setOpenUploadModal(false)}>
      <DialogTitle>部署页面</DialogTitle>
      <DialogContent>
        <form className='flex flex-col gap-3 pt-1 w-[500px]' onSubmit={handleSubmit(onSubmit)}>
          <div className='flex flex-col gap-1'>
            <label className='text-sm'>应用key</label>
            <Controller control={control} name='appKey' render={({ field }) => <TextField {...field} />} />
          </div>
          <div className='flex flex-col gap-1'>
            <label className='text-sm'>版本</label>
            <Controller control={control} name='version' render={({ field }) => <TextField {...field} />} />
          </div>
          <div className='flex flex-col gap-1'>
            <label className='text-sm'>文件名</label>
            <Controller control={control} name='filename' render={({ field }) => <TextField {...field} />} />
          </div>
          <DialogActions>
            <Button
              onClick={() => {
                setOpenUploadModal(false);
              }}>
              {t('Cancel')}
            </Button>
            <Button type='submit'>{t('Submit')}</Button>
          </DialogActions>
        </form>
      </DialogContent>
    </Dialog>
  );
};
