import {
  PageContainer,
  ProForm,
  ProFormText,
} from '@ant-design/pro-components';
import { history, useAccess } from '@umijs/max';
import {
  App,
  Button,
  Card,
  Col,
  Descriptions,
  type DescriptionsProps,
  Row,
  Space,
  Tag,
  Typography,
} from 'antd';
import React, { useEffect } from 'react';
import { clearAccessToken } from '@/access';
import PasswordLevel from '@/components/PasswordLevel';
import useUserInfo from '@/hooks/useUserInfo';
import { changeUserPass } from '@/services/api';
import { $t } from '@/utils/i18n';

const { Text } = Typography;

const Profile: React.FC = () => {
  const { userInfo, setUserInfo } = useUserInfo();
  const { isGlobalCompany } = useAccess();
  const userCompany = userInfo?.company;
  const { message: antdMessage, modal } = App.useApp();

  const roleList = () => {
    return (
      <Space>
        {userInfo?.roleList?.map((item) => (
          <Tag color="blue" key={item?.id}>
            {item?.mark || '-'}
          </Tag>
        )) || '-'}
      </Space>
    );
  };
  const items: DescriptionsProps['items'] = [
    {
      key: '1',
      span: 'filled',
      label: $t('form.user.displayName'),
      children: userInfo?.nickName || '-',
    },
    {
      key: '2',
      span: 'filled',
      label: $t('table.username'),
      children: userInfo?.username || '-',
    },
    {
      key: '3',
      span: 'filled',
      label: $t('form.user.email'),
      children: userInfo?.email || '-',
    },
    {
      key: '4',
      span: 'filled',
      label: $t('table.role'),
      children: roleList(),
    },
    {
      key: '5',
      span: 'filled',
      label: $t('table.company'),
      children: userCompany?.name || '-',
    },
  ];

  useEffect(() => {
    if (!isGlobalCompany) {
      items.push({
        key: '6',
        span: 'filled',
        label: $t('table.validityEndTime'),
        children: userCompany?.validityEndTime ? (
          <Space>
            {userCompany.validityEndTime}
            {userCompany?.validityStatus === 2 && (
              <Text type="danger" style={{ fontSize: '12px' }}>
                {$t('pages.company.expired')}
              </Text>
            )}
          </Space>
        ) : (
          $t('pages.company.permanent')
        ),
      });
    }
  }, [userCompany, isGlobalCompany]);

  const changePasswordSuccessHadle = async () => {
    let countdown = 5;
    let timer: NodeJS.Timeout | null = null;
    const modalData = {
      title: $t('pages.changePasswordSuccess'),
      okText: `${$t('pages.goLogin')}(${countdown}S)`,
      centered: true,
      onOk: () => {
        history.replace('/login');
        instance.destroy();
      },
    };
    const instance = modal.info({
      ...modalData,
    });
    timer = setInterval(() => {
      countdown--;
      instance.update({
        okText: `${$t('pages.goLogin')}(${countdown}S)`,
      });
      if (countdown <= 0) {
        if (timer) {
          clearInterval(timer);
          timer = null;
          history.replace('/login');
          instance.destroy();
        }
      }
    }, 1000);

    clearAccessToken();
    setUserInfo(undefined);
    localStorage.removeItem('changePassTimestamp');
  };

  return (
    <PageContainer>
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card
            title={`👤 ${$t('pages.profile.basicInfo')}`}
            hoverable
            variant="borderless"
            style={{ height: '100%' }}
          >
            <Descriptions layout="vertical" items={items} />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card
            title={`🔐 ${$t('pages.profile.changePassword')}`}
            hoverable
            variant="borderless"
            style={{ height: '100%' }}
          >
            <ProForm
              onFinish={async (values: API.ChangeUserPassParams) => {
                const { code, message } = await changeUserPass(values);
                if (code === 200) {
                  await changePasswordSuccessHadle();
                } else {
                  antdMessage.error(message);
                }
              }}
              submitter={{
                render: () => {
                  return [
                    <Button htmlType="submit" type="primary" key="edit" block>
                      {$t('pages.confirmModify')}
                    </Button>,
                  ];
                },
              }}
            >
              <ProFormText.Password
                name="password"
                label={$t('pages.oldPassword')}
                placeholder={$t('pages.oldPassword.tips')}
                rules={[{ required: true, message: $t('form.required') }]}
                getValueFromEvent={(e) => e.target.value.trim()}
              />
              <ProFormText.Password
                name="newPassword"
                label={$t('pages.newPassword')}
                rules={[
                  { required: true, message: $t('form.required') },
                  { min: 6, message: $t('form.password.placeholder') },
                ]}
                extra={<PasswordLevel passwordStr="newPassword" />}
                getValueFromEvent={(e) => e.target.value.trim()}
              />
              <ProFormText.Password
                name="newPassword2"
                label={$t('pages.confirmPassword')}
                dependencies={['newPassword']}
                getValueFromEvent={(e) => e.target.value.trim()}
                rules={[
                  { required: true, message: $t('form.required') },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('newPassword') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(
                        new Error($t('form.password.passwordNotMatch')),
                      );
                    },
                  }),
                ]}
              />
            </ProForm>
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default Profile;
