<script setup lang="ts">
  import { IUser, UserRole } from '~/types'
  import { MIN_PASSWORD_LENGTH, ModalButtonMode } from '~/constants'
  import { useUsers } from '~/composables/useUsers'

  const toast = useToast()
  const users = useUsers()
  const auth = useAuth()
  const emits = defineEmits(['userComplete', 'selfComplete', 'deleteUser'])
  const showPassword = ref(false)
  const showRepeatPassword = ref(false)
  const modalShow = ref(true)
  const showBackdrop = ref(false)

  const props = defineProps({
    modalTitle: {
      type: String,
      required: false,
      default: 'User edit'
    },
    name: {
      type: String,
      required: false,
      default: ''
    },
    middleName: {
      type: String,
      required: false,
      default: ''
    },
    surname: {
      type: String,
      required: false,
      default: ''
    },
    email: {
      type: String,
      required: false,
      default: ''
    },
    role: {
      type: String,
      required: false,
      default: UserRole.ADMIN
    },
    password: {
      type: String,
      required: false,
      minlength: MIN_PASSWORD_LENGTH,
      default: ''
    },
    repeatPassword: {
      type: String,
      required: false,
      minLength: MIN_PASSWORD_LENGTH,
      default: ''
    },
    createdAt: {
      type: Number,
      required: false,
      default: 1
    },
    mode: {
      type: String,
      required: false,
      default: ModalButtonMode.UPDATE
    },
    id: {
      type: Number,
      required: false,
      default: 0
    },
    user: {
      type: Object,
      required: true
    },
    selectedUser: {
      type: Object,
      required: true
    },
    suspendUser: {
      type: Function,
      required: false,
      default: null
    }
  })

  const togglePasswordVisibility = (field) => {
    if (field === 'passwordInput') {
      showPassword.value = !showPassword.value
    } else if (field === 'repeatPasswordInput') {
      showRepeatPassword.value = !showRepeatPassword.value
    }
  }

  const closeModal = () => {
    modalShow.value = false
    emits('userComplete')
  }

  const selectedRole: Ref<UserRole> = ref(props.role)

  const eventName = computed(() => {
    return `${props.mode}clicked`
  })

  const isEmail = (val: string) =>
    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
      val
    )
  const form = ref({
    id: {
      value: props.id,
      error: false
    },
    name: {
      value: props.name,
      error: false
    },
    middleName: {
      value: props.middleName,
      error: false
    },
    surname: {
      value: props.surname,
      error: false
    },
    email: {
      value: props.email,
      error: false
    },
    password: {
      // value: '',
      value: props.password,
      error: false
    },
    repeatPassword: {
      // value: '',
      value: props.repeatPassword,
      error: false
    },
    errors: {
      value: '',
      error: false
    }
  })

  const isEditable = (fieldName: string) => {
    const adminRoles = ['ADMIN', 'SUPER_ADMIN']
    const userRoles = ['MANAGER', 'STAFF_MEMBER']

    if (adminRoles.includes(auth.currentUser.value.role)) {
      return true // Allow editing for admins and super admins
    } else if (userRoles.includes(auth.currentUser.value.role)) {
      if (fieldName === 'password' || fieldName === 'repeatPassword') {
        return true // Allow editing for password fields for the current user
      }
    }
    return false // Disable editing for other fields
  }

  const setValue = () => {
    form.value.id.value = props.id
    form.value.name.value = props.name
    form.value.middleName.value = props.middleName
    form.value.surname.value = props.surname
    form.value.email.value = props.email
    form.value.password.value = ''
    form.value.repeatPassword.value = ''
    selectedRole.value = props.role

    console.log('Password: ', form.value.password.value)
    console.log('Password2: ', form.value.repeatPassword.value)
  }

  const properties = toRefs(props)

  watch(properties.name, setValue)

  const selectRole = (role: UserRole) => {
    selectedRole.value = role
  }

  const doSave = async () => {
    // Add
    if (props.mode === ModalButtonMode.ADD) {
      if (form.value.name.value.length === 0) {
        form.value.name.error = true
      } else if (form.value.middleName.value.length === 0) {
        form.value.middleName.error = true
      } else if (form.value.surname.value.length === 0) {
        form.value.surname.error = true
      } else if (!isEmail(form.value.email.value)) {
        form.value.email.error = true
      } else if (form.value.password.value.length < MIN_PASSWORD_LENGTH) {
        form.value.password.error = true
      } else if (form.value.repeatPassword.value.length < MIN_PASSWORD_LENGTH) {
        form.value.repeatPassword.error = true
      } else if (
        form.value.password.value !== form.value.repeatPassword.value
      ) {
        form.value.password.error = true
        form.value.repeatPassword.error = true
        toast.error('Passwords do not match')
      } else {
        const newUser: IUser = {
          name: form.value.name.value,
          middleName: form.value.middleName.value,
          surname: form.value.surname.value,
          email: form.value.email.value,
          role: Object.keys(UserRole)[
            Object.values(UserRole).indexOf(selectedRole.value)
          ]
        }
        if (form.value.password.value.length > 0) {
          Object.assign(newUser, {
            password: form.value.password.value
          })
        }

        const { error } = await users.addUser(newUser)
        if (error.value) {
          const { message } = error.value
          form.value.errors.value = message
          toast.error(`${message}`)
          console.log(error.value)
        } else {
          modalShow.value = false
          showBackdrop.value = false
          emits('userComplete')
          // emits('show')
          toast.success('User create successful')
        }
      }
    }

    // Update
    else if (form.value.name.value.length === 0) {
      console.log('Inside Admin Edit')
      form.value.name.error = true
    } else if (form.value.middleName.value.length === 0) {
      form.value.middleName.error = true
    } else if (form.value.surname.value.length === 0) {
      form.value.surname.error = true
    } else if (!isEmail(form.value.email.value)) {
      form.value.email.error = true
    } else if (
      form.value.password.value.length > 0 &&
      form.value.password.value.length < MIN_PASSWORD_LENGTH
    ) {
      form.value.password.error = true
    } else {
      const newUser: IUser = {
        name: form.value.name.value,
        middleName: form.value.middleName.value,
        surname: form.value.surname.value,
        email: form.value.email.value,
        role: Object.keys(UserRole)[
          Object.values(UserRole).indexOf(selectedRole.value)
        ]
      }
      if (form.value.password.value.length > 0) {
        Object.assign(newUser, {
          password: form.value.password.value
        })
        console.log('First pass: ', newUser.password)
      }
      // if (
      //   auth.currentUser.value.role === 'ADMIN' ||
      //   auth.currentUser.value.role === 'SUPER_ADMIN'
      // ) {
      //   const { error } = await users.updateUser(newUser, props.id)
      //   if (error.value) {
      //     const { message } = error.value
      //     form.value.errors.value = message
      //     toast.error(`${message}`)
      //     console.log(error.value)
      //   } else {
      //     modalShow.value = false
      //     emits('userComplete')
      //     emits('show')
      //     toast.success('User edit successful')
      //   }
      // }

      console.log('Inside Self Edit')
      console.log('2nd pass: ', newUser.password)
      const { error } = await users.updateSelf(newUser, newUser.password)

      if (error.value) {
        const { message } = error.value
        form.value.errors.value = message
        toast.error(`${message}`)
        console.log(error.value)
      } else {
        modalShow.value = false
        emits('selfComplete')
        toast.success('User edit successful')
      }
    }
  }
</script>
 this is the scrip tag for my usermodal component , the issue im facing is when i try to update only the password nothing happens, the code istn being reached