import { useState } from 'react';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType } from '@/entities/common/model/types';
import {
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useUserChangePasswordMutation } from '@/entities/user/api/use-user-change-password-mutation';
import { snackBar } from '@/shared/lib/toast';

export const PasswordModifyLoginPasswordPage = () => {
  const { navigate } = useNavigate();
  const [currentPassword, setCurrentPassword] = useState<string>('');
  const [newPassword, setNewPassword] = useState<string>('');
  const [confirmPassword, setConfirmPassword] = useState<string>('');
  const [usrid, ] = useState<string>('nictest00');

  const changePasswordMutation = useUserChangePasswordMutation({
    onSuccess: () => {
      snackBar('비밀번호가 성공적으로 변경되었습니다.');
      // Clear form
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
      // Navigate back
      navigate(PATHS.account.password.manage);
    },
    onError: (error) => {
      snackBar(error?.response?.data?.message || '비밀번호 변경에 실패했습니다.');
    }
  });

  useSetHeaderTitle('로그인 비밀번호 변경');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.account.password.manage);
  });

  // 저장 버튼 활성화 조건 체크
  const isFormValid = () => {
    return (
      currentPassword.length >= 8 &&
      newPassword.length >= 8 &&
      confirmPassword.length >= 8 &&
      newPassword === confirmPassword
    );
  };

  // 저장 버튼 클릭 핸들러
  const handleSave = () => {
    if (!isFormValid()) return;

    // TODO: Validate current password before submitting
    changePasswordMutation.mutate({
      usrid: usrid,
      currentPassword: currentPassword,
      newPassword: newPassword,
    });
  };

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="ing-list add">
              <div className="user-add">
                <div className="ua-row">
                  <div className="ua-label">기존 비밀번호 <span className="red">*</span></div>
                  <input
                    className="wid-100"
                    type="password"
                    placeholder=""
                    value={currentPassword}
                    onChange={(e) => setCurrentPassword(e.target.value)}
                  />
                </div>
                <div className="ua-row">
                  <div className="ua-label">변경 비밀번호 <span className="red">*</span></div>
                  <input
                    className={`wid-100 ${confirmPassword && newPassword !== confirmPassword ? 'error' : ''}`}
                    type="password"
                    placeholder=""
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                  />
                </div>
                <div className="ua-row">
                  <div className="ua-label">변경 비밀번호 재입력 <span className="red">*</span></div>
                  <input
                    className={`wid-100 ${confirmPassword && newPassword !== confirmPassword ? 'error' : ''}`}
                    type="password"
                    placeholder=""
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                  />
                </div>
                {confirmPassword && newPassword !== confirmPassword && (
                  <div className="ua-help error">입력 정보 불일치</div>
                )}
              </div>

              <div className="apply-row bottom-padding">
                <button
                  className="btn-50 btn-blue flex-1"
                  type="button"
                  disabled={!isFormValid() || changePasswordMutation.isPending}
                  onClick={handleSave}
                >{changePasswordMutation.isPending ? '처리중...' : '저장'}</button>
              </div>
            </div>
          </div>
        </div>
      </main>
    </>
  );
};