import { useShallow } from 'zustand/react/shallow';
import { useUserAppStore } from '../store';
import { useEffect, useState } from 'react';
import { useModal } from '@kevisual/components/modal/Confirm.tsx';

import DeleteOutlined from '@ant-design/icons/DeleteOutlined';
import EditOutlined from '@ant-design/icons/EditOutlined';
import LinkOutlined from '@ant-design/icons/LinkOutlined';
import PlusOutlined from '@ant-design/icons/PlusOutlined';
import UnorderedListOutlined from '@ant-design/icons/UnorderedListOutlined';
import CodeOutlined from '@ant-design/icons/CodeOutlined';
import ShareAltOutlined from '@ant-design/icons/ShareAltOutlined';
import { FormControlLabel, Switch, useTheme } from '@mui/material';
import { isObjectNull } from '@/utils/is-null';
import { useNewNavigate } from '@/modules';
import { DialogActions, Tooltip } from '@mui/material';
import { marked } from 'marked';
import clsx from 'clsx';
import { IconButton } from '@kevisual/components/button/index.tsx';
import { Select } from '@kevisual/components/select/index.tsx';
import { iText } from '@kevisual/resources/index.ts';
import { PermissionManager } from '@kevisual/resources/pages/file/modules/PermissionManager.tsx';
import { Button } from '@mui/material';
import { message } from '@/modules/message';
import { Dialog, DialogContent, DialogTitle, ButtonGroup } from '@mui/material';
import { useTranslation } from 'react-i18next';
import { TextField, InputAdornment } from '@mui/material';
import { useForm, Controller } from 'react-hook-form';
import { pick } from 'lodash-es';
import copy from 'copy-to-clipboard';

