import { useLingui } from '@lingui/react/macro'
import { type ReactNode, createContext, useContext, useEffect, useRef, useState } from 'react'
import { useIsClient } from 'usehooks-ts'

import { HelperText } from '../../Fields/HelperText/HelperText'
import { Modal } from '../../Modal/Modal'
import { ShakeWrapper } from '../../ShakeWrapper/ShakeWrapper'
import { TooltipProvider } from '../../Tooltip/Tooltip'
import {
  type FeedbackFormPayload,
  type FeedbackUser,
  buildFeedbackContext,
} from '../collect-feedback-context'
import {
  FeedbackMode,
  type FeedbackModePhase,
  type FeedbackModeProps,
  type FeedbackModeRenderProps,
} from '../FeedbackMode'
import { FeedbackNeedsAuthError, checkFeedbackSession, submitFeedbackViaGateway } from './client'
import { FEEDBACK_GATEWAY_DEV_FLAG } from './config'
import { readFeedbackDraftMessage, writeFeedbackDraftMessage } from './draft-storage'
import { irisEnvironment } from './iris-payload'
import { isFeedbackGatewayVisible, isLocalHostname, registerFeedbackGatewayApp } from './runtime'
import { type FeedbackGatewayAuth, useFeedbackGatewayAuth } from './useFeedbackGatewayAuth'

/** Path the host's local dev proxy serves to name the Oly origin it forwards to. */
const LOCAL_OLY_ORIGIN_PATH = '/api/feedback/oly-origin'

export type FeedbackGatewayContextValue = {
  /** Whether feedback is available (host toggle, or the dev opt-in flag). */
  enabled: boolean
  /** Start a feedback session. Wire this to a "Send feedback" menu item, command, or shortcut. */
  openFeedback: () => void
}

const FeedbackGatewayContext = createContext<FeedbackGatewayContextValue | undefined>(undefined)

export interface FeedbackGatewayProviderProps {
  /** App id stamped on the report (`toggle`, `oly`, …). Also keys the saved draft. */
  app: string
  /** Host feature toggle. The dev opt-in flag (`pattern-feedback-gateway-dev`) also enables it. */
  enabled: boolean
  /** Deployment environment label (`development`, `stage`, `staging`, `production`). */
  environment: string
  /** Signed-in user, for the report context. Oly still identifies the requester from its cookie. */
  user?: FeedbackUser
  /**
   * The host serves a same-origin dev proxy on localhost for `/api/feedback*`,
   * `/api/artifacts/upload`, and `/api/feedback/oly-origin` (Toggle's Vite plugin, Pi's server).
   * Leave off for apps that only run on `*.pattern.com`.
   */
  usesLocalDevProxy?: boolean
  /**
   * Fired once when a capture session opens. Pass Pi's call: `(mode) =>
   * mode.startMode('screenshot')`.
   */
  onCaptureReady?: FeedbackModeProps['onCaptureReady']
  children: ReactNode
  /**
   * Base `qa-test-id` for the feedback UI this provider renders: the capture UI gets `qaTestId`,
   * the review body `${qaTestId}-review`, and the review Modal `${qaTestId}-review-dialog`. The
   * provider itself renders no DOM of its own.
   */
  qaTestId?: string
}

/**
 * Drop-in in-app feedback for any Pattern app that sends reports through the Oly gateway.
 *
 * Owns the whole session: availability, an Oly session check before capture (so a Login bounce can
 * never throw away screenshots or recordings), the capture UI ({@link FeedbackMode}), a default
 * review dialog with Login / Send, draft persistence across the bounce, and upload + submit via
 * {@link submitFeedbackViaGateway}. Hosts wrap their app and call `openFeedback()` from
 * {@link useFeedbackGateway}.
 *
 * Local dev on `<app>.localhost` needs a same-origin proxy: Vite SPAs add
 * `feedbackGatewayDevProxyPlugin` from `lib/pattern-ui/feedback-gateway-dev-proxy-plugin.ts` and
 * pass `usesLocalDevProxy`.
 */
export function FeedbackGatewayProvider({
  app,
  enabled: hostEnabled,
  environment,
  user,
  usesLocalDevProxy = false,
  onCaptureReady,
  children,
  qaTestId = 'feedback-gateway-provider',
}: FeedbackGatewayProviderProps) {
  const isClient = useIsClient()
  const [active, setActive] = useState(false)
  // Remounts FeedbackMode per session so the next one starts clean with the saved draft.
  const [sessionKey, setSessionKey] = useState(0)
  const [initialMessage, setInitialMessage] = useState('')
  const [initialPhase, setInitialPhase] = useState<FeedbackModePhase>('capture')
  const [reviewOpen, setReviewOpen] = useState(false)

  // Idempotent: the gateway runtime reads this profile to route local Login through `dev-bind`.
  if (usesLocalDevProxy) registerFeedbackGatewayApp(app, { usesLocalDevProxy: true })

  let devOptIn = false
  if (isClient) {
    try {
      devOptIn = window.localStorage.getItem(FEEDBACK_GATEWAY_DEV_FLAG) === 'true'
    } catch {
      devOptIn = false
    }
  }
  const enabled = isFeedbackGatewayVisible(hostEnabled, devOptIn)
  const sessionActive = enabled && active

  const gatewayAuthRef = useRef<FeedbackGatewayAuth | null>(null)
  const openRef = useRef<() => void>(() => {})
  // Set for the whole session, including the auth check before `active` flips. A second
  // `openFeedback` (the shortcut, or the menu) would otherwise remount and drop captures.
  const sessionOpenRef = useRef(false)

  const resolveLocalOlyOrigin =
    usesLocalDevProxy && isClient && isLocalHostname(window.location.hostname)
      ? async () => {
          const response = await fetch(LOCAL_OLY_ORIGIN_PATH, { credentials: 'same-origin' })
          if (!response.ok) throw new Error('oly-origin unavailable')
          const body = (await response.json()) as { origin?: string }
          if (!body.origin) throw new Error('oly-origin missing')
          return body.origin
        }
      : undefined

  const gatewayAuth = useFeedbackGatewayAuth({
    app,
    enabled,
    open: sessionActive && reviewOpen,
    resolveOlyGatewayOrigin: resolveLocalOlyOrigin,
    onReturnFromAuth: () => {
      openRef.current()
    },
  })
  gatewayAuthRef.current = gatewayAuth

  function startSession(options?: { review?: boolean }) {
    setInitialMessage(readFeedbackDraftMessage(app))
    setInitialPhase(options?.review ? 'review' : 'capture')
    setSessionKey((key) => key + 1)
    sessionOpenRef.current = true
    setActive(true)
  }

  function openFeedback() {
    if (!enabled || sessionOpenRef.current) return
    sessionOpenRef.current = true
    const gateway = gatewayAuthRef.current
    if (!gateway) {
      startSession()
      return
    }
    void (async () => {
      try {
        const result = await checkFeedbackSession({ dashboardOrigin: gateway.config.gatewayOrigin })
        if (result.status === 'needs_auth') {
          sessionOpenRef.current = false
          gateway.redirectToLogin(new FeedbackNeedsAuthError(result.authUrl))
          return
        }
        // Forbidden / session error: open review only so authNotice surfaces without wasting
        // captures the user could never send.
        if (result.status === 'forbidden' || result.status === 'error') {
          startSession({ review: true })
          return
        }
        startSession()
      } catch {
        sessionOpenRef.current = false
        gateway.redirectToLogin()
      }
    })()
  }
  openRef.current = openFeedback

  async function onSubmit(form: FeedbackFormPayload) {
    const gateway = gatewayAuthRef.current
    if (!gateway) throw new Error('Feedback gateway auth is not ready.')
    writeFeedbackDraftMessage(app, form.message)
    try {
      await submitFeedbackViaGateway(
        {
          ...form,
          context: buildFeedbackContext({
            app,
            environment: irisEnvironment(environment),
            user,
            localStorage: {},
          }),
        },
        { dashboardOrigin: gateway.config.gatewayOrigin },
      )
      writeFeedbackDraftMessage(app, '')
    } catch (error) {
      if (error instanceof FeedbackNeedsAuthError) gateway.redirectToLogin(error)
      throw error
    }
  }

  return (
    <FeedbackGatewayContext.Provider value={{ enabled, openFeedback }}>
      {children}
      {sessionActive ? (
        // Capture bar and review use Tooltips; not every host shell mounts a TooltipProvider.
        <TooltipProvider>
          <FeedbackMode
            key={sessionKey}
            active
            initialPhase={initialPhase}
            initialMessage={initialMessage}
            onCaptureReady={onCaptureReady}
            onExit={() => {
              sessionOpenRef.current = false
              setActive(false)
            }}
            onSubmit={onSubmit}
            renderReview={(review) => (
              <FeedbackGatewayReview
                app={app}
                review={review}
                gatewayAuth={gatewayAuth}
                onOpenChange={setReviewOpen}
                qaTestId={`${qaTestId}-review-dialog`}
              />
            )}
            qaTestId={qaTestId}
          />
        </TooltipProvider>
      ) : null}
    </FeedbackGatewayContext.Provider>
  )
}

