import { Fragment, useEffect, useState } from 'react';
import { useUserStore } from '../store';
import { useShallow } from 'zustand/react/shallow';
import { isObjectNull } from '@/utils/is-null';
import { CardBlank } from '@kevisual/components/card/CardBlank.tsx';
import { Dialog, ButtonGroup, Button, DialogContent, DialogTitle, Tooltip } from '@mui/material';
import { IconButton } from '@kevisual/components/button/index.tsx';
import { useTranslation } from 'react-i18next';
import { useModal } from '@kevisual/components/modal/Confirm.tsx';
import { TextField } from '@mui/material';
import { useForm, Controller } from 'react-hook-form';
import { pick } from 'lodash-es';
import { useAdminStore } from '../admin/store/admin-store';
import { SquareAsterisk, Edit as EditOutlined, Trash as DeleteOutlined, Plus as PlusOutlined, UserPen } from 'lucide-react';
import { toast } from 'react-toastify';
const FormModal = () => {
  const { control, handleSubmit, reset } = useForm();
  const userStore = useUserStore(
    useShallow((state) => {
      return {
        showEdit: state.showEdit,
        setShowEdit: state.setShowEdit,
        formData: state.formData,
        updateData: state.updateData,
        setFormData: state.setFormData,
      };
    }),
  );
  const adminStore = useAdminStore(useShallow((state) => state));
  useEffect(() => {
    const open = userStore.showEdit;
    if (open) {
      const isNull = isObjectNull(userStore.formData);
      if (isNull) {
        reset({});
      } else reset(userStore.formData);
    }
    return () => {
      reset({});
    };
  }, [userStore.showEdit]);

  const onFinish = (values: any) => {
    const pickValues = pick(values, ['id', 'username', 'description']);
    if (pickValues.id) {
      userStore.updateData(pickValues);
    } else {
      const newPickValues = pick(values, ['username', 'description', 'password']);
      adminStore.createNewUser(newPickValues);
    }
  };

  const onClose = () => {
    userStore.setShowEdit(false);
    reset({});
    userStore.setFormData({});
  };

  const isEdit = userStore.formData.id;
  const { t } = useTranslation();

  return (
    <Dialog
      open={userStore.showEdit}
      onClose={() => userStore.setShowEdit(false)}
      sx={{
        '& .MuiDialog-paper': {
          width: '800px',
        },
      }}>
      <DialogTitle>{isEdit ? t('Edit') : t('Add')}</DialogTitle>
      <DialogContent>
        <form className='flex flex-col gap-6 pt-4' onSubmit={handleSubmit(onFinish)}>
          <Controller name='username' control={control} defaultValue='' render={({ field }) => <TextField {...field} label='username' fullWidth />} />
          <Controller
            name='description'
            control={control}
            defaultValue=''
            render={({ field }) => <TextField {...field} label='description' multiline rows={4} fullWidth />}
          />
          {!isEdit && (
            <Controller
              name='password'
              control={control}
              defaultValue=''
              render={({ field }) => <TextField {...field} label='password' type='password' fullWidth />}
            />
          )}
          <div>
            <Button type='submit' variant='contained'>
              {t('Submit')}
            </Button>
            <Button className='ml-2' type='button' onClick={onClose}>
              {t('Cancel')}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
};
export const NameModal = () => {
  const { control, handleSubmit, reset } = useForm();
  const userStore = useUserStore(useShallow((state) => state));
  const adminStore = useAdminStore(useShallow((state) => state));
  const onFinish = async (values: any) => {
    const check = await adminStore.checkUserExist(values.username);
    if (check === false) {
      const uid = userStore.formData.id;
      if (!uid) {
        toast.error('获取用户id失败');
        return;
      }
      const res = await adminStore.changeName(uid, values.username);
      if (res.code === 200) {
        userStore.setShowNameEdit(false);
        userStore.getList();
      }
    } else {
      toast.error('用户名已存在，请重新输入');
    }
  };
  const onClose = () => {
    userStore.setShowNameEdit(false);
    reset({});
    userStore.setFormData({});
  };
  const { t } = useTranslation();
  return (
    <Dialog open={userStore.showNameEdit} onClose={() => userStore.setShowNameEdit(false)}>
      <DialogTitle>修改用户名</DialogTitle>
      <DialogContent>
        <form className='flex flex-col gap-6 pt-4' onSubmit={handleSubmit(onFinish)}>
          <Controller name='username' control={control} defaultValue='' render={({ field }) => <TextField {...field} label='username' fullWidth />} />
          <div>
            <Button type='submit' variant='contained'>
              {t('Submit')}
            </Button>
            <Button className='ml-2' type='button' onClick={onClose}>
              {t('Cancel')}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
};
export const List = () => {
  const [modal, contextHolder] = useModal();
  const userStore = useUserStore(
    useShallow((state) => {
      return {
        setFormData: state.setFormData,
        setShowEdit: state.setShowEdit,
        setShowNameEdit: state.setShowNameEdit,
        list: state.list,
        deleteData: state.deleteData,
        getList: state.getList,
        loading: state.loading,
        formData: state.formData,
      };
    }),
  );
  const adminStore = useAdminStore(useShallow((state) => state));
  useEffect(() => {
    userStore.getList();
  }, []);

  const onAdd = () => {
    userStore.setFormData({});
    userStore.setShowEdit(true);
  };
  return (
    <div className='w-full h-full flex'>
      <div className='p-2'>
        <IconButton onClick={onAdd} variant='contained'>
          <PlusOutlined className='w-4 h-4' />
        </IconButton>
      </div>
      <div className='flex grow overflow-hidden h-full'>
        <div className='grow overflow-auto scrollbar bg-gray-100'>
          <div className='flex  flex-wrap   gap-x-10 gap-y-4 rounded pt-10  justify-center'>
            {userStore.list.length > 0 &&
              userStore.list.map((item) => {
                return (
                  <Fragment key={item.id}>
                    <div
                      className='flex text-sm gap flex-col w-[400px] max-h-[400px] bg-white p-4 rounded-lg'
                      key={item.id}
                      onClick={() => {
                        // userStore.setFormData(item);
                      }}>
                      <div className='px-4 cursor-pointer'>
                        <div
                          className='font-bold'
                          onClick={(e) => {
                            e.stopPropagation();
                            // message.success('copy code success');
                          }}>
                          {item.username || '-'}
                        </div>
                        <div className='font-light text-xs mt-2'>{item.description ? item.description : '-'}</div>
                      </div>
                      <div className='flex mt-2 '>
                        <ButtonGroup
                          variant='contained'
                          color='primary'
                          sx={{ color: 'white', '& .MuiButton-root': { color: 'white', minWidth: '32px', width: '32px', height: '32px', padding: '6px' } }}>
                          <Tooltip title='编辑'>
                            <Button
                              onClick={(e) => {
                                userStore.setFormData(item);
                                userStore.setShowEdit(true);
                                e.stopPropagation();
                              }}>
                              <EditOutlined />
                            </Button>
                          </Tooltip>
                          <Tooltip title='修改用户名'>
                            <Button
                              onClick={(e) => {
                                userStore.setFormData(item);
                                userStore.setShowNameEdit(true);
                                e.stopPropagation();
                              }}>
                              <UserPen />
                            </Button>
                          </Tooltip>
                          <Tooltip title='重置密码'>
                            <Button
                              onClick={(e) => {
                                modal.confirm({
                                  title: '重置密码',
                                  content: 'Are you sure reset password?',
                                  onOk: () => {
                                    adminStore.resetPassword(item.id);
                                  },
                                });
                                e.stopPropagation();
                              }}>
                              <SquareAsterisk />
                            </Button>
                          </Tooltip>
                          <Tooltip title='禁用'>
                            <Button
                              onClick={(e) => {
                                modal.confirm({
                                  title: 'Delete',
                                  content: 'Are you sure delete this data?',
                                  onOk: async () => {
                                    await adminStore.deleteUser(item.id);
                                    userStore.getList();
                                  },
                                });
                                e.stopPropagation();
                              }}>
                              <DeleteOutlined />
                            </Button>
                          </Tooltip>
                        </ButtonGroup>
                      </div>
                    </div>
                  </Fragment>
                );
              })}
            <CardBlank className='w-[400px]' />
            {userStore.list.length == 0 && (
              <div className='text-center' key={'no-data'}>
                No Data
              </div>
            )}
          </div>
        </div>
      </div>
      <FormModal />
      <NameModal />
      {contextHolder}
    </div>
  );
};
