'use client'
import React, { useEffect } from 'react'

/**
 * Global provider that injects a password visibility toggle (eye icon)
 * into ALL password input fields across the Payload admin panel.
 *
 * This works on every page — login, reset password, account, etc. —
 * without needing to override any built-in views.
 */
const PasswordToggleProvider: React.FC<{ children?: React.ReactNode }> = ({ children }) => {
  useEffect(() => {
    const eyeOpenSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"/><circle cx="12" cy="12" r="3"/></svg>`
    const eyeClosedSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"/><path d="M14.084 14.158a3 3 0 0 1-4.242-4.242"/><path d="M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"/><path d="m2 2 20 20"/></svg>`

    const styleId = 'password-toggle-styles'
    if (!document.getElementById(styleId)) {
      const style = document.createElement('style')
      style.id = styleId
      style.textContent = `
        .pw-toggle-parent {
          position: relative !important;
        }
        .pw-toggle-input {
          padding-right: 3rem !important;
        }
        .pw-toggle-btn {
          position: absolute;
          right: 0.75rem;
          top: 50%;
          transform: translateY(-50%);
          background: none;
          border: none;
          cursor: pointer;
          padding: 0.25rem;
          display: flex;
          align-items: center;
          justify-content: center;
          color: var(--theme-elevation-400);
          transition: color 0.15s ease;
          z-index: 5;
          line-height: 0;
        }
        .pw-toggle-btn:hover {
          color: var(--theme-text);
        }
      `
      document.head.appendChild(style)
    }

    const MARKER = 'data-pw-toggle'

    function addToggle(input: HTMLInputElement) {
      if (input.getAttribute(MARKER)) return
      input.setAttribute(MARKER, 'true')

      const parent = input.parentElement
      if (!parent) return

      // DO NOT reparent the input. React/Next.js will lose track of the node and throw 'NotFoundError'.
      // Instead, we just ensure the parent is positioned and append the button.
      parent.classList.add('pw-toggle-parent')
      input.classList.add('pw-toggle-input')

      const btn = document.createElement('button')
      btn.type = 'button'
      btn.className = 'pw-toggle-btn'
      btn.setAttribute('aria-label', 'Toggle password visibility')
      btn.innerHTML = eyeOpenSVG

      let visible = false
      btn.addEventListener('click', (e) => {
        e.preventDefault()
        e.stopPropagation()
        visible = !visible
        input.type = visible ? 'text' : 'password'
        btn.innerHTML = visible ? eyeClosedSVG : eyeOpenSVG
      })

      parent.appendChild(btn)
    }

    function scanForPasswordFields() {
      const inputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]')
      inputs.forEach(addToggle)
    }

    // Initial scan
    scanForPasswordFields()

    // Watch for dynamically added password fields
    const observer = new MutationObserver(() => {
      scanForPasswordFields()
    })

    observer.observe(document.body, {
      childList: true,
      subtree: true,
    })

    // ─── REDIRECT TO LOGIN AFTER RESET PASSWORD (CLEAN FIX) ────────────
    // Payload's ResetPasswordForm calls `fetchFullUser` after a successful reset.
    // We intercept `window.fetch`. When the reset succeeds, we quietly log the
    // user out in the background (to clear HTTP-only cookies). Then, when
    // `fetchFullUser` inevitably calls `/api/users/me`, we mock a 401 Unauthorized
    // response. Payload's organic code handles this by cleanly redirecting
    // to the login page without any flashing.

    const originalFetch = window.fetch
    window.fetch = async function (...args) {
      const [input, init] = args
      const url =
        typeof input === 'string'
          ? input
          : input instanceof URL
            ? input.toString()
            : (input as Request).url

      const method =
        init?.method?.toUpperCase() || (input instanceof Request ? input.method : 'GET')

      if (url.includes('/users/reset-password') && method === 'POST') {
        const response = await originalFetch.apply(this, args)

        if (response.ok) {
          sessionStorage.setItem('payload-password-reset', 'true')
          originalFetch('/api/users/logout', { method: 'POST', credentials: 'include' }).catch(
            () => {},
          )
          window.location.assign('/admin')
        }

        return response
      }

      if (url.includes('/users/me') && sessionStorage.getItem('payload-password-reset') === 'true') {
        sessionStorage.removeItem('payload-password-reset')

        return new Response(JSON.stringify({ user: null }), {
          status: 401,
          headers: { 'Content-Type': 'application/json' },
        })
      }

      return originalFetch.apply(this, args)
    }

    return () => {
      observer.disconnect()
      window.fetch = originalFetch
    }
  }, [])


  return <>{children}</>
}

export default PasswordToggleProvider
