import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Form, Input, Button, Message } from '@arco-design/web-react';
import { IconUser, IconLock } from '@arco-design/web-react/icon';
import { useAuthStore } from '@/stores/auth';

const FormItem = Form.Item;

export default function Login() {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const login = useAuthStore((s) => s.login);

  const handleSubmit = async (values: { phone: string; password: string }) => {
    setLoading(true);
    try {
      await login(values);
      Message.success('登录成功');
      navigate('/dashboard', { replace: true });
    } catch {
      Message.error('手机号或密码错误');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      style={{
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: 'var(--color-fill-2)',
      }}
    >
      <Card
        style={{ width: 400 }}
        title={
          <div style={{ textAlign: 'center', fontSize: 24, fontWeight: 600 }}>
            充电柜管理系统
          </div>
        }
      >
        <Form onSubmit={handleSubmit} autoComplete="off">
          <FormItem
            field="phone"
            rules={[{ required: true, message: '请输入手机号' }]}
          >
            <Input
              prefix={<IconUser />}
              placeholder="手机号"
              style={{ height: 40 }}
            />
          </FormItem>
          <FormItem
            field="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<IconLock />}
              placeholder="密码"
              style={{ height: 40 }}
            />
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              htmlType="submit"
              long
              loading={loading}
              style={{ height: 40 }}
            >
              登录
            </Button>
          </FormItem>
        </Form>
      </Card>
    </div>
  );
}
