import { useToastController } from '@tamagui/toast'
import { useMemo, useState } from 'react'
import type { MenuIntent, MenuOverflowItemIntent } from '../intents'
import { MenuOverflowButton } from '../MenuBar'
import { ConfirmDialog } from '../overlays/ConfirmDialog'

// renderMenu — overflow trigger. Wraps each item so confirm: triggers a
// shared AlertDialog and feedback: flows into the toast controller.

export function RenderMenu({
  intent,
  reduceMotion,
  boldText,
}: {
  intent: MenuIntent
  reduceMotion?: boolean
  boldText?: boolean
}) {
  const toast = useToastController()
  const [confirming, setConfirming] = useState<MenuOverflowItemIntent | null>(null)

  const run = async (item: MenuOverflowItemIntent) => {
    try {
      await Promise.resolve(item.onPress())
      if (item.feedback?.success) toast.show(item.feedback.success, { preset: 'success' })
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err)
      toast.show(item.feedback?.error ?? msg, { preset: 'error' })
    }
  }

  // Map to the legacy MenuOverflow item shape consumed by MenuOverflowButton.
  const items = useMemo(
    () =>
      intent.items.map((item) => ({
        label: item.label,
        icon: item.icon,
        destructive: item.destructive,
        disabled: item.disabled,
        isOn: item.toggled,
        onPress: () => {
          if (item.confirm) {
            setConfirming(item)
            return
          }
          void run(item)
        },
      })),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [intent.items]
  )

  return (
    <>
      <MenuOverflowButton
        overflow={{
          accessibilityLabel: intent.accessibilityLabel ?? 'More actions',
          items,
        }}
        reduceMotion={reduceMotion}
        boldText={boldText}
      />
      <ConfirmDialog
        open={!!confirming}
        onOpenChange={(open) => {
          if (!open) setConfirming(null)
        }}
        title={confirming?.confirmTitle ?? confirming?.label ?? ''}
        message={confirming?.confirm ?? ''}
        confirmLabel={confirming?.confirmLabel ?? confirming?.label ?? 'OK'}
        destructive={confirming?.destructive}
        onConfirm={() => {
          if (confirming) void run(confirming)
        }}
      />
    </>
  )
}
