import { useState } from 'react';
import { Button, Form, Input, NavBar, Toast } from 'antd-mobile';
import { useLocation, useNavigate } from 'react-router-dom';
import { authApi } from '@/api/auth';
import { initPush } from '@/push/initPush';
import { useAuthStore } from '@/stores/authStore';

export default function Login() {
  const navigate = useNavigate();
  const location = useLocation() as { state?: { from?: string } };
  const setSession = useAuthStore((s) => s.setSession);
  const [submitting, setSubmitting] = useState(false);

  const onFinish = async (values: { loginId: string; password: string }) => {
    setSubmitting(true);
    try {
      const r = await authApi.login(values);
      const me = await authApi.me().catch(() => null);
      setSession(r.accessToken, r.refreshToken, me ?? {
        userId: 0, loginId: values.loginId,
      });
      Toast.show({ icon: 'success', content: '로그인 성공' });
      void initPush(); // 푸시 토큰 등록 (config-gated, 미설정 시 no-op)
      navigate(location.state?.from ?? '/', { replace: true });
    } catch {
      // request interceptor 가 토스트 처리
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="page" style={{ paddingBottom: 0 }}>
      <NavBar back={null}>GA 설계사 셀프 조회</NavBar>
      <div style={{ padding: 24 }}>
        <div style={{ fontSize: 22, fontWeight: 700, marginBottom: 8 }}>로그인</div>
        <div style={{ color: '#999', marginBottom: 24, fontSize: 13 }}>
          본인 정산 명세서·출금 신청·공지를 조회합니다.
        </div>
        <Form
          layout="vertical"
          onFinish={onFinish}
          footer={
            <Button block type="submit" color="primary" size="large" loading={submitting}>
              로그인
            </Button>
          }
        >
          <Form.Item label="아이디" name="loginId" rules={[{ required: true, message: '아이디를 입력하세요' }]}>
            <Input placeholder="loginId" clearable />
          </Form.Item>
          <Form.Item label="비밀번호" name="password" rules={[{ required: true, message: '비밀번호를 입력하세요' }]}>
            <Input placeholder="********" type="password" clearable />
          </Form.Item>
        </Form>
        <div style={{ marginTop: 16, fontSize: 12, color: '#bbb', textAlign: 'center' }}>
          PWA · 홈 화면에 추가하면 앱처럼 사용할 수 있습니다.
        </div>
      </div>
    </div>
  );
}
