import { Feather } from '@expo/vector-icons'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Image } from 'expo-image'
import { useRouter } from 'expo-router'
import React, { useEffect, useState } from 'react'
import { Platform, Pressable } from 'react-native'
import { useConfirmDialog } from 'src/hooks/useConfirmDialog'
import { postStorySelfExpire } from 'src/lib/api'
import { ICON } from 'src/lib/icons'
import { storyQueries } from 'src/lib/queries/stories'
import { appStorage, uiKeys } from 'src/state/storage'
import { timeAgo } from 'src/utils'
import {
  Button,
  Circle,
  H2,
  H3,
  Paragraph,
  ScrollView,
  Separator,
  Sheet,
  Text,
  useTheme,
  XStack,
  YStack,
} from 'tamagui'
import StoriesExplanation from './StoriesExplanation'

const ONBOARDING_COMPLETED_KEY = uiKeys.storiesOnboardingCompleted
const STORIES_DISABLED_KEY = uiKeys.hideStories

interface Story {
  id: string
  url: string
  created_at: string
  viewed: boolean
  view_count: number
}

interface SelfAvatarModalProps {
  isOpen: boolean
  stories: Story[]
  onClose: () => void
  userAvatar: string
  username: string
  onAddStory: () => void
  onViewStories: () => void
  onDisableStories?: () => void
}

const FeatureCard: React.FC<{
  icon: string
  title: string
  description: string
  theme: any
}> = ({ icon, title, description, theme }) => (
  <YStack
    padding={20}
    backgroundColor={theme.backgroundSecondary.val}
    borderRadius={16}
    borderWidth={1}
    borderColor={theme.borderColor.val}
    gap={12}
    alignItems="center"
  >
    <Circle
      size={60}
      backgroundColor={theme.backgroundTertiary.val}
      alignItems="center"
      justifyContent="center"
    >
      <Feather name={icon as any} size={ICON.lg} color={theme.color.val} />
    </Circle>
    <H3 color={theme.color.val} textAlign="center" fontWeight="600">
      {title}
    </H3>
    <Paragraph
      color={theme.colorSecondary.val}
      textAlign="center"
      fontSize={14}
      lineHeight={20}
    >
      {description}
    </Paragraph>
  </YStack>
)

const OnboardingScreen: React.FC<{
  onGetStarted: () => void
  onDisable: () => void
  theme: any
  username: string
}> = ({ onGetStarted, onDisable, theme, username: _username }) => (
  <YStack flex={1} paddingHorizontal={20}>
    <YStack alignItems="center" paddingTop={20} paddingBottom={30}>
      <Circle
        size={80}
        backgroundColor={theme.backgroundTertiary.val}
        alignItems="center"
        justifyContent="center"
        marginBottom={20}
      >
        <Feather name="clock" size={ICON.xl} color={theme.color.val} />
      </Circle>

      <H2 color={theme.color.val} textAlign="center" fontWeight="700" marginBottom={8}>
        Welcome to Stories!
      </H2>

      <Paragraph
        color={theme.colorSecondary.val}
        textAlign="center"
        fontSize={16}
        lineHeight={22}
        paddingHorizontal={20}
      >
        Share moments that disappear in 24 hours with your followers
      </Paragraph>
    </YStack>

    <ScrollView showsVerticalScrollIndicator={false} flex={1}>
      <YStack gap={16} paddingBottom={20}>
        <FeatureCard
          icon="clock"
          title="24-Hour Stories"
          description="Your stories automatically disappear after 24 hours, perfect for sharing spontaneous moments"
          theme={theme}
        />

        <FeatureCard
          icon="users"
          title="Connect with Followers"
          description="Share behind-the-scenes content and daily highlights with people who follow you"
          theme={theme}
        />

        <FeatureCard
          icon="eye-off"
          title="Casual & Private"
          description="Stories feel more relaxed than posts - share freely without worrying about your main feed"
          theme={theme}
        />
      </YStack>
    </ScrollView>

    <YStack paddingBottom={40} gap={12} paddingTop={20}>
      <Button
        size="$5"
        backgroundColor={theme.backgroundTertiary.val}
        borderRadius={25}
        onPress={onGetStarted}
        pressStyle={{ scale: 0.98 }}
      >
        <XStack alignItems="center" gap={12}>
          <Text color={theme.color.val} fontWeight="bold" fontSize={16}>
            Get Started with Stories
          </Text>
        </XStack>
      </Button>

      <Button
        size="$4"
        backgroundColor="transparent"
        borderColor={theme.borderColor.val}
        borderWidth={1}
        borderRadius={25}
        onPress={onDisable}
        pressStyle={{ scale: 0.98 }}
      >
        <XStack alignItems="center" gap={8}>
          <Text color={theme.colorSecondary.val} fontWeight="500">
            Not interested - Hide Stories
          </Text>
        </XStack>
      </Button>

      <Paragraph
        color={theme.colorTertiary.val}
        textAlign="center"
        fontSize={12}
        paddingTop={8}
      >
        You can always re-enable Stories later in the Appearance Settings
      </Paragraph>
    </YStack>
  </YStack>
)

const StackedStoriesPreview: React.FC<{
  stories: Story[]
  onTap: () => void
}> = ({ stories, onTap }) => {
  const theme = useTheme()
  const maxVisible = 4
  const visibleStories = stories.slice(0, maxVisible)

  return (
    <Pressable onPress={onTap}>
      <YStack height={220} width={140} alignItems="center" justifyContent="center">
        {visibleStories.map((story, index) => (
          <YStack
            key={story.id}
            position="absolute"
            width={140 - index * 6}
            height={200 - index * 8}
            borderRadius={12}
            backgroundColor={theme.background.val}
            borderWidth={1}
            borderColor={theme.borderColorStrong.val}
            style={{
              transform: [
                { translateX: index * 12 - 18 },
                { translateY: index * 8 - 12 },
                { rotate: `${index * 4 - 6}deg` },
              ],
              zIndex: maxVisible - index,
            }}
          >
            <Image
              source={story.url as any}
              style={{ width: '100%', height: '100%', borderRadius: 10 }}
            />
          </YStack>
        ))}
        {stories.length > maxVisible && (
          <YStack
            position="absolute"
            bottom={80}
            right={-60}
            backgroundColor={theme.background.val}
            borderRadius={20}
            paddingHorizontal={8}
            paddingVertical={4}
            borderWidth={2}
            borderColor={theme.borderColor.val}
            zIndex={10}
          >
            <Text color={theme.color.val} fontSize={12} fontWeight="bold">
              +{stories.length - maxVisible}
            </Text>
          </YStack>
        )}
      </YStack>
    </Pressable>
  )
}

const StoryListItem: React.FC<{
  story: Story
  onDelete: (id: string) => void
  onStoryViews: (id: string) => void
}> = ({ story, onDelete, onStoryViews }) => {
  const theme = useTheme()
  const sharedAgo = React.useMemo(() => {
    return timeAgo(story.created_at)
  }, [story.created_at])

  return (
    <XStack
      padding={12}
      backgroundColor={theme.backgroundSecondary.val}
      borderRadius={8}
      alignItems="center"
      gap={12}
    >
      <Image
        source={{ uri: story.url }}
        {...({ width: 60, height: 80, borderRadius: 6 } as any)}
      />

      <YStack flex={1} gap={4}>
        <XStack alignItems="center" justifyContent="space-between">
          <Text color={theme.color.val} fontSize={16} fontWeight="normal">
            Shared {sharedAgo} ago
          </Text>
          {!story.viewed && (
            <Text>
              <Circle size={8} backgroundColor={theme.background.val} />
            </Text>
          )}
        </XStack>

        <XStack alignItems="center" gap={4}>
          <Feather name="eye" size={ICON.xs} color={theme.colorTertiary.val} />
          <Text color={theme.colorTertiary.val} fontSize={12}>
            {story?.view_count || 0} views
          </Text>
        </XStack>
      </YStack>

      <XStack gap={8}>
        <Button
          size="$2"
          circular
          backgroundColor={theme.backgroundTertiary.val}
          borderColor={theme.borderColor.val}
          onPress={() => onStoryViews(story.id)}
        >
          <Text>
            <Feather name="eye" size={ICON.sm} color={theme.color.val} />
          </Text>
        </Button>
        <Button
          size="$2"
          circular
          backgroundColor={theme.backgroundTertiary.val}
          borderColor={theme.borderColor.val}
          onPress={() => onDelete(story.id)}
        >
          <Text>
            <Feather name="trash-2" size={ICON.sm} color={theme.color.val} />
          </Text>
        </Button>
      </XStack>
    </XStack>
  )
}

