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 { useUserChangeCancelPasswordMutation } from '@/entities/user/api/use-user-change-cancel-password-mutation';
import { snackBar } from '@/shared/lib/toast';

export const PasswordModifyCancelPasswordPage = () => {
  const { navigate } = useNavigate();
  const [mid, setMid] = useState<string>('nictest00m');
  const [password, setPassword] = useState<string>('');
  const [confirmPassword, setConfirmPassword] = useState<string>('');

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

  const midList = [
    { value: 'nictest00', label: 'nictest00' },
    { value: 'nictest00m', label: 'nictest00m' },
    { value: 'nictest01m', label: 'nictest01m' },
    { value: 'nictest02m', label: 'nictest02m' },
  ];

  useSetHeaderTitle('거래취소 비밀번호 변경');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.account.password.manage);
  });

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

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

    // TODO: Validate current password before submitting
    changeCancelPasswordMutation.mutate({
      mid,
      password: password
    });
  };

  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>
                  <select className="wid-100" value={mid} onChange={(e) => setMid(e.target.value)}>
                    {midList.map((item) => (
                      <option key={item.value} value={item.value}>{item.label}</option>
                    ))}
                  </select>
                </div>
                <div className="ua-row">
                  <div className="ua-label">변경 비밀번호 <span className="red">*</span></div>
                  <input
                    className={`wid-100 ${confirmPassword && password !== confirmPassword ? 'error' : ''}`}
                    type="password"
                    placeholder=""
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                </div>
                <div className="ua-row">
                  <div className="ua-label">변경 비밀번호 재입력 <span className="red">*</span></div>
                  <input
                    className={`wid-100 ${confirmPassword && password !== confirmPassword ? 'error' : ''}`}
                    type="password"
                    placeholder=""
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                  />
                </div>
                {confirmPassword && password !== 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() || changeCancelPasswordMutation.isPending}
                  onClick={handleSave}
                >{changeCancelPasswordMutation.isPending ? '처리중...' : '저장'}</button>
              </div>
            </div>
          </div>
        </div>
      </main>
    </>
  );
};