import {
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  LockOutlined,
  MailOutlined,
  SafetyOutlined,
} from '@ant-design/icons';
import { useModel, useIntl } from '@umijs/max';
import { App, Button, Form, Input, Modal, Steps } from 'antd';
import React, { useEffect, useState } from 'react';
import {
  changePassword,
  sendCurrentEmailCode,
  sendNewEmailCode,
  verifyCurrentEmail,
  bindNewEmail,
} from '@/services/auth/api';
import { getApiLanguage } from '@/services/auth/errorCodes';
import useStyles from './index.style';

const SecurityView: React.FC = () => {
  const { styles, cx } = useStyles();
  const intl = useIntl();
  const { message } = App.useApp();
  const { initialState, setInitialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;

  // Password modal state
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [passwordLoading, setPasswordLoading] = useState(false);
  const [passwordForm] = Form.useForm();

  // Email modal state
  const [emailModalVisible, setEmailModalVisible] = useState(false);
  const [emailStep, setEmailStep] = useState(0);
  const [emailLoading, setEmailLoading] = useState(false);
  const [currentEmailVerified, setCurrentEmailVerified] = useState(false);
  const [currentCount, setCurrentCount] = useState(0);
  const [newCount, setNewCount] = useState(0);
  const [currentEmailForm] = Form.useForm();
  const [newEmailForm] = Form.useForm();

  // Countdown - current email
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (currentCount > 0) {
      timer = setTimeout(() => setCurrentCount(currentCount - 1), 1000);
    }
    return () => clearTimeout(timer);
  }, [currentCount]);

  // Countdown - new email
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (newCount > 0) {
      timer = setTimeout(() => setNewCount(newCount - 1), 1000);
    }
    return () => clearTimeout(timer);
  }, [newCount]);

  // Reset email state
  const resetEmailState = () => {
    setEmailStep(0);
    setCurrentEmailVerified(false);
    setCurrentCount(0);
    setNewCount(0);
    currentEmailForm.resetFields();
    newEmailForm.resetFields();
  };

  // Change password
  const handleChangePassword = async (values: {
    oldPassword: string;
    newPassword: string;
    logoutOtherDevices: boolean;
  }) => {
    setPasswordLoading(true);
    try {
      const response = await changePassword({
        oldPassword: values.oldPassword,
        newPassword: values.newPassword,
        logoutOtherDevices: values.logoutOtherDevices,
      });

      if (response.success) {
        message.success(
          intl.formatMessage({
            id: 'pages.account.settings.password.success',
            defaultMessage: '密码修改成功',
          }),
        );
        setPasswordModalVisible(false);
        passwordForm.resetFields();
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.password.failed',
              defaultMessage: '密码修改失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.password.failed',
            defaultMessage: '密码修改失败',
          }),
      );
    } finally {
      setPasswordLoading(false);
    }
  };

  // Send current email code
  const handleSendCurrentCode = async () => {
    if (!currentUser?.email) return;

    try {
      const response = await sendCurrentEmailCode({
        email: currentUser.email,
        language: getApiLanguage(intl.locale) as 'zh' | 'en' | undefined,
      });

      if (response.success) {
        setCurrentCount(60);
        message.success(
          intl.formatMessage({
            id: 'pages.account.settings.email.codeSent',
            defaultMessage: '验证码已发送',
          }),
        );
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.email.sendFailed',
              defaultMessage: '发送验证码失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.email.sendFailed',
            defaultMessage: '发送验证码失败',
          }),
      );
    }
  };

  // Verify current email
  const handleVerifyCurrentEmail = async (values: { currentCode: string }) => {
    setEmailLoading(true);
    try {
      const response = await verifyCurrentEmail({
        action: 'verify-current',
        currentCode: values.currentCode,
      });

      if (response.success) {
        setCurrentEmailVerified(true);
        setEmailStep(1);
        message.success(
          intl.formatMessage({
            id: 'pages.account.settings.email.currentVerified',
            defaultMessage: '当前邮箱验证成功',
          }),
        );
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.email.verifyFailed',
              defaultMessage: '验证失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.email.verifyFailed',
            defaultMessage: '验证失败',
          }),
      );
    } finally {
      setEmailLoading(false);
    }
  };

  // Send new email code
  const handleSendNewCode = async () => {
    try {
      const newEmail = newEmailForm.getFieldValue('newEmail');
      if (!newEmail) {
        message.error(
          intl.formatMessage({
            id: 'pages.account.settings.email.inputNewEmail',
            defaultMessage: '请先输入新邮箱',
          }),
        );
        return;
      }

      const response = await sendNewEmailCode({
        email: newEmail,
        language: getApiLanguage(intl.locale) as 'zh' | 'en' | undefined,
      });

      if (response.success) {
        setNewCount(60);
        message.success(
          intl.formatMessage({
            id: 'pages.account.settings.email.codeSent',
            defaultMessage: '验证码已发送',
          }),
        );
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.email.sendFailed',
              defaultMessage: '发送验证码失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.email.sendFailed',
            defaultMessage: '发送验证码失败',
          }),
      );
    }
  };

  // Bind new email
  const handleBindNewEmail = async (values: { newEmail: string; newCode: string }) => {
    setEmailLoading(true);
    try {
      const response = await bindNewEmail({
        action: 'bind-new',
        newEmail: values.newEmail,
        newCode: values.newCode,
      });

      if (response.success && response.data) {
        message.success(
          intl.formatMessage({
            id: 'pages.account.settings.email.bindSuccess',
            defaultMessage: '邮箱绑定成功',
          }),
        );
        setEmailModalVisible(false);
        resetEmailState();

        // Update global user state
        if (initialState) {
          setInitialState({
            ...initialState,
            currentUser: {
              ...initialState.currentUser!,
              email: values.newEmail,
            },
          });
        }
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.email.bindFailed',
              defaultMessage: '邮箱绑定失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.email.bindFailed',
            defaultMessage: '邮箱绑定失败',
          }),
      );
    } finally {
      setEmailLoading(false);
    }
  };

  // Open email modal
  const openEmailModal = () => {
    resetEmailState();
    setEmailModalVisible(true);
  };

  return (
    <>
      <div className={styles.securityList}>
        {/* Password Item */}
        <div className={styles.securityItem}>
          <div className={cx(styles.securityIcon, styles.securityIconPassword)}>
            <LockOutlined />
          </div>
          <div className={styles.securityContent}>
            <div className={styles.securityTitle}>
              {intl.formatMessage({
                id: 'pages.account.settings.security.password',
                defaultMessage: '账户密码',
              })}
            </div>
            <div className={styles.securityDesc}>
              {intl.formatMessage({
                id: 'pages.account.settings.security.password.desc',
                defaultMessage: '定期更换密码可以提高账户安全性',
              })}
            </div>
          </div>
          <div className={styles.securityAction}>
            <Button
              type="primary"
              ghost
              className={styles.securityButton}
              onClick={() => setPasswordModalVisible(true)}
            >
              {intl.formatMessage({
                id: 'pages.account.settings.security.modify',
                defaultMessage: '修改',
              })}
            </Button>
          </div>
        </div>

        {/* Email Item */}
        <div className={styles.securityItem}>
          <div className={cx(styles.securityIcon, styles.securityIconEmail)}>
            <MailOutlined />
          </div>
          <div className={styles.securityContent}>
            <div className={styles.securityTitle}>
              {intl.formatMessage({
                id: 'pages.account.settings.security.email',
                defaultMessage: '绑定邮箱',
              })}
              {currentUser?.email ? (
                <span className={cx(styles.statusBadge, styles.statusBound)}>
                  <CheckCircleOutlined />
                  {intl.formatMessage({
                    id: 'pages.account.settings.security.email.boundStatus',
                    defaultMessage: '已绑定',
                  })}
                </span>
              ) : (
                <span className={cx(styles.statusBadge, styles.statusUnbound)}>
                  <ExclamationCircleOutlined />
                  {intl.formatMessage({
                    id: 'pages.account.settings.security.email.unboundStatus',
                    defaultMessage: '未绑定',
                  })}
                </span>
              )}
            </div>
            <div className={styles.securityDesc}>
              {currentUser?.email ? (
                <>
                  {intl.formatMessage({
                    id: 'pages.account.settings.security.email.bound',
                    defaultMessage: '已绑定邮箱',
                  })}
                  ：<span className={styles.securityEmail}>{currentUser.email}</span>
                </>
              ) : (
                intl.formatMessage({
                  id: 'pages.account.settings.security.email.notBound',
                  defaultMessage: '未绑定邮箱，建议绑定以提高账户安全性',
                })
              )}
            </div>
          </div>
          <div className={styles.securityAction}>
            <Button
              type="primary"
              ghost
              className={styles.securityButton}
              onClick={openEmailModal}
            >
              {currentUser?.email
                ? intl.formatMessage({
                    id: 'pages.account.settings.security.change',
                    defaultMessage: '更换',
                  })
                : intl.formatMessage({
                    id: 'pages.account.settings.security.bind',
                    defaultMessage: '绑定',
                  })}
            </Button>
          </div>
        </div>
      </div>

      {/* Password Modal */}
      <Modal
        title={intl.formatMessage({
          id: 'pages.account.settings.password.title',
          defaultMessage: '修改密码',
        })}
        open={passwordModalVisible}
        onCancel={() => {
          setPasswordModalVisible(false);
          passwordForm.resetFields();
        }}
        footer={null}
        width={440}
        destroyOnHidden
        centered
      >
        <div className={styles.modalContent}>
          <Form
            form={passwordForm}
            onFinish={handleChangePassword}
            layout="vertical"
            className={styles.modalForm}
          >
            <Form.Item
              name="oldPassword"
              label={intl.formatMessage({
                id: 'pages.account.settings.password.old',
                defaultMessage: '当前密码',
              })}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'pages.account.settings.password.old.required',
                    defaultMessage: '请输入当前密码',
                  }),
                },
              ]}
            >
              <Input.Password
                size="large"
                prefix={<LockOutlined style={{ color: 'rgba(0,0,0,0.25)' }} />}
                placeholder={intl.formatMessage({
                  id: 'pages.account.settings.password.old.placeholder',
                  defaultMessage: '请输入当前密码',
                })}
              />
            </Form.Item>

            <Form.Item
              name="newPassword"
              label={intl.formatMessage({
                id: 'pages.account.settings.password.new',
                defaultMessage: '新密码',
              })}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'pages.account.settings.password.new.required',
                    defaultMessage: '请输入新密码',
                  }),
                },
                {
                  min: 6,
                  message: intl.formatMessage({
                    id: 'pages.account.settings.password.new.minLength',
                    defaultMessage: '密码至少6个字符',
                  }),
                },
              ]}
            >
              <Input.Password
                size="large"
                prefix={<LockOutlined style={{ color: 'rgba(0,0,0,0.25)' }} />}
                placeholder={intl.formatMessage({
                  id: 'pages.account.settings.password.new.placeholder',
                  defaultMessage: '请输入新密码',
                })}
              />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              label={intl.formatMessage({
                id: 'pages.account.settings.password.confirm',
                defaultMessage: '确认新密码',
              })}
              dependencies={['newPassword']}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'pages.account.settings.password.confirm.required',
                    defaultMessage: '请确认新密码',
                  }),
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(
                      new Error(
                        intl.formatMessage({
                          id: 'pages.account.settings.password.mismatch',
                          defaultMessage: '两次输入的密码不一致',
                        }),
                      ),
                    );
                  },
                }),
              ]}
            >
              <Input.Password
                size="large"
                prefix={<LockOutlined style={{ color: 'rgba(0,0,0,0.25)' }} />}
                placeholder={intl.formatMessage({
                  id: 'pages.account.settings.password.confirm.placeholder',
                  defaultMessage: '请再次输入新密码',
                })}
              />
            </Form.Item>

            <Form.Item style={{ marginBottom: 0, marginTop: 8 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={passwordLoading}
                className={styles.submitButtonModal}
              >
                {intl.formatMessage({
                  id: 'pages.account.settings.password.submit',
                  defaultMessage: '确认修改',
                })}
              </Button>
            </Form.Item>
          </Form>
        </div>
      </Modal>

      {/* Email Modal */}
      <Modal
        title={
          currentUser?.email
            ? intl.formatMessage({
                id: 'pages.account.settings.email.changeTitle',
                defaultMessage: '更换邮箱',
              })
            : intl.formatMessage({
                id: 'pages.account.settings.email.bindTitle',
                defaultMessage: '绑定邮箱',
              })
        }
        open={emailModalVisible}
        onCancel={() => {
          setEmailModalVisible(false);
          resetEmailState();
        }}
        footer={null}
        width={480}
        destroyOnHidden
        centered
      >
        <div className={styles.modalContent}>
          {currentUser?.email && (
            <Steps
              current={emailStep}
              size="small"
              className={styles.modalSteps}
              items={[
                {
                  title: intl.formatMessage({
                    id: 'pages.account.settings.email.step1',
                    defaultMessage: '验证当前邮箱',
                  }),
                },
                {
                  title: intl.formatMessage({
                    id: 'pages.account.settings.email.step2',
                    defaultMessage: '绑定新邮箱',
                  }),
                },
              ]}
            />
          )}

          {/* Step 1: Verify current email */}
          {emailStep === 0 && currentUser?.email && (
            <Form
              form={currentEmailForm}
              onFinish={handleVerifyCurrentEmail}
              layout="vertical"
              className={styles.modalForm}
            >
              <div className={styles.currentEmailTag}>
                <MailOutlined />
                {currentUser.email}
              </div>

              <div className={styles.codeInputRow}>
                <Form.Item
                  name="currentCode"
                  className={styles.codeInput}
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({
                        id: 'pages.account.settings.email.code.required',
                        defaultMessage: '请输入验证码',
                      }),
                    },
                    {
                      len: 6,
                      message: intl.formatMessage({
                        id: 'pages.account.settings.email.code.length',
                        defaultMessage: '验证码为6位数字',
                      }),
                    },
                  ]}
                >
                  <Input
                    size="large"
                    prefix={<SafetyOutlined style={{ color: 'rgba(0,0,0,0.25)' }} />}
                    placeholder={intl.formatMessage({
                      id: 'pages.account.settings.email.code.placeholder',
                      defaultMessage: '6位验证码',
                    })}
                    maxLength={6}
                  />
                </Form.Item>
                <Button
                  size="large"
                  disabled={currentCount > 0}
                  onClick={handleSendCurrentCode}
                  className={styles.codeButton}
                >
                  {currentCount > 0
                    ? `${currentCount}s`
                    : intl.formatMessage({
                        id: 'pages.account.settings.email.sendCode',
                        defaultMessage: '发送验证码',
                      })}
                </Button>
              </div>

              <Form.Item style={{ marginBottom: 0 }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={emailLoading}
                  className={styles.submitButtonModal}
                >
                  {intl.formatMessage({
                    id: 'pages.account.settings.email.verifyNext',
                    defaultMessage: '验证并下一步',
                  })}
                </Button>
              </Form.Item>
            </Form>
          )}

          {/* Step 2: Bind new email (or direct bind) */}
          {(emailStep === 1 || !currentUser?.email) && (
            <Form
              form={newEmailForm}
              onFinish={handleBindNewEmail}
              layout="vertical"
              className={styles.modalForm}
            >
              {currentEmailVerified && (
                <div className={styles.modalSuccessTip}>
                  <CheckCircleOutlined />
                  {intl.formatMessage({
                    id: 'pages.account.settings.email.currentVerifiedTip',
                    defaultMessage: '当前邮箱已验证，请在30分钟内完成新邮箱绑定',
                  })}
                </div>
              )}

              <Form.Item
                name="newEmail"
                label={intl.formatMessage({
                  id: 'pages.account.settings.email.newEmail',
                  defaultMessage: '新邮箱',
                })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'pages.account.settings.email.newEmail.required',
                      defaultMessage: '请输入新邮箱',
                    }),
                  },
                  {
                    type: 'email',
                    message: intl.formatMessage({
                      id: 'pages.account.settings.email.newEmail.invalid',
                      defaultMessage: '邮箱格式不正确',
                    }),
                  },
                ]}
              >
                <Input
                  size="large"
                  prefix={<MailOutlined style={{ color: 'rgba(0,0,0,0.25)' }} />}
                  placeholder={intl.formatMessage({
                    id: 'pages.account.settings.email.newEmail.placeholder',
                    defaultMessage: '请输入新邮箱地址',
                  })}
                />
              </Form.Item>

              <div className={styles.codeInputRow}>
                <Form.Item
                  name="newCode"
                  className={styles.codeInput}
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({
                        id: 'pages.account.settings.email.code.required',
                        defaultMessage: '请输入验证码',
                      }),
                    },
                    {
                      len: 6,
                      message: intl.formatMessage({
                        id: 'pages.account.settings.email.code.length',
                        defaultMessage: '验证码为6位数字',
                      }),
                    },
                  ]}
                >
                  <Input
                    size="large"
                    prefix={<SafetyOutlined style={{ color: 'rgba(0,0,0,0.25)' }} />}
                    placeholder={intl.formatMessage({
                      id: 'pages.account.settings.email.code.placeholder',
                      defaultMessage: '6位验证码',
                    })}
                    maxLength={6}
                  />
                </Form.Item>
                <Button
                  size="large"
                  disabled={newCount > 0}
                  onClick={handleSendNewCode}
                  className={styles.codeButton}
                >
                  {newCount > 0
                    ? `${newCount}s`
                    : intl.formatMessage({
                        id: 'pages.account.settings.email.sendCode',
                        defaultMessage: '发送验证码',
                      })}
                </Button>
              </div>

              <Form.Item style={{ marginBottom: 0 }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={emailLoading}
                  className={styles.submitButtonModal}
                >
                  {intl.formatMessage({
                    id: 'pages.account.settings.email.confirmBind',
                    defaultMessage: '确认绑定',
                  })}
                </Button>
              </Form.Item>
            </Form>
          )}
        </div>
      </Modal>
    </>
  );
};

export default SecurityView;