export const SelfAvatarModal: React.FC<SelfAvatarModalProps> = ({
  isOpen,
  stories,
  onClose,
  userAvatar: _userAvatar,
  username,
  onAddStory,
  onViewStories,
  onDisableStories,
}) => {
  const [showStoryList, setShowStoryList] = useState(false)
  const [showOnboarding, setShowOnboarding] = useState(false)
  const [_showStoryViewers, setShowStoryViewers] = useState(false)
  const [_selectedStoryId, setSelectedStoryId] = useState<string | null>(null)
  const queryClient = useQueryClient()
  const theme = useTheme()
  const router = useRouter()
  const { confirm, dialog: confirmDialog } = useConfirmDialog()

  // Check onboarding status when modal opens
  useEffect(() => {
    if (isOpen) {
      const hasCompletedOnboarding =
        appStorage.getBoolean(ONBOARDING_COMPLETED_KEY) ?? false
      const isStoriesDisabled = appStorage.getBoolean(STORIES_DISABLED_KEY) ?? false

      // Show onboarding if not completed and stories not disabled
      if (!hasCompletedOnboarding && !isStoriesDisabled) {
        setShowOnboarding(true)
      } else {
        setShowStoryList(false)
        setShowStoryViewers(false)
      }
    }
  }, [isOpen])

  const deleteStoryMutation = useMutation({
    mutationFn: postStorySelfExpire,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: storyQueries.carousel().queryKey })
    },
  })

  const hasStories = stories?.length > 0
  const hasMaxStories = stories?.length == 20

  const handleCompleteOnboarding = () => {
    appStorage.set(ONBOARDING_COMPLETED_KEY, true)
    setShowOnboarding(false)
  }

  const handleDisableStories = async () => {
    const ok = await confirm({
      title: 'Disable Stories',
      message:
        'Stories will be hidden from your interface. You can re-enable them anytime in the Appearance app settings.',
      confirmLabel: 'Disable',
      destructive: true,
    })
    if (ok) {
      appStorage.set(STORIES_DISABLED_KEY, true)
      appStorage.set(ONBOARDING_COMPLETED_KEY, true)
      onDisableStories?.()
      onClose()
      router.push('/profile')
    }
  }

  const handleAddStory = () => {
    onClose()
    onAddStory()
  }

  const handleViewStories = () => {
    onClose()
    onViewStories()
  }

  const handleDeleteStory = async (storyId: string) => {
    const ok = await confirm({
      title: 'Delete Story',
      message:
        'Are you sure you want to delete this story? This action cannot be undone.',
      confirmLabel: 'Delete',
      destructive: true,
    })
    if (ok) {
      setShowStoryList(false)
      deleteStoryMutation.mutate(storyId)
      onClose()
    }
  }

  const handleViewStoryViewers = (storyId: string) => {
    onClose()
    router.push({ pathname: '/story/viewers/[id]', params: { id: storyId } })
  }

  const _handleBackFromViewers = () => {
    setShowStoryViewers(false)
    setSelectedStoryId(null)
  }

  return (
    <Sheet
      modal
      open={isOpen}
      onOpenChange={onClose}
      snapPoints={showOnboarding ? [90] : [85]}
      dismissOnSnapToBottom={!showOnboarding}
      zIndex={100_000}
    >
      <Sheet.Overlay backgroundColor="rgba(0,0,0,0.8)" />
      <Sheet.Handle backgroundColor={theme.backgroundTertiary.val} />

      <Sheet.Frame backgroundColor={theme.background.val} padding={0}>
        {showOnboarding ? (
          <OnboardingScreen
            onGetStarted={handleCompleteOnboarding}
            onDisable={handleDisableStories}
            theme={theme}
            username={username}
          />
        ) : showStoryList ? (
          <YStack flex={1} paddingHorizontal={20}>
            <XStack alignItems="center" justifyContent="space-between" paddingTop={20}>
              <Button
                size="$3"
                circular
                backgroundColor="transparent"
                borderColor="transparent"
                onPress={() => setShowStoryList(false)}
              >
                <Feather
                  name="arrow-left"
                  size={ICON.md}
                  color={theme.colorTertiary.val}
                />
              </Button>

              <Text color={theme.color.val} fontSize={18} fontWeight="bold">
                Your Stories
              </Text>

              <YStack width={40} />
            </XStack>

            <Separator borderColor={theme.borderColor.val} my="$3" />

            <ScrollView showsVerticalScrollIndicator={false}>
              <YStack gap={12} paddingBottom={100}>
                {stories.map((story) => (
                  <StoryListItem
                    key={story.id}
                    story={story}
                    onDelete={handleDeleteStory}
                    onStoryViews={handleViewStoryViewers}
                  />
                ))}
              </YStack>
            </ScrollView>
          </YStack>
        ) : (
          <YStack flex={1} paddingHorizontal={20}>
            <XStack
              alignItems="center"
              justifyContent="space-between"
              paddingVertical={20}
            >
              <Text color={theme.color.val} fontSize={18} fontWeight="bold">
                Your Story
              </Text>

              <Button
                size="$3"
                circular
                backgroundColor="transparent"
                borderColor="transparent"
                onPress={onClose}
              >
                <Feather name="x" size={ICON.md} color={theme.color.val} />
              </Button>
            </XStack>

            <YStack flex={1} alignItems="center" justifyContent="center" gap={32}>
              {hasStories ? (
                <YStack alignItems="center" gap={20}>
                  <StackedStoriesPreview
                    stories={stories}
                    onTap={() => setShowStoryList(true)}
                  />
                  <Pressable onPress={() => setShowStoryList(true)}>
                    <Text
                      color={theme.colorTertiary.val}
                      fontSize={18}
                      textAlign="center"
                    >
                      Tap to manage your {stories.length} stor
                      {stories.length === 1 ? 'y' : 'ies'}
                    </Text>
                  </Pressable>
                </YStack>
              ) : (
                <StoriesExplanation />
              )}
            </YStack>

            <YStack paddingBottom={Platform.OS === 'android' ? 60 : 40} gap={12}>
              {!hasMaxStories && (
                <Button
                  size="$4"
                  backgroundColor={theme.backgroundTertiary.val}
                  borderColor={theme.borderColor.val}
                  borderRadius={25}
                  onPress={handleAddStory}
                >
                  <XStack alignItems="center" gap={8}>
                    <Feather name="plus" size={ICON.sm} color={theme.color.val} />
                    <Text color={theme.color.val} fontWeight="bold">
                      Add to Story
                    </Text>
                  </XStack>
                </Button>
              )}

              {hasStories && (
                <Button
                  size="$4"
                  backgroundColor="transparent"
                  borderColor={theme.borderColor.val}
                  borderRadius={25}
                  onPress={handleViewStories}
                >
                  <XStack alignItems="center" gap={8}>
                    <Feather name="eye" size={ICON.sm} color={theme.colorSecondary.val} />
                    <Text color={theme.color.val} fontWeight="bold">
                      View Your Stories
                    </Text>
                  </XStack>
                </Button>
              )}
            </YStack>
          </YStack>
        )}
        {confirmDialog}
      </Sheet.Frame>
    </Sheet>
  )
}