const FormModal = () => {
  const defaultValues = {
    id: '',
    title: '',
    domain: '',
    key: '',
    description: '',
    proxy: true,
    status: 'running',
  };
  const { control, handleSubmit, reset } = useForm({
    defaultValues,
  });
  const containerStore = useUserAppStore(
    useShallow((state) => {
      return {
        showEdit: state.showEdit,
        setShowEdit: state.setShowEdit,
        userApp: state.userApp,
        updateData: state.updateData,
      };
    }),
  );
  useEffect(() => {
    const open = containerStore.showEdit;
    if (open) {
      const isNull = isObjectNull(containerStore.userApp);
      console.log('isNull', containerStore.userApp);
      if (isNull) {
        reset(defaultValues);
      } else {
        reset(containerStore.userApp);
      }
    }
  }, [containerStore.showEdit, containerStore.userApp]);
  const onFinish = async (values: any) => {
    const pickValues = pick(values, ['id', 'title', 'domain', 'key', 'description', 'proxy', 'status']);
    containerStore.updateData(pickValues);
  };
  const onClose = () => {
    containerStore.setShowEdit(false);
    reset();
  };
  const isEdit = containerStore?.userApp?.id;
  const theme = useTheme();
  const defaultProps = theme.components?.MuiTextField?.defaultProps as any;
  return (
    <Dialog
      open={containerStore.showEdit}
      onClose={() => containerStore.setShowEdit(false)}
      sx={{
        '& .MuiDialog-paper': {
          width: '1000px',
        },
      }}>
      <DialogTitle>{isEdit ? 'Edit' : 'Add'}</DialogTitle>
      <DialogContent>
        <form className='flex flex-col gap-4 pt-2' onSubmit={handleSubmit(onFinish)}>
          <Controller name='title' control={control} render={({ field }) => <TextField {...defaultProps} {...field} label='title' />} />
          {/* <Controller
            name='domain'
            control={control}
            render={({ field }) => <TextField {...defaultProps} {...field} label='domain' variant='outlined' helperText='域名自定义绑定' />}
          /> */}
          <Controller name='key' control={control} render={({ field }) => <TextField {...defaultProps} {...field} label='key' fullWidth />} />
          <Controller
            name='description'
            control={control}
            render={({ field }) => <TextField {...defaultProps} {...field} label='description' multiline rows={4} fullWidth />}
          />
          <Controller name='proxy' control={control} render={({ field }) => <Switch {...defaultProps} {...field} checked={field.value} />} />
          <Controller
            name='status'
            control={control}
            render={({ field }) => (
              <Select
                {...defaultProps}
                {...field}
                sx={{
                  width: '100%',
                }}
                options={[
                  { label: 'Running', value: 'running' },
                  { label: 'Stop', value: 'stop' },
                ]}
              />
            )}
          />
          <div>
            <Button type='submit' variant='contained'>
              提交
            </Button>
            <Button className='ml-2' type='reset' onClick={onClose}>
              取消
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
};
const ShareModal = () => {
  const [permission, setPermission] = useState<any>(null);
  const [runtime, setRuntime] = useState<string[]>([]);
  const containerStore = useUserAppStore(
    useShallow((state) => {
      return {
        showEdit: state.showShareEdit,
        setShowEdit: state.setShowShareEdit,
        updateData: state.updateData,
        userApp: state.userApp,
      };
    }),
  );
  useEffect(() => {
    const open = containerStore.showEdit;
    if (open) {
      const permission = containerStore.userApp?.data?.permission || {};
      const runtime = containerStore.userApp?.data?.runtime || [];
      if (isObjectNull(permission)) {
        setPermission(null);
      } else {
        setPermission(permission);
      }
      setRuntime(runtime);
    }
  }, [containerStore.showEdit, containerStore.userApp]);
  const onFinish = async () => {
    const values = {
      id: containerStore.userApp.id,
      data: {
        permission,
        runtime,
      },
    };
    containerStore.updateData(values);
  };
  const onClose = () => {
    containerStore.setShowEdit(false);
  };
  const { t } = useTranslation();
  console.log('runtime', runtime);
  const theme = useTheme();
  const defaultProps = theme.components?.MuiTextField?.defaultProps as any;
  return (
    <Dialog
      open={containerStore.showEdit}
      onClose={() => {
        containerStore.setShowEdit(false);
      }}>
      <DialogTitle>{t('app.share')}</DialogTitle>
      <DialogContent>
        <div className='flex flex-col gap-2 w-[400px] '>
          <PermissionManager
            value={permission}
            onChange={(value) => {
              setPermission(value);
            }}
          />
          <FormControlLabel
            label={t('app.runtime')}
            labelPlacement='top'
            sx={{
              '& .MuiFormControlLabel-label': {
                width: '100%',
              },
            }}
            control={
              <Select
                multiple
                size='small'
                value={runtime}
                onChange={(e) => {
                  setRuntime(e.target.value as string[]);
                }}
                options={[
                  {
                    label: 'Node',
                    value: 'node',
                  },
                  {
                    label: 'Browser',
                    value: 'browser',
                  },
                ]}
              />
            }
          />
        </div>
      </DialogContent>
      <DialogActions>
        <Button type='submit' variant='contained' onClick={onFinish}>
          {t('Submit')}
        </Button>
        <Button className='ml-2' type='reset' onClick={onClose}>
          {t('Cancel')}
        </Button>
      </DialogActions>
    </Dialog>
  );
};
export const List = () => {
  const [modal, contextHolder] = useModal();
  const { t } = useTranslation();
  const userAppStore = useUserAppStore(
    useShallow((state) => {
      return {
        list: state.list,
        getList: state.getList,
        setShowEdit: state.setShowEdit,
        formData: state.formData,
        setFormData: state.setFormData,
        deleteData: state.deleteData,
        setShowShareEdit: state.setShowShareEdit,
        getUserApp: state.getUserApp,
      };
    }),
  );
  const navicate = useNewNavigate();
  useEffect(() => {
    userAppStore.getList();
  }, []);
  return (
    <div className='w-full h-full flex bg-slate-100'>
      <div className='p-2 h-full bg-white flex flex-col gap-2'>
        <Tooltip title='添加一个应用'>
          <IconButton
            sx={{
              padding: '8px',
            }}
            onClick={() => {
              userAppStore.setFormData({});
              userAppStore.setShowEdit(true);
            }}>
            <PlusOutlined />
          </IconButton>
        </Tooltip>
        <Tooltip title='转到Container管理界面'>
          <IconButton
            sx={{
              padding: '8px',
            }}
            onClick={() => {
              navicate('/container');
            }}>
            <CodeOutlined />
          </IconButton>
        </Tooltip>
        <Tooltip title='域名自定义绑定'>
          <IconButton
            sx={{
              padding: '8px',
            }}
            onClick={() => {
              message.info('联系管理员');
            }}>
            <LinkOutlined />
          </IconButton>
        </Tooltip>
      </div>
      <div className='grow'>
        <div className='w-full h-full p-4'>
          <div className='w-full h-full bg-white rounded-lg p-2 scrollbar '>
            <div className='flex flex-wrap gap-2'>
              {userAppStore.list.map((item) => {
                const isRunning = item.status === 'running';
                const hasDescription = !!item.description;
                const content = marked.parse(item.description);
                return (
                  <div className='card w-[300px] relative pb-10 ' key={item.id}>
                    <div className='card-title flex font-bold justify-between' onClick={() => {}}>
                      {item.title}
                      <div>
                        <Tooltip title={isRunning ? '网页可正常访问' : '网页被关闭'}>
                          <div className={`${isRunning ? 'bg-green-500' : 'bg-red-500'} w-4 h-4 rounded-full`}></div>
                        </Tooltip>
                      </div>
                    </div>
                    <div className='flex flex-col gap-2'>
                      <Tooltip title={'复制App ID到剪贴板'}>
                        <div
                          className='text-xs cursor-copy'
                          onClick={() => {
                            copy(item.id);
                            message.success('复制成功');
                          }}>
                          {item.id}
                        </div>
                      </Tooltip>
                      {item?.data?.domain && (
                        <div className='text-xs'>
                          {t('app.domain')}: {item?.data?.domain}
                        </div>
                      )}
                      <div className='text-xs'>
                        {t('app.version')}: {item.version}
                      </div>
                      <div className={clsx('text-sm border border-gray-200 p-2 max-h-[140px] scrollbar my-1', !hasDescription && 'hidden')}>
                        <div dangerouslySetInnerHTML={{ __html: content }}></div>
                      </div>
                    </div>
                    <div className='py-4'></div>
                    <div className='absolute bottom-0 left-4 py-4'>
                      <ButtonGroup
                        variant='contained'
                        color='primary'
                        sx={{ color: 'white', '& .MuiButton-root': { color: 'white', minWidth: '32px', width: '32px', height: '32px', padding: '6px' } }}>
                        <Tooltip title={'Edit'}>
                          <Button
                            onClick={() => {
                              userAppStore.getUserApp(item.id);
                              userAppStore.setFormData(item);
                              userAppStore.setShowEdit(true);
                            }}>
                            <EditOutlined />
                          </Button>
                        </Tooltip>
                        <Tooltip title={'App Version List'}>
                          <Button
                            onClick={() => {
                              navicate(`/app/${item.key}/version/list`);
                            }}>
                            <UnorderedListOutlined />
                          </Button>
                        </Tooltip>
                        <Tooltip title={iText.share.tips}>
                          <Button
                            onClick={() => {
                              userAppStore.getUserApp(item.id);
                              userAppStore.setFormData(item);
                              userAppStore.setShowShareEdit(true);
                            }}>
                            <ShareAltOutlined />
                          </Button>
                        </Tooltip>
                        <Tooltip title={'To App'}>
                          <Button
                            onClick={() => {
                              if (isRunning) {
                                let baseUri = location.origin;
                                if (item.domain) {
                                  if (item.domain.startsWith('http://') || item.domain.startsWith('https://')) {
                                    baseUri = item.domain;
                                  } else if (item.domain.startsWith('//')) {
                                    baseUri = new URL(item.domain).origin;
                                  } else {
                                    baseUri = new URL('https://' + item.domain).toString();
                                  }
                                  if (baseUri.endsWith('/')) {
                                    window.open(baseUri, '_blank');
                                  }
                                  console.log('baseUri', baseUri);
                                  message.success('success');
                                  return;
                                }
                                if (DEV_SERVER) {
                                  baseUri = 'http://localhost:3005';
                                }
                                const link = new URL(`/${item.user}/${item.key}/`, baseUri);
                                window.open(link.toString(), '_blank');
                              } else {
                                message.error('The app is not running');
                              }
                            }}>
                            <LinkOutlined />
                          </Button>
                        </Tooltip>
                        <Tooltip title={'Delete'}>
                          <Button
                            onClick={(e) => {
                              console.log('delete', item);
                              modal.confirm({
                                title: 'Delete',
                                content: 'Are you sure delete this data?',
                                onOk: () => {
                                  userAppStore.deleteData(item.id);
                                },
                              });
                              e.stopPropagation();
                            }}>
                            <DeleteOutlined />
                          </Button>
                        </Tooltip>
                      </ButtonGroup>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
      {contextHolder}
      <FormModal />
      <ShareModal />
    </div>
  );
};
