import { useState, type FormEvent } from 'react';
import { Password } from 'primereact/password';
import { Button } from 'primereact/button';
import { Card } from 'primereact/card';
import { Message } from 'primereact/message';
import BasePageHeader from '@/core/components/BasePageHeader';
import { authApi } from '../auth.api';

export default function ChangePasswordView() {
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ severity: 'success' | 'error'; text: string } | null>(null);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setMessage(null);

    if (newPassword.length < 8) {
      setMessage({ severity: 'error', text: '비밀번호는 8자 이상이어야 합니다.' });
      return;
    }
    if (newPassword !== confirmPassword) {
      setMessage({ severity: 'error', text: '새 비밀번호가 일치하지 않습니다.' });
      return;
    }

    setLoading(true);
    try {
      await authApi.changePassword({ currentPassword, newPassword });
      setMessage({ severity: 'success', text: '비밀번호가 변경되었습니다.' });
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
    } catch {
      setMessage({ severity: 'error', text: '비밀번호 변경에 실패했습니다.' });
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      <BasePageHeader title="비밀번호 변경" />
      <Card style={{ maxWidth: '480px' }}>
        {message && <Message severity={message.severity} text={message.text} style={{ width: '100%', marginBottom: '1rem' }} />}
        <form onSubmit={onSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
          <div className="form-field">
            <label className="form-field__label">현재 비밀번호</label>
            <Password value={currentPassword} onChange={(e) => setCurrentPassword(e.target.value)} feedback={false} toggleMask inputStyle={{ width: '100%' }} />
          </div>
          <div className="form-field">
            <label className="form-field__label">새 비밀번호</label>
            <Password value={newPassword} onChange={(e) => setNewPassword(e.target.value)} feedback={false} toggleMask inputStyle={{ width: '100%' }} />
          </div>
          <div className="form-field">
            <label className="form-field__label">새 비밀번호 확인</label>
            <Password value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} feedback={false} toggleMask inputStyle={{ width: '100%' }} />
          </div>
          <Button type="submit" label="변경" icon="pi pi-check" loading={loading} />
        </form>
      </Card>
    </div>
  );
}
