import { EditOutlined, FileTextOutlined, KeyOutlined, LockOutlined, LoginOutlined, LogoutOutlined, MailOutlined, MobileOutlined, ReloadOutlined } from "@ant-design/icons";
import { useLogto, type IdTokenClaims } from "@logto/react";
import { App, Avatar, Button, Divider, Flex, Typography } from "antd";
import { useCallback, useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router";
import { AUTH_CALLBACK_URL, USER_CENTER_URL } from "../utils/front";
import useAutoLogin from "../hooks/useAutoLogin";
import { LOGTO_DOMAIN } from "../utils/common";
import { useAppVersion } from "../hooks/useAppVersion";
import { BindKaiqiuAccount } from "../components/BindKaiqiuAccount";
import { ChangeBackground } from "../components/ChangeBackground";
import PermissionControlPanel from "../components/PermissionControlPanel";

enum modifyRoutes {
  username = '/account/username',
  email = '/account/email',
  passwd = '/account/password',
  passkey = '/account/passkey/manage',
  auth_app = '/account/authenticator-app',
  backup_code = '/account/backup-codes/generate',
}

const redirect = encodeURIComponent(USER_CENTER_URL);

function AppVersion({ version }: { version?: string }) {
  if (!version) return null;
  return (
    <Divider>
      <Typography.Text type="secondary">
        <Flex gap={4}>
          <span style={{ textTransform: 'uppercase' }}>app version:</span>
          {version}
        </Flex>
      </Typography.Text>
    </Divider>
  );
}

export const UserCenter = () => {
  const { signIn, isAuthenticated, signOut, getIdTokenClaims } = useLogto();
  const { autoSignIn } = useAutoLogin();
  const [user, setUser] = useState<IdTokenClaims>();
  const navigate = useNavigate();
  const location = useLocation();
  const handleSignIn = useCallback(() => {
    signIn(AUTH_CALLBACK_URL);
  }, []);
  useEffect(() => {
    if (isAuthenticated) return;
    const autoSignIn = new URLSearchParams(location.search).get('autoSignIn');
    if (autoSignIn) {
      handleSignIn();
    }
  }, [isAuthenticated]);
  useEffect(() => {
    if (!isAuthenticated) return;
    getIdTokenClaims().then(claims => setUser(claims));
  }, [isAuthenticated]);
  const handleModifyInfo = useCallback((url: string) => {
    window.location.href = `${LOGTO_DOMAIN}${url}?redirect=${redirect}`;
  }, []);
  const app = App.useApp();
  const version = useAppVersion();
  if (!isAuthenticated) {
    return (
      <div className="app">
        <Button
          block
          type="primary"
          icon={<LogoutOutlined />}
          size="large"
          onClick={handleSignIn}
        >
          登录
        </Button>
        <AppVersion version={version} />
      </div>
    );
  }
  return (
    <>
      <ChangeBackground url={user?.picture ?? ''} />
      <Flex className="app" gap={12} vertical align="center" style={{ maxWidth: 600 }}>
        <Avatar size={128} src={user?.picture} style={{ background: '#f56a00' }}>
          {(user?.username || user?.name)}
        </Avatar>
        <Flex>
          <Typography.Text>{user?.username ?? user?.name ?? '未设置'}</Typography.Text>
        </Flex>
        <BindKaiqiuAccount />
        <Divider>权限设置</Divider>
        <PermissionControlPanel />
        <Divider>修改信息</Divider>
        <Button block icon={<EditOutlined />} onClick={() => handleModifyInfo(modifyRoutes.username)}>修改用户名({user?.username ?? '未设置'})</Button>
        <Button block icon={<MailOutlined />} onClick={() => handleModifyInfo(modifyRoutes.email)}>修改 E-Mail</Button>
        <Button block icon={<LockOutlined />} onClick={() => handleModifyInfo(modifyRoutes.auth_app)}>修改密码</Button>
        <Button block icon={<MobileOutlined />} onClick={() => handleModifyInfo(modifyRoutes.auth_app)}>添加验证器</Button>
        <Button block icon={<KeyOutlined />} onClick={() => handleModifyInfo(modifyRoutes.passkey)}>管理 Passkey</Button>
        <Button block icon={<FileTextOutlined />} onClick={() => handleModifyInfo(modifyRoutes.backup_code)}>备份代码</Button>
        <Divider />
        <Flex align="center" justify="center" style={{ width: '100%' }} gap={12}>
          <Flex flex={1}>
            <Button block icon={<ReloadOutlined />} onClick={() => autoSignIn()}>
              重新登陆
            </Button>
          </Flex>
          <Flex flex={1}>
            <Button
              block
              danger
              icon={<LoginOutlined />}
              onClick={() => app.modal.confirm({
                maskClosable: true,
                title: '确认登出？',
                cancelText: '保持登录',
                okText: '确认登出',
                okButtonProps: {
                  icon: <LogoutOutlined />,
                  danger: true,
                },
                onOk: () => signOut(USER_CENTER_URL),
              })}
            >
              登出
            </Button>
          </Flex>
        </Flex>
      </Flex>
      <AppVersion version={version} />
    </>
  );
}