import Footer from '@/components/Footer/Footer';
import { ROUTE_HOME } from '@/constants';
import { login } from '@/services/controller/AuthController';
import { parseJwt } from '@/utils/jwtTokenUtils';
import { getToken, removeToken, setToken } from '@/utils/localStorageUtils';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginFormPage, ProFormText } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { Image, theme } from 'antd';
import { useEffect } from 'react';
import logoImg from '../../../public/logo.png';
import mobifontImg from '../../../public/owner.png';

const LoginPage = () => {
  const { token } = theme.useToken();
  const urlParams = new URL(window.location.href).searchParams;
  const redirect = urlParams.get('redirect');

  useEffect(() => {
    checkLogin();
  }, []);
  const checkLogin = () => {
    const token = getToken();
    if (!token) {
      return;
    }
    const parsed = parseJwt(token);
    const { sub, exp } = parsed;
    const now = Math.floor(Date.now() / 1000);
    const oneHour = 60 * 60;
    if (exp - now < oneHour) {
      removeToken();
    } else {
      if (redirect) {
        history.push(redirect);
      } else {
        history.push(ROUTE_HOME);
      }
    }
  };

  const handleLogin = async (values: API.LoginRequestBody) => {
    try {
      const resp = await login(values);
      if (resp?.token) {
        setToken(resp.token);
        if (redirect) {
          history.push(redirect);
        } else {
          history.push(ROUTE_HOME);
        }
      }
    } catch (error) {
      console.error('Login error:', error);
    }
  };

  return (
    <div
      style={{
        backgroundColor: 'white',
        height: '100vh',
      }}
    >
      <LoginFormPage
        backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
        logo={logoImg}
        backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
        title={
          <span style={{ color: token.colorBgContainer }}>
            Hệ thống giám sát tàu cá
          </span>
        }
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0,0.65)',
          backdropFilter: 'blur(4px)',
        }}
        subTitle={<Image preview={false} src={mobifontImg} />}
        submitter={{
          searchConfig: {
            submitText: 'Đăng nhập',
          },
        }}
        onFinish={async (values: API.LoginRequestBody) => handleLogin(values)}
      >
        <>
          <ProFormText
            name="username"
            fieldProps={{
              size: 'large',
              prefix: (
                <UserOutlined
                  style={{
                    color: token.colorText,
                  }}
                  className={'prefixIcon'}
                />
              ),
            }}
            placeholder={'Tài khoản'}
            rules={[
              {
                required: true,
                message: 'Tài khoản không được để trống!',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: (
                <LockOutlined
                  style={{
                    color: token.colorText,
                  }}
                  className={'prefixIcon'}
                />
              ),
            }}
            placeholder={'Mật khẩu'}
            rules={[
              {
                required: true,
                message: 'Mật khẩu không được để trống!',
              },
            ]}
          />
        </>
      </LoginFormPage>
      <div
        style={{
          backgroundColor: 'transparent',
          position: 'absolute',
          bottom: 0,
          zIndex: 99,
          width: '100%',
        }}
      >
        <Footer />
      </div>
    </div>
  );
};
export default LoginPage;
