import { Fragment, useEffect, useState } from 'react';
import { useOrgStore } from '../store';
import { useShallow } from 'zustand/react/shallow';
import { useNewNavigate } from '@/modules';
import { useTranslation } from 'react-i18next';
import { Tooltip, Button, ButtonGroup, Dialog, DialogTitle, DialogContent } from '@mui/material';
import { IconButton } from '@kevisual/components/button/index.tsx';
import EditOutlined from '@ant-design/icons/EditOutlined';
import SaveOutlined from '@ant-design/icons/SaveOutlined';
import DeleteOutlined from '@ant-design/icons/DeleteOutlined';
import LeftOutlined from '@ant-design/icons/LeftOutlined';
import PlusOutlined from '@ant-design/icons/PlusOutlined';
import SwapOutlined from '@ant-design/icons/SwapOutlined';
import UnorderedListOutlined from '@ant-design/icons/UnorderedListOutlined';
import clsx from 'clsx';
import { isObjectNull } from '@/utils/is-null';
import { CardBlank } from '@/components/card/CardBlank';
import { useLayoutStore } from '@/modules/layout/store';
import { useModal } from '@kevisual/components/modal/Confirm.tsx';
import { useForm, Controller } from 'react-hook-form';
import { TextField } from '@mui/material';
import { pick } from 'lodash-es';

const FormModal = () => {
  const { t } = useTranslation();
  const { control, handleSubmit, reset } = useForm();
  const userStore = useOrgStore(
    useShallow((state) => {
      return {
        showEdit: state.showEdit,
        setShowEdit: state.setShowEdit,
        formData: state.formData,
        updateData: state.updateData,
        setFormData: state.setFormData,
      };
    }),
  );

  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) => {
    const pickValues = pick(values, ['id', 'username', 'description']);
    userStore.updateData(pickValues);
  };

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

  const isEdit = userStore.formData.id;

  return (
    <Dialog open={userStore.showEdit} onClose={() => userStore.setShowEdit(false)}>
      <DialogTitle>{isEdit ? 'Edit' : 'Add'}</DialogTitle>
      <DialogContent sx={{ padding: '20px', minWidth: '600px' }}>
        <form onSubmit={handleSubmit(onFinish)}>
          <Controller
            name='username'
            control={control}
            defaultValue=''
            render={({ field }) => <TextField {...field} label='username' disabled={isEdit} fullWidth margin='normal' />}
          />
          <Controller
            name='description'
            control={control}
            defaultValue=''
            render={({ field }) => <TextField {...field} label='description' multiline rows={4} fullWidth margin='normal' />}
          />
          <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 List = () => {
  const navicate = useNewNavigate();
  const userStore = useOrgStore(
    useShallow((state) => {
      return {
        setFormData: state.setFormData,
        setShowEdit: state.setShowEdit,
        list: state.list,
        deleteData: state.deleteData,
        getList: state.getList,
        loading: state.loading,
        updateData: state.updateData,
        formData: state.formData,
      };
    }),
  );
  const layoutStore = useLayoutStore(
    useShallow((state) => {
      return {
        switchOrg: state.switchOrg,
      };
    }),
  );
  const [modal, contextHolder] = useModal();
  useEffect(() => {
    userStore.getList();
  }, []);

  const onAdd = () => {
    userStore.setFormData({});
    userStore.setShowEdit(true);
  };
  const { t } = useTranslation();
  return (
    <div className='w-full h-full flex'>
      <div className='p-2'>
        <Tooltip title={t('Add Org')}>
          <IconButton onClick={onAdd} variant='contained'>
            <PlusOutlined />
          </IconButton>
        </Tooltip>
      </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={t('Edit')}>
                            <Button
                              onClick={(e) => {
                                userStore.setFormData(item);
                                userStore.setShowEdit(true);
                                e.stopPropagation();
                              }}>
                              <EditOutlined />
                            </Button>
                          </Tooltip>
                          <Tooltip title={t('User List')}>
                            <Button
                              onClick={(e) => {
                                navicate(`/org/edit/user/${item.id}`);
                                e.stopPropagation();
                              }}>
                              <UnorderedListOutlined />
                            </Button>
                          </Tooltip>
                          <Button
                            onClick={(e) => {
                              modal.confirm({
                                title: 'Delete',
                                content: 'Are you sure delete this data?',
                                onOk: () => {
                                  userStore.deleteData(item.id);
                                },
                              });
                              e.stopPropagation();
                            }}>
                            <DeleteOutlined />
                          </Button>
                          <Tooltip title={t('Switch to Org')}>
                            <Button
                              onClick={() => {
                                layoutStore.switchOrg(item.username);
                              }}>
                              <SwapOutlined />
                            </Button>
                          </Tooltip>
                        </ButtonGroup>
                      </div>
                    </div>
                  </Fragment>
                );
              })}
            {userStore.list.length == 0 && <div className='text-center'>No Data</div>}
            <CardBlank className='w-[400px]' />
          </div>
        </div>
      </div>
      <FormModal />
      {contextHolder}
    </div>
  );
};
