import { useShallow } from 'zustand/react/shallow';
import { useOrgStore } from '../store';
import { useParams } from 'react-router';
import { useEffect } from 'react';
import { message } from '@/modules/message';
import DeleteOutlined from '@ant-design/icons/DeleteOutlined';
import LeftOutlined from '@ant-design/icons/LeftOutlined';
import PlusOutlined from '@ant-design/icons/PlusOutlined';
import { Tooltip, Button, ButtonGroup, Dialog, DialogTitle, DialogContent } from '@mui/material';
import { IconButton } from '@kevisual/components/button/index.tsx';
import { useNewNavigate } from '@/modules';
import { isObjectNull } from '@/utils/is-null';
import copy from 'copy-to-clipboard';
import { useTranslation } from 'react-i18next';
import { useModal } from '@kevisual/components/modal/Confirm.tsx';
import { TextField } from '@mui/material';
import { Select } from '@kevisual/components/select/index.tsx';
import { useForm, Controller } from 'react-hook-form';

const FormModal = () => {
  const { control, handleSubmit, reset } = useForm();
  const userStore = useOrgStore(
    useShallow((state) => {
      return {
        showEdit: state.showUserEdit,
        setShowEdit: state.setShowUserEdit,
        formData: state.userFormData,
        setFormData: state.setUserFormData,
        addUser: state.addUser,
      };
    }),
  );

  useEffect(() => {
    const open = userStore.showEdit;
    if (open) {
      const isNull = isObjectNull(userStore.formData);
      if (isNull) {
        reset({});
      } else reset(userStore.formData);
    }
    return () => {
      reset({});
    };
  }, [userStore.showEdit, userStore.formData, reset]);

  const onFinish = async (values: any) => {
    console.log(values);
    const username = values.username;
    const role = values.role;
    if (!username) {
      message.error('username is required');
      return;
    }
    const res = await userStore.addUser({ username: username, role });
    if (res?.code === 200) {
      userStore.setShowEdit(false);
    }
  };

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

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

  return (
    <Dialog open={userStore.showEdit} onClose={() => userStore.setShowEdit(false)}>
      <DialogTitle>{isEdit ? 'Edit' : 'Add'}</DialogTitle>
      <DialogContent sx={{ padding: '20px', minWidth: '600px' }}>
        <form className='flex flex-col gap-6' onSubmit={handleSubmit(onFinish)}>
          <Controller
            name='username'
            control={control}
            defaultValue=''
            render={({ field }) => <TextField {...field} label='username' disabled={isEdit} fullWidth margin='normal' />}
          />
          <Controller
            name='role'
            control={control}
            defaultValue=''
            render={({ field }) => (
              <Select
                {...field}
                options={[
                  { label: 'admin', value: 'admin' },
                  { label: 'user', value: 'user' },
                ]}
                fullWidth
              />
            )}
          />
          <div className='flex gap-2'>
            <Button variant='contained' type='submit'>
              {t('Submit')}
            </Button>
            <Button className='ml-2' onClick={onClose}>
              {t('Cancel')}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
};

export const UserList = () => {
  const param = useParams();
  const navicate = useNewNavigate();
  const [modal, contextHolder] = useModal();
  const { t } = useTranslation();
  const orgStore = useOrgStore(
    useShallow((state) => {
      return {
        users: state.users,
        org: state.org,
        setOrgId: state.setOrgId,
        getOrg: state.getOrg,
        setShowUserEdit: state.setShowUserEdit,
        setUserFormData: state.setUserFormData,
        setShowEdit: state.setShowEdit,
        removeUser: state.removeUser,
        addUser: state.addUser,
      };
    }),
  );
  useEffect(() => {
    if (param.id) {
      orgStore.setOrgId(param.id);
      orgStore.getOrg();
    }
    return () => {
      orgStore.setUserFormData({});
    };
  }, []);
  return (
    <div className='w-full h-full bg-gray-100 flex'>
      <div className='p-2 bg-white mr-2'>
        <IconButton
          onClick={() => {
            orgStore.setUserFormData({});
            orgStore.setShowUserEdit(true);
          }}>
          <PlusOutlined />
        </IconButton>
      </div>
      <div className='p-4 pt-12  grow relative'>
        <div className='absolute top-2'>
          <Tooltip title={t('Back')}>
            <IconButton
              onClick={() => {
                navicate(-1);
              }}>
              <LeftOutlined />
            </IconButton>
          </Tooltip>
        </div>
        <div className='p-4  bg-white  rounded-lg border  shadow-md h-full'>
          <div className='flex gap-4'>
            {orgStore.users.map((item) => {
              const isOwner = item.role === 'owner';
              return (
                <div key={item.id} className='card w-[300px]  justify-between p-2 '>
                  <div
                    className='card-title capitalize truncate cursor-pointer'
                    onClick={() => {
                      copy(item.username);
                    }}>
                    {t('Username')}: {item.username}
                  </div>
                  <div className='flex gap-2 capitalize'>{item.role || '-'}</div>
                  <div className='mt-2'>
                    <ButtonGroup
                      variant='contained'
                      color='primary'
                      sx={{ color: 'white', '& .MuiButton-root': { color: 'white', minWidth: '32px', width: '32px', height: '32px', padding: '6px' } }}>
                      {/* <Tooltip title='edit'>
                        <Button
                          disabled={isOwner}
                          onClick={() => {
                            orgStore.setUserFormData(item);
                            orgStore.setShowUserEdit(true);
                          }}>
                          <EditOutlined />
                        </Button>
                      </Tooltip> */}
                      <Tooltip title='delete'>
                        <Button
                          disabled={isOwner}
                          onClick={() => {
                            modal.confirm({
                              title: 'Delete',
                              content: 'Are you sure?',
                              onOk: () => {
                                orgStore.removeUser(item.id);
                              },
                            });
                          }}>
                          <DeleteOutlined />
                        </Button>
                      </Tooltip>
                    </ButtonGroup>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <FormModal />
      {contextHolder}
    </div>
  );
};
