import { useState, type FormEvent } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';
import { Card } from 'primereact/card';
import { Message } from 'primereact/message';
import { useAuthStore } from '../auth.store';
import './LoginView.scss';

export default function LoginView() {
  const login = useAuthStore((s) => s.login);
  const loading = useAuthStore((s) => s.loading);
  const navigate = useNavigate();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');

  async function onLogin(e: FormEvent) {
    e.preventDefault();
    setError('');
    try {
      await login(email, password);
      navigate('/dashboard');
    } catch (err: unknown) {
      const axiosErr = err as { response?: { data?: { detail?: string } } };
      setError(axiosErr?.response?.data?.detail ?? '로그인에 실패했습니다. 이메일과 비밀번호를 확인하세요.');
    }
  }

  return (
    <div className="login-page">
      <Card className="login-page__card">
        <div className="login-page__content">
          <div className="login-page__logo">
            <i className="pi pi-clock" style={{ fontSize: '2.5rem', color: 'var(--p-primary-color)' }} />
            <h1 className="login-page__title">WTM</h1>
            <p className="login-page__subtitle">Work Time Manager</p>
          </div>

          {error && <Message severity="error" text={error} style={{ width: '100%' }} />}

          <form className="login-page__form" onSubmit={onLogin}>
            <div className="form-field">
              <label className="form-field__label">이메일</label>
              <InputText
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                type="email"
                placeholder="user@hanwha.com"
                required
              />
            </div>

            <div className="form-field">
              <label className="form-field__label">비밀번호</label>
              <InputText
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                type="password"
                placeholder="비밀번호 입력"
              />
            </div>

            <Button
              type="submit"
              label="로그인"
              icon="pi pi-sign-in"
              loading={loading}
              className="login-page__submit"
            />
          </form>

          <div className="login-page__links">
            <Link to="/forgot-password" className="login-page__link">
              비밀번호 찾기
            </Link>
          </div>
        </div>
      </Card>
    </div>
  );
}
