import Feather from '@expo/vector-icons/Feather'
import { Pressable } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { openSystemSettings, type PermissionKind } from 'src/lib/media'
import { Button, Text, useTheme, YStack } from 'tamagui'

type Props = {
  kind: PermissionKind
  /** Called when the user taps "Try again" — typically a hook-returned request fn. */
  onRetry?: () => void
  /** Called when the user dismisses the screen (e.g. close the camera). */
  onCancel?: () => void
  /** Override the title / body when a screen wants specific copy. */
  title?: string
  body?: string
  /** Dark backdrop variant used by full-bleed camera screens. */
  dark?: boolean
}

const ICON: Record<PermissionKind, string> = {
  camera: 'camera-off',
  microphone: 'mic-off',
  mediaLibrary: 'image',
}

const DEFAULT_COPY: Record<PermissionKind, { title: string; body: string }> = {
  camera: {
    title: 'Camera access is off',
    body: 'Grant camera access to take photos and videos.',
  },
  microphone: {
    title: 'Microphone access is off',
    body: 'Grant microphone access to record video with sound.',
  },
  mediaLibrary: {
    title: 'Photo access is off',
    body: 'Grant photo-library access to pick images and videos.',
  },
}

export function PermissionDeniedScreen({
  kind,
  onRetry,
  onCancel,
  title,
  body,
  dark = false,
}: Props) {
  const theme = useTheme()
  const bg = dark ? '#000' : theme.background.val
  const fg = dark ? 'white' : theme.color.val
  const muted = dark ? 'rgba(255,255,255,0.7)' : theme.colorSecondary.val
  const copy = DEFAULT_COPY[kind]
  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: bg }} edges={['top', 'bottom']}>
      <YStack flex={1} alignItems="center" justifyContent="center" gap="$4" p="$6">
        <Feather name={ICON[kind] as any} size={48} color={fg} />
        <Text color={fg} fontSize="$6" fontWeight="700" textAlign="center">
          {title ?? copy.title}
        </Text>
        <Text color={muted} textAlign="center">
          {body ?? copy.body}
        </Text>
        {onRetry ? (
          <Button size="$4" onPress={onRetry}>
            <Text>Try again</Text>
          </Button>
        ) : null}
        <Button size="$4" chromeless onPress={openSystemSettings}>
          <Text color={fg}>Open Settings</Text>
        </Button>
        {onCancel ? (
          <Pressable onPress={onCancel} hitSlop={12}>
            <Text color={muted}>Cancel</Text>
          </Pressable>
        ) : null}
      </YStack>
    </SafeAreaView>
  )
}
