import { useState, useEffect } from 'react';
import { UserAccountAuthWrapProps } from '../model/types';
import { UserAccountAuthPermList } from './user-account-auth-perm-list';
import { useUserMenuPermissionsMutation } from '@/entities/user/api/use-user-menu-permission-mutation';
import { useUserUpdatePermissionsMutation } from '@/entities/user/api/use-user-update-permission-mutation';
import { UserMenuPermissionData } from '@/entities/user/model/types';

export const UserAccountAuthWrap = ({
  mid,
  usrid,
  idCL,
  status,
}: UserAccountAuthWrapProps) => {
  const [currentStatus, setCurrentStatus] = useState(status);
  const [currentIdCL, setCurrentIdCl] = useState(idCL);
  const [permissions, setPermissions] = useState<Array<UserMenuPermissionData>>([]);
  const [hasChanges, setHasChanges] = useState(false);
  console.log('mid : ', mid);
  console.log('usrid : ', usrid);
  console.log('idCL : ', idCL);
  console.log('status : ', status);
  const { mutateAsync: userMenuPermissions } = useUserMenuPermissionsMutation();
  const updatePermissionsMutation = useUserUpdatePermissionsMutation();
  useEffect(() => {
    if (mid && usrid) {
      console.log('userMenuPermissions');
      userMenuPermissions({mid: mid, usrid: usrid}).then((res: any) => {
        console.log('res : ', res);
        console.log('permissions : ', res?.permissions);
        setPermissions(res?.permissions || []);
      }).catch((error) => {
        console.error('Failed to fetch menu permissions:', error);
        setPermissions([]);
      });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mid, usrid]);
  
  useEffect(() => {
    console.log('permissions : ', permissions);
  }, [permissions]);

  // 변경 사항 감지
  useEffect(() => {
    const statusChanged = currentStatus !== status;
    const idCLChanged = currentIdCL !== idCL;
    setHasChanges(statusChanged || idCLChanged);
  }, [currentStatus, currentIdCL, status, idCL]);

  let menuItems = [
    {menuId: '30', parent: '30', menuName: '거래조회', subMenu: 
      [
        {menuId: '31', parent: '30', menuName: '거래내역조회'},
        {menuId: '32', parent: '30', menuName: '현금영수증발행'},
        {menuId: '33', parent: '30', menuName: '에스크로'},
        {menuId: '34', parent: '30', menuName: '빌링'}
      ]
    },
    {menuId: '35', parent: '35', menuName: '정산조회', subMenu: 
      [
        {menuId: '36', parent: '35', menuName: '정산달력'},
        {menuId: '37', parent: '35', menuName: '정산내역'},
      ]
    },
    {menuId: '38', parent: '38', menuName: '가맹점관리', subMenu: 
      [
        {menuId: '39', parent: '38', menuName: '가맹점정보'},
        {menuId: '40', parent: '38', menuName: '등록현황'},
      ]
    },
    {menuId: '41', parent: '41', menuName: '결제관리', subMenu: 
      [
        {menuId: '42', parent: '41', menuName: '결제정보'},
        {menuId: '43', parent: '41', menuName: '결제데이터통보'},
      ]
    },
    {menuId: '44', parent: '44', menuName: '계정관리', subMenu: 
      [
        {menuId: '45', parent: '44', menuName: '사용자관리'},
        {menuId: '46', parent: '44', menuName: '비밀번호관리'},
      ]
    },
    {menuId: '47', parent: '47', menuName: '부가세신고자료', subMenu: 
      [
        {menuId: '48', parent: '47', menuName: '세금계산서'},
        {menuId: '49', parent: '47', menuName: '부가세참고'},
      ]
    },
    {menuId: '50', parent: '50', menuName: '부가서비스', subMenu: 
      [
        {menuId: '51', parent: '50', menuName: '부가서비스소개'},
        {menuId: '52', parent: '50', menuName: '신용카드ARS카드결제'},
        {menuId: '53', parent: '50', menuName: '지급대행'},
        {menuId: '54', parent: '50', menuName: '링크결제'},
        {menuId: '55', parent: '50', menuName: '자금이체'},
        {menuId: '56', parent: '50', menuName: 'KEY-IN결제'},
        {menuId: '57', parent: '50', menuName: 'SMS결제통보'},
        {menuId: '58', parent: '50', menuName: '알림톡결제통보'},
        {menuId: '59', parent: '50', menuName: '계좌점유인증'},
        {menuId: '60', parent: '50', menuName: '계좌성명조회'},
        {menuId: '65', parent: '50', menuName: '안면인증'},
      ]
    },
    {menuId: '61', parent: '61', menuName: '고객지원', subMenu: 
      [
        {menuId: '62', parent: '61', menuName: '공지사항'},
        {menuId: '63', parent: '61', menuName: '자주묻는질문'},
        {menuId: '64', parent: '61', menuName: '1:1문의'},
      ]
    },
  ]
  return (
    <>
      <div className="ing-list pdtop">
        <div className="perm-form">
          <div className="perm-field">
            <div className="perm-label">계정 상태</div>
            <div className="perm-control">
              <select value={currentStatus} onChange={(e) => setCurrentStatus(e.target.value)}>
                <option value="NORMAL">사용</option>
                <option value="SUSPENDED">미사용</option>
              </select>
            </div>
          </div>
          <div className="perm-field">
            <div className="perm-label">로그인 범위</div>
            <div className="perm-control">
              <select value={currentIdCL} onChange={(e) => setCurrentIdCl(e.target.value)}>
                <option value="MID">MID</option>
                <option value="GID">MID + GID</option>
              </select>
            </div>
          </div>
        </div>

        <div className="ing-title fs18">메뉴별 권한 설정</div>

        <UserAccountAuthPermList
          mid={ mid }
          usrid={ usrid }
          idCL={ currentIdCL }
          status={ currentStatus }
          menuItems={ menuItems }
          menuGrants={ permissions }
        ></UserAccountAuthPermList>

        <div className="apply-row bottom-padding">
          <button
            className="btn-50 btn-blue flex-1"
            type="button"
            disabled={!hasChanges || updatePermissionsMutation.isPending}
            onClick={() => {
              console.log('updatePermissionMutation');
              updatePermissionsMutation.mutate(
                {
                  mid: mid,
                  usrid: usrid,
                  idCl: currentIdCL,
                  status: currentStatus
                });
            }}
          >
            {updatePermissionsMutation.isPending ? '저장 중...' : '저장'}
          </button>
        </div>

      </div>
    </>
  );
};