'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { getSession, signIn } from 'next-auth/react';
import { Form, Input, Button, Typography, notification, Alert } from 'antd';
import { UserOutlined, LockOutlined, EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
import { userEmailValidator } from '@/utills/validator';
import { loginPost } from '../service';
import FirstChangePassword from '../components/FirstChangePassword';

const { Title, Paragraph } = Typography;

const LoginPage: React.FC = () => {
  const [isLogin, setIsLogin] = useState<boolean | null>(null);
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [showPassword, setShowPassword] = useState(false);
  const [changePassword, setChangePassword] = useState<{ id: number; token: string } | null>(null);

  const onFinish = async(values: { username: string; password: string; }) => {
    setSubmitting(true);
    await loginPost({ email: values.username, password: values.password })
      .then((result) => {
        if (result.data.user.first_login === 1) {
          setChangePassword({
            id: result.data.user.id,
            token: result.data.user.token,
          });
        } else {
          signIn('credentials', {
            email: values.username,
            password: values.password,
            user: JSON.stringify(result.data.user),
            callbackUrl: '/dashboard',
          });
        }
        setSubmitting(false);
      })
      .catch((error) => {
        notification.error({
          message: 'Error',
          description: error.response.data.message,
        });
        setSubmitting(false);
      });
  };

  const togglePasswordVisibility = (): void => {
    setShowPassword(!showPassword);
  };

  useEffect(() => {
    getSession()
      .then((session) => {
        if (session) {
          setIsLogin(true);
        } else {
          setIsLogin(false);
        }
      })
      .catch(() => {
        setIsLogin(false);
      });
  }, []);

  if (isLogin) {
    window.location.href = '/dashboard';
    return <></>;
  }

  if (isLogin === null) {
    return <></>;
  }

  return (
    <div className="auth-page">
      <div className="login-box">
        <div className="login-box-header">
          <div className="logo">
            <Image src="/images/logo.png" alt="logo" height={50} width={194} />
          </div>
        </div>
        <div className="login-box-content">
          <Title level={3} className="login-box-title">
                        Welcome to Housiey
          </Title>
          {changePassword ? (
            <>
              <Alert description={'Please set a personalized password for your account.'} message={<>Successfully authorized</>} type="success"
                showIcon className='my-5'/>

              <FirstChangePassword user={changePassword} callAfterSuccess={setChangePassword}/>
            </>
          ) : (
            <>
              <Paragraph className="login-box-subtitle">
                        Sign in by entering information below
              </Paragraph>
              <Form name="login" onFinish={onFinish}>
                <Form.Item
                  name="username"
                  rules={[{ validator: userEmailValidator(' ') }]}>
                  <Input
                    prefix={<UserOutlined className="site-form-item-icon" />}
                    placeholder="Email"
                    size="large"
                  />
                </Form.Item>
                <Form.Item
                  name="password"
                  rules={[
                    {
                      required: true,
                      message: 'Please Enter Your Password',
                    },
                  ]}>
                  <Input.Password
                    prefix={<LockOutlined className="site-form-item-icon" />}
                    type={showPassword ? 'text' : 'password'}
                    placeholder="Password"
                    size="large"
                    suffix={
                      <span onClick={togglePasswordVisibility}>
                        {showPassword ? (
                          <EyeTwoTone />
                        ) : (
                          <EyeInvisibleOutlined />
                        )}
                      </span>
                    }
                  />
                </Form.Item>
                <Form.Item>
                  <Button
                    loading={submitting}
                    type="primary"
                    htmlType="submit"
                    size="large"
                    className="login-form-button"
                  >
                                    Login
                  </Button>
                </Form.Item>
                <div className="login-box-footer">
                  <Link href="./forgotPassword">Forgot Password?</Link>
                </div>
              </Form>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default LoginPage;
