import { type MouseEventHandler, type ReactElement, cloneElement, useEffect, useState } from 'react'
import { useIsClient } from 'usehooks-ts'

import {
  type FeedbackContext,
  type FeedbackFormPayload,
  type FeedbackUser,
  type FeedbackWidgetPayload,
  buildFeedbackContext,
} from './collect-feedback-context'
import { FeedbackWidgetModal } from './FeedbackWidgetModal'
import {
  FeedbackNeedsAuthError,
  OLY_DASHBOARD_ORIGIN,
  buildFeedbackLoginUrl,
  clearFeedbackReturnMarker,
  hasFeedbackReturnMarker,
  submitFeedbackViaGateway,
  useFeedbackGatewaySession,
} from './gateway'

export type { FeedbackContext, FeedbackFormPayload, FeedbackUser, FeedbackWidgetPayload }
export type { AgentDomPayload } from '../ElementComment/element-dom-context'
export type { FeedbackWidgetFormProps, FeedbackWidgetFormRenderProps } from './FeedbackWidgetForm'
export type { FeedbackWidgetModalProps } from './FeedbackWidgetModal'

export {
  buildFeedbackContext,
  describeFeedbackPayload,
  snapshotLocalStorage,
} from './collect-feedback-context'
export { FeedbackWidgetForm } from './FeedbackWidgetForm'
export { FeedbackWidgetModal } from './FeedbackWidgetModal'
export {
  FeedbackGatewayWidget,
  FEEDBACK_GATEWAY_DEV_FLAG,
  buildLocalDevGatewayLoginHref,
  buildPiLocalGatewayLoginHref,
  isFeedbackGatewayVisible,
  LOCAL_OLY_GATEWAY_ORIGIN,
  registerFeedbackGatewayApp,
  resolveFeedbackGatewayConfig,
} from './gateway'
export type { FeedbackGatewayWidgetProps } from './gateway/FeedbackGatewayWidget'

export type FeedbackTriggerElement = ReactElement<{
  onClick?: MouseEventHandler<HTMLElement>
}>

export interface FeedbackWidgetProps {
  /**
   * Optional override for Storybook, localhost, or emergency host routing. When omitted, the widget
   * checks session and posts to the shared Oly dashboard gateway with cookie-only credentials.
   */
  onSubmit?: (payload: FeedbackWidgetPayload) => Promise<void>
  /** Short app id included in the payload (for example `pi` or `oly`). */
  app: string
  /** Deployment environment included in the payload (for example `development`). */
  environment: string
  /** Signed-in user who captured the feedback (host override mode only). */
  user?: FeedbackUser
  /**
   * Control that opens the modal. Required — the widget does not paint its own button. Mount the
   * widget in the app shell (above in-app navigation) and pass the nav item, menu row, or other
   * control that should open it. The element should be a button (or spread props onto one); an
   * existing `onClick` still runs.
   *
   * Screen recording captures this tab and follows client-side page changes only while this
   * component stays mounted. A full document unload ends the recording.
   */
  trigger: FeedbackTriggerElement
  /** Open the modal on first render (Storybook). */
  defaultOpen?: boolean
  /** Show the sent confirmation on first render (Storybook). */
  defaultSent?: boolean
  /** Seed screenshots (Storybook). */
  initialScreenshots?: File[]
  /** Seed the description field (Storybook). */
  initialMessage?: string
  /** Seed the in-progress screen-recording bar (Storybook). */
  defaultScreenRecording?: boolean
  /**
   * Dashboard gateway origin for session/submit API calls. Defaults to `https://oly.pattern.com`.
   * Pi local dev uses same-origin (`http://pi.localhost:3000`) with a server proxy.
   */
  gatewayOrigin?: string
  /**
   * Origin for `/feedback-auth` login bounces. Defaults to `gatewayOrigin`. Set to
   * `http://oly.localhost:8282` when `gatewayOrigin` is a Pi dev proxy.
   */
  gatewayAuthOrigin?: string
  /**
   * Override login navigation. Pi local dev should send users to the host `/login` route because
   * the session proxy forwards the host Global Token cookie.
   */
  getGatewayLoginHref?: () => string | null
  /** Optional test id rendered as the `qa-test-id` attribute for QA testing */
  qaTestId?: string
}

export function FeedbackWidget({
  onSubmit,
  app,
  environment,
  user,
  trigger,
  defaultOpen = false,
  defaultSent = false,
  initialScreenshots = [],
  initialMessage = '',
  defaultScreenRecording = false,
  gatewayOrigin = OLY_DASHBOARD_ORIGIN,
  gatewayAuthOrigin,
  getGatewayLoginHref,
  qaTestId = 'feedback-widget',
}: FeedbackWidgetProps) {
  const authOrigin = gatewayAuthOrigin ?? gatewayOrigin
  const isClient = useIsClient()
  const [open, setOpen] = useState(defaultOpen)
  const [captureActive, setCaptureActive] = useState(defaultScreenRecording)
  const usesGateway = onSubmit == null
  const returnToHref = isClient ? window.location.href : undefined
  const gatewaySession = useFeedbackGatewaySession({
    enabled: usesGateway,
    open,
    returnToHref,
    gatewayOrigin,
    gatewayAuthOrigin: authOrigin,
    getGatewayLoginHref,
  })

  useEffect(() => {
    if (!isClient || !usesGateway) return
    if (!hasFeedbackReturnMarker(window.location.href)) return
    const nextHref = clearFeedbackReturnMarker(window.location.href)
    window.history.replaceState(null, '', nextHref)
    setOpen(true)
  }, [isClient, usesGateway])

  async function submitPayload(form: FeedbackFormPayload) {
    const payload = {
      ...form,
      context: buildFeedbackContext({
        app,
        environment,
        user: usesGateway ? undefined : user,
      }),
    }

    if (onSubmit) {
      await onSubmit(payload)
      return
    }

    try {
      await submitFeedbackViaGateway(payload, { dashboardOrigin: gatewayOrigin })
    } catch (error) {
      if (error instanceof FeedbackNeedsAuthError && returnToHref) {
        const hostLoginHref = getGatewayLoginHref?.()
        if (hostLoginHref) {
          window.location.assign(hostLoginHref)
          return
        }
        const loginUrl = buildFeedbackLoginUrl(error.authUrl, returnToHref, authOrigin)
        if (loginUrl) {
          window.location.assign(loginUrl)
          return
        }
      }
      throw error
    }
  }

  const modal = (
    <FeedbackWidgetModal
      open={open}
      onOpenChange={setOpen}
      onSubmit={submitPayload}
      initialScreenshots={initialScreenshots}
      initialMessage={initialMessage}
      defaultSent={defaultSent}
      defaultScreenRecording={defaultScreenRecording}
      onCaptureActiveChange={setCaptureActive}
      gatewaySession={gatewaySession}
      draftStorageKey={usesGateway ? app : undefined}
      allowMediaAttachments={!usesGateway}
      qaTestId={`${qaTestId}-modal`}
    />
  )

  return (
    <div qa-test-id={qaTestId}>
      {captureActive
        ? null
        : cloneElement(trigger, {
            onClick: (event) => {
              trigger.props.onClick?.(event)
              if (!event.defaultPrevented) setOpen(true)
            },
          })}
      {modal}
    </div>
  )
}
