import type { ErrorBoundaryProps } from 'expo-router'
import { useLocalSearchParams } from 'expo-router'
import { ActivityIndicator, Keyboard, Platform } from 'react-native'
import { ErrorState } from 'src/components/common/ErrorState'
import { PressableOpacity } from 'src/components/common/PressableOpacity'
import UserAvatar from 'src/components/common/UserAvatar'
import { Switch } from 'src/components/form/Switch'
import { ScreenScrollContainer } from 'src/components/layout'
import { EditMediaAltCard } from 'src/components/post/edit/EditMediaAltCard'
import { Card, FieldHelperText, FieldTitle } from 'src/components/ui'
import { usePostEdit } from 'src/hooks/usePostEdit'
import { useActiveProfile } from 'src/state/AuthProvider'
import { Text, TextArea, useTheme, View, XStack, YStack } from 'tamagui'

export function ErrorBoundary({ error, retry }: ErrorBoundaryProps) {
  return <ErrorState message={error.message} onRetry={retry} />
}

export default function Page() {
  const { id } = useLocalSearchParams<{ id: string }>()
  const theme = useTheme()
  const { profile: user } = useActiveProfile()
  const edit = usePostEdit(id)

  if (edit.isPending || edit.isLoading) {
    return (
      <View flexGrow={1} mt="$5">
        <ActivityIndicator color={theme.color.val} />
      </View>
    )
  }

  if (edit.isError) {
    return <Text>Error: {edit.error?.message}</Text>
  }

  return (
    <ScreenScrollContainer variant="scroll" header="Edit Post">
      <View onTouchStart={() => Keyboard.dismiss()}>
        <YStack p="$3" gap="$3">
          <XStack gap="$3" justifyContent="space-between" alignItems="center">
            <XStack gap="$3" alignItems="center">
              <UserAvatar url={user?.avatar} size="sm" />
              <Text
                fontSize={Platform.OS === 'ios' ? '$7' : '$5'}
                fontWeight="bold"
                color={theme.color.val}
              >
                {user?.username}
              </Text>
            </XStack>
            <Text color={theme.colorTertiary.val}>
              {edit.caption ? edit.caption.length : '0'}/{edit.maxCharacters}
            </Text>
          </XStack>

          <TextArea
            size="$4"
            fontSize={Platform.OS === 'ios' ? '$7' : '$5'}
            borderWidth={1}
            borderColor={theme.borderColor.val}
            color={theme.color.val}
            defaultValue={edit.caption}
            onChangeText={edit.setCaption}
            maxLength={edit.maxCharacters}
            backgroundColor={theme.backgroundTertiary.val}
            numberOfLines={4}
            textAlignVertical="top"
            rows={4}
            multiline={true}
            placeholder="Share your moment..."
            placeholderTextColor="$colorTertiary"
          />

          <Card flexDirection="row" justifyContent="space-between">
            <YStack maxWidth="70%" gap="$2">
              <FieldTitle fontSize="$4">Contains Sensitive Media</FieldTitle>
              <FieldHelperText>Applies a sensitive content warning.</FieldHelperText>
            </YStack>

            <Switch
              size="$3"
              checked={edit.isSensitive}
              onCheckedChange={(checked) =>
                !edit.post?.sensitive ? edit.setSensitive(checked) : null
              }
            >
              <Switch.Thumb transition="quicker" />
            </Switch>
          </Card>

          {edit.isSensitive ? (
            edit.showSpoiler ? (
              <YStack gap="$1">
                <XStack justifyContent="space-between" alignItems="center" px="$3">
                  <Text alignSelf="center" allowFontScaling={false} fontWeight={'bold'}>
                    Custom content warning
                  </Text>
                  <PressableOpacity onPress={() => edit.setShowSpoiler(false)}>
                    <Text color="$gray9" allowFontScaling={false}>
                      Hide
                    </Text>
                  </PressableOpacity>
                </XStack>
                <TextArea
                  size="$4"
                  fontSize={Platform.OS === 'ios' ? '$7' : '$5'}
                  borderWidth={1}
                  defaultValue={edit.spoilerText}
                  onChangeText={edit.setSpoilerText}
                  maxLength={140}
                  backgroundColor={theme.background.val}
                  numberOfLines={4}
                  textAlignVertical="top"
                  multiline={true}
                  placeholder="Set an optional spoiler content warning"
                  placeholderTextColor="$colorTertiary"
                />
                <XStack justifyContent="flex-end" alignItems="center">
                  <Text color="$gray9">
                    {edit.spoilerText && edit.spoilerText.length
                      ? edit.spoilerText.length
                      : '0'}
                    /140
                  </Text>
                </XStack>
              </YStack>
            ) : (
              <PressableOpacity onPress={() => edit.setShowSpoiler(true)}>
                <Text pl="$3" allowFontScaling={false} fontWeight={'bold'}>
                  Edit custom content warning
                </Text>
              </PressableOpacity>
            )
          ) : null}
        </YStack>

        <YStack>
          {edit.media.map((item) => (
            <EditMediaAltCard
              key={`pe-media-${item.id}`}
              item={item}
              onChange={edit.updateMediaAlt}
            />
          ))}
        </YStack>
        <View h={200} />
      </View>
    </ScreenScrollContainer>
  )
}
