import { getYear } from 'date-fns';
import { FC, useState } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import { useNavigate } from 'react-router';
import { Toaster } from 'sonner';
import { productVersion } from '../../../package.json';
import LoginBg from '../../assets/loginBg.png';
// import { authClient } from '../../auth/client';
import { Button, Group, Stack } from '../../components';
import { PasswordInput } from '../../components/PasswordInput';
import { RememberCheckbox } from './RememberCheckbox';

type Inputs = {
  username: string;
  password: string;
};

export const LoginScene: FC = () => {
  const navigate = useNavigate();
  const { register, handleSubmit } = useForm<Inputs>();

  const [failLogin, setFailLogin] = useState(false);
  const [loading, setLoading] = useState(false);

  const onSubmit: SubmitHandler<Inputs> = ({ username, password }) => {
    // TODO: handle login
    // setLoading(true);
    // authClient.actions
    //   .generateToken({
    //     username,
    //     password,
    //     allowRefresh: true,
    //     lifeTime: 1296000,
    //     audience: 'test-auth',
    //   })
    //   .then(([error, result]) => {
    //     setLoading(false);
    //     if (error) {
    //       toast.error((error.error as Error).message, {
    //         classNames: { icon: 'text-red' },
    //       });
    //       setFailLogin(true);
    //       setLoading(false);
    //       return;
    //     }
    //     const { token } = result;
    //     localStorage.setItem('token', token);
    //     navigate('/dashboard');
    //   });
    setFailLogin(false);
    setLoading(false);
    console.log('username', username);
    console.log('password', password);
    navigate('/');
  };

  const [rememberMe, setRememberMe] = useState(true);
  return (
    <section className="h-100vh w-100vw flex flex-col items-center justify-center overflow-hidden bg-black text-white">
      <Toaster style={{ zIndex: 50 }} position="top-right" expand={true} />
      <form
        className="min-h-105% min-w-110% flex flex-col items-center justify-center bg-cover bg-center"
        style={{
          backgroundImage: `url(${LoginBg})`, // TODO: change icon
        }}
        onSubmit={handleSubmit(onSubmit)}
      >
        <div className="w w-120 flex flex-col items-center rounded-xl p-10">
          <div className="mb-10 mt-8 w-full flex flex-col gap-6">
            <div className="relative">
              <div className="pointer-events-none absolute start-0 inset-y-0 flex items-center ps-3">
                <div className="i-ant-design-user-outlined h-5 w-5 text-orange-600"></div>
              </div>
              <input
                type="text"
                className="block w-full border border-gray-300 rounded-lg bg-white p-2.5 ps-10 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500"
                required
                placeholder="username"
                {...register('username', { required: true })}
              />
            </div>
            <PasswordInput
              placeholder="password"
              {...register('password', { required: true })}
            />
            <div className="flex justify-between">
              <RememberCheckbox
                label="Remember me"
                checked={rememberMe}
                onChange={() => {
                  setRememberMe(!rememberMe);
                }}
              />
            </div>
            <Group className="items-center">
              <Button
                type="submit"
                className="h-10 w-30 border-sky-800 bg-sky-600 px-1.5 py-2 text-white"
              >
                {loading && <div className="i-mdi-loading h-5 animate-spin" />}
                Sign In
              </Button>
              {failLogin && (
                <div className="pl-10 text-red">
                  Incorrect username or password
                </div>
              )}
            </Group>
          </div>
        </div>
        <Stack className="items-center gap-2">
          <p>{`© ${getYear(new Date())} F.A.S.T.`}</p>
          <p>{`Ver. ${productVersion}`}</p>
        </Stack>
      </form>
    </section>
  );
};
