import { Button, Card, Form, Input, Popover } from 'antd';
import './login-form.less';
import { BsPersonCircle } from 'react-icons/bs';
import { IoLockClosed } from 'react-icons/io5';
import { useState } from 'react';
import { Rule } from 'antd/es/form';
import { capitalizeEachWord } from '@pos/base';

interface Payload {
  username: string;
  password: string;
}

interface LoginForm {
  onSubmit(payload: Payload): Promise<void>;
}

function inputRule(label: string): Rule[] {
  return [
    { required: true, message: `${capitalizeEachWord(label)} harus diisi!` },
    {
      max: 100,
      message: `${capitalizeEachWord(label)} maksimal 50 karakter!`,
    },
    ...(label === 'username'
      ? [
          {
            pattern: new RegExp(/^[a-zA-Z0-9 ]*$/i),
            message: `${capitalizeEachWord(label)} hanya menerima alfanumerik!`,
          },
        ]
      : []),
  ];
}

export function LoginForm(props: LoginForm) {
  const onSubmit = props?.onSubmit;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  async function onFinish(payload: Payload) {
    setLoading(true);
    try {
      if (onSubmit)
        await onSubmit({
          username: payload?.username?.trim(),
          password: payload?.password?.trim(),
        });
    } catch ({ response }: any) {
      form.setFields([{ name: 'validation', errors: [response?.data?.message] }]);
    } finally {
      setLoading(false);
    }
  }

  async function onValuesChange() {
    form.setFields([{ name: 'validation', errors: [] }]);
  }

  return (
    <div className="login-form">
      <Card className="shadow-md bg-white/90 w-2/6 p-4 rounded-3xl min-w-96 max-w-md">
        <div className="title">
          <h1>Hello</h1>
          <h2>Welcome Team!</h2>
          <h3>Smile ... It's a beatiful day.</h3>
        </div>
        <Form form={form} onFinish={onFinish} className="mt-6" layout="vertical" onValuesChange={onValuesChange}>
          <Popover content="Username" placement="right">
            <Form.Item name="username" rules={inputRule('username')} className="mb-4">
              <Input
                size="large"
                placeholder="username"
                className="rounded-3xl"
                prefix={<BsPersonCircle color="#7973b1" className="mr-3" />}
              />
            </Form.Item>
          </Popover>
          <Popover content="Password" placement="right">
            <Form.Item name="password" rules={inputRule('password')} className="mb-7">
              <Input.Password
                size="large"
                className="rounded-3xl"
                placeholder="password"
                prefix={<IoLockClosed color="#7973b1" className="mr-3" />}
              />
            </Form.Item>
          </Popover>

          <Form.Item name="validation" className="m-0 text-center">
            <Button size="large" loading={loading} type="primary" className="w-full mb-2 rounded-3xl" htmlType="submit">
              Login
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