function FeedbackGatewayReview({
  app,
  review,
  gatewayAuth,
  onOpenChange,
  qaTestId,
}: {
  app: string
  review: FeedbackModeRenderProps
  gatewayAuth: FeedbackGatewayAuth
  onOpenChange: (open: boolean) => void
  qaTestId: string
}) {
  const { t } = useLingui()

  // The session check runs only while this step is on screen — never during capture.
  useEffect(() => {
    onOpenChange(true)
    return () => onOpenChange(false)
  }, [onOpenChange])

  const didSend = review.phase === 'sent'

  return (
    <Modal
      open
      dismissOnBackdropClick={false}
      onOpenChange={(next) => {
        if (!next) review.exit()
      }}
      size='lg'
      qaTestId={qaTestId}
      headerProps={
        didSend
          ? { title: t`Feedback sent` }
          : {
              title: t`Send feedback`,
              description: t`Describe what you noticed. Your captures are attached below.`,
              showClose: true,
              closeDisabled: review.isSubmitting,
            }
      }
      footerProps={
        didSend
          ? { primaryButton: { variant: 'strong', children: t`Close`, onClick: review.exit } }
          : {
              secondaryButton: {
                variant: 'weak',
                children: t`Back to capture`,
                disabled: review.isSubmitting,
                onClick: review.backToCapture,
              },
              primaryButton: gatewayAuth.needsLogin
                ? {
                    variant: 'strong',
                    children: t`Login`,
                    disabled: review.isSubmitting,
                    onClick: () => {
                      if (review.message.trim()) writeFeedbackDraftMessage(app, review.message)
                      gatewayAuth.onLogin()
                    },
                  }
                : {
                    variant: 'strong',
                    children: t`Send`,
                    isLoading: review.isSubmitting || gatewayAuth.isChecking,
                    disabled: !gatewayAuth.canSend || review.isSubmitting,
                    onClick: review.submit,
                  },
            }
      }
    >
      <ShakeWrapper
        ref={review.shakeRef}
        tooltip={didSend ? undefined : t`Fill out the required field before sending.`}
      >
        {review.body}
        {!didSend && gatewayAuth.authNotice ? (
          <HelperText state='error' wrap className='mt-3'>
            {gatewayAuth.authNotice}
          </HelperText>
        ) : null}
      </ShakeWrapper>
    </Modal>
  )
}

/**
 * `enabled` + `openFeedback()` from the nearest {@link FeedbackGatewayProvider}. Outside a provider
 * it returns a disabled no-op, so shared nav/menu code can call it unconditionally.
 */
export function useFeedbackGateway(): FeedbackGatewayContextValue {
  return useContext(FeedbackGatewayContext) ?? { enabled: false, openFeedback: () => {} }
}
