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';
import { MenuItems } from '@/entities/common/model/constant';
import { useTranslation } from 'react-i18next';

export const UserAccountAuthWrap = ({
  mid,
  usrid,
  idCL,
  status,
}: UserAccountAuthWrapProps) => {
  const { t } = useTranslation();
  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]);
  return (
    <>
      <div className="ing-list pdtop pb-86">
        <div className="perm-form">
          <div className="perm-field">
            <div className="perm-label">{t('account.accountStatus')}</div>
            <div className="perm-control">
              <select value={currentStatus} onChange={(e) => setCurrentStatus(e.target.value)}>
                <option value="NORMAL">{t('account.active')}</option>
                <option value="SUSPENDED">{t('account.inactive')}</option>
              </select>
            </div>
          </div>
          <div className="perm-field">
            <div className="perm-label">{t('account.loginScope')}</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">{t('account.menuPermissions')}</div>

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

        <div className="apply-row">
          <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 ? t('common.saving') : t('common.save')}
          </button>
        </div>

      </div>
    </>
  );
};