import Feather from '@expo/vector-icons/Feather'
import {
  BottomSheetBackdrop,
  type BottomSheetModal,
  BottomSheetView,
} from '@gorhom/bottom-sheet'
import { forwardRef, useCallback } from 'react'
import { Pressable } from 'react-native'
import { PixelfedBottomSheetModal } from 'src/components/common/BottomSheets'
import { useStoredTheme } from 'src/hooks/useStoredTheme'
import {
  ACCENT_VARIANT_IDS,
  ACCENT_VARIANTS,
  type AccentVariantId,
} from 'src/lib/accentVariants'
import { AccountStore } from 'src/state/accountStore'
import { Text, useTheme, View, XStack, YStack } from 'tamagui'

const SWATCH_SIZE = 44

type Props = {
  accountId: string | null
  selected: AccentVariantId
}

// Bottom-sheet picker for the active account's accent variant. Renders the
// 8 hues in a 4×2 grid (44pt circles), reading the design-time hex from
// `ACCENT_VARIANTS` rather than a separate token table — there's no runtime
// indirection because the swatch hex IS the source of truth the sub-themes
// were built from. The currently-selected swatch carries a check glyph;
// tapping any swatch persists the choice via `setAccentVariant` and dismisses.
export const AccentPicker = forwardRef<BottomSheetModal, Props>(function AccentPicker(
  { accountId, selected },
  ref
) {
  const theme = useTheme()
  const scheme = useStoredTheme()

  const renderBackdrop = useCallback(
    (props: any) => (
      <BottomSheetBackdrop {...props} disappearsOnIndex={-1} appearsOnIndex={0} />
    ),
    []
  )

  const onPick = (n: AccentVariantId) => {
    if (!accountId) return
    AccountStore.setAccentVariant(accountId, n)
    if (ref && typeof ref === 'object' && 'current' in ref && ref.current?.dismiss) {
      ref.current.dismiss()
    }
  }

  return (
    <PixelfedBottomSheetModal
      ref={ref}
      enableDynamicSizing
      backdropComponent={renderBackdrop}
      backgroundStyle={{ backgroundColor: theme.background.val }}
      handleIndicatorStyle={{ backgroundColor: theme.backgroundTertiary.val }}
    >
      <BottomSheetView
        style={{ paddingHorizontal: 16, paddingTop: 8, paddingBottom: 28 }}
      >
        <YStack gap="$3" pb="$3">
          <Text
            fontSize="$6"
            fontWeight="700"
            color={theme.color.val}
            paddingHorizontal={4}
          >
            Accent colour
          </Text>
          <Text fontSize="$3" color={theme.colorSecondary.val} paddingHorizontal={4}>
            Pick a hue for this account. Tab pills, the like heart, and the camera button
            all switch to match.
          </Text>
        </YStack>
        <XStack flexWrap="wrap" rowGap={16} columnGap={8} justifyContent="space-between">
          {ACCENT_VARIANT_IDS.map((n) => {
            const v = ACCENT_VARIANTS[n]
            const hex = scheme === 'light' ? v.light : v.dark
            const onAccent = scheme === 'light' ? v.onAccent : v.onAccentDark
            const isSelected = n === selected
            return (
              <Pressable
                key={n}
                onPress={() => onPick(n)}
                accessibilityRole="button"
                accessibilityLabel={v.name}
                accessibilityState={{ selected: isSelected }}
                style={({ pressed }) => ({
                  width: '23%',
                  alignItems: 'center',
                  opacity: pressed ? 0.7 : 1,
                })}
              >
                <View
                  width={SWATCH_SIZE}
                  height={SWATCH_SIZE}
                  borderRadius={SWATCH_SIZE / 2}
                  backgroundColor={hex}
                  alignItems="center"
                  justifyContent="center"
                  borderWidth={isSelected ? 2 : 0}
                  borderColor={theme.color.val}
                >
                  {isSelected ? (
                    <Feather name="check" size={20} color={onAccent} />
                  ) : null}
                </View>
                <Text
                  fontSize={11}
                  fontWeight="600"
                  color={theme.colorSecondary.val}
                  marginTop={6}
                  numberOfLines={1}
                  textAlign="center"
                  allowFontScaling={false}
                >
                  {v.name}
                </Text>
              </Pressable>
            )
          })}
        </XStack>
      </BottomSheetView>
    </PixelfedBottomSheetModal>
  )
})
