import {Stack, useLocalSearchParams} from 'expo-router'
import {SymbolView} from 'expo-symbols'
import {useEffect} from 'react'
import {View} from 'react-native'

import {ErrorState} from '@/components/error-state'
import {FeedList} from '@/components/feed-list'
import {LoadingState} from '@/components/loading-state'
import {FriendButton} from '@/components/profile/friend-button'
import {ProfileMetric} from '@/components/profile/profile-metric'
import {ProfileTile} from '@/components/profile/profile-tile'
import {SectionHeader} from '@/components/section-header'
import {Avatar} from '@/components/ui/avatar'
import {Button} from '@/components/ui/button'
import {Card} from '@/components/ui/card'
import {HeaderIconButton} from '@/components/ui/header-icon-button'
import {Layout} from '@/components/ui/layout'
import {H2, Text} from '@/components/ui/typography'
import {useDetail} from '@/hooks/use-detail'
import {useProfileActions} from '@/hooks/use-profile-actions'
import {atoms as a, useTheme} from '@/sprinkles'
import {profileActivity, profileDetail} from '@/stores/profile'

// the profile embeds this many latest activity items; the rest paginate
const ACTIVITY_PREVIEW = 5

export default function ProfileScreen() {
  const {userId} = useLocalSearchParams<{userId: string}>()
  const {
    data: profile,
    loading,
    error,
    retry,
  } = useDetail(profileDetail, userId)
  const t = useTheme()
  const activity = profileActivity.useItems(userId)
  const activityLoading = profileActivity.useLoading(userId)
  const loadActivity = profileActivity.useLoad()
  const {
    busy,
    messaging,
    onAddFriend,
    onMessage,
    onUnblock,
    showProfileMenu,
  } = useProfileActions(userId, profile)

  const canViewContent =
    profile?.friendshipStatus === 'self' ||
    profile?.friendshipStatus === 'friends'

  useEffect(() => {
    if (canViewContent) void loadActivity(userId)
  }, [canViewContent, userId, loadActivity])

  return (
    <>
      <Stack.Screen
        options={{
          title: profile ? `@${profile.handle}` : 'Profile',
          headerRight:
            profile && profile.friendshipStatus !== 'self'
              ? () => (
                  <HeaderIconButton
                    icon="ellipsis"
                    label="Profile options"
                    onPress={showProfileMenu}
                  />
                )
              : undefined,
        }}
      />
      <Layout.ModalContent>
        {error && !profile ? (
          <ErrorState message={error} onRetry={retry} />
        ) : !profile ? (
          loading ? (
            <LoadingState />
          ) : null
        ) : (
          <View style={a.gap_2xl}>
            <View style={a.gap_sm}>
              <View
                style={[
                  a.flex_row,
                  a.align_center,
                  a.justify_between,
                ]}
              >
                <Avatar
                  handle={profile.handle}
                  uri={profile.avatarUrl}
                  size={72}
                />
                <View style={[a.flex_row, a.align_center, a.gap_xs]}>
                  {profile.friendshipStatus === 'blocked' ? (
                    <Button
                      label="Unblock"
                      color="secondary"
                      size="small"
                      onPress={() => void onUnblock()}
                    />
                  ) : (
                    <>
                      {profile.friendshipStatus === 'friends' && (
                        <Button
                          label="Message"
                          color="secondary"
                          size="small"
                          shape="round"
                          disabled={messaging}
                          onPress={() => void onMessage()}
                        >
                          <SymbolView
                            name="message"
                            size={18}
                            weight="medium"
                            tintColor={t.palette.contrast_900}
                          />
                        </Button>
                      )}
                      <FriendButton
                        status={profile.friendshipStatus}
                        busy={busy}
                        onAddFriend={onAddFriend}
                      />
                    </>
                  )}
                </View>
              </View>
              <View style={a.gap_xs}>
                <H2>@{profile.handle}</H2>
                <View style={[a.flex_row, a.align_center, a.gap_md]}>
                  {canViewContent && (
                    <>
                      <ProfileMetric
                        count={profile.crumbCount}
                        noun="crumb"
                        href={`/profile/${userId}/crumbs`}
                        handle={profile.handle}
                      />
                      <ProfileMetric
                        count={profile.trailCount}
                        noun="trail"
                        href={`/profile/${userId}/trails`}
                        handle={profile.handle}
                      />
                    </>
                  )}
                  <ProfileMetric
                    count={profile.friendCount}
                    noun="friend"
                    href={
                      canViewContent
                        ? `/profile/${userId}/friends`
                        : undefined
                    }
                    handle={profile.handle}
                  />
                </View>
              </View>
            </View>

            {canViewContent ? (
              <>
                <View style={[a.flex_row, a.gap_md]}>
                  <ProfileTile
                    label="Crumbs"
                    href={`/profile/${userId}/crumbs`}
                    count={profile.crumbCount}
                    noun="crumb"
                    preview={profile.crumbPreview ?? undefined}
                    emptyHint="No crumbs yet"
                  />
                  <ProfileTile
                    label="Trails"
                    href={`/profile/${userId}/trails`}
                    count={profile.trailCount}
                    noun="trail"
                    preview={profile.trailPreview ?? undefined}
                    emptyHint="No trails yet"
                  />
                </View>

                <View style={a.gap_xs}>
                  <SectionHeader
                    label="Recent activity"
                    seeAllHref={`/profile/${userId}/activity`}
                    seeAllLabel="See all activity"
                  />
                  <Card>
                    <FeedList
                      items={activity.slice(0, ACTIVITY_PREVIEW)}
                      loading={
                        activityLoading && activity.length === 0
                      }
                      hideAuthor
                    />
                  </Card>
                </View>
              </>
            ) : profile.friendshipStatus === 'blocked' ? (
              <Text style={t.atoms.text_contrast_medium}>
                You blocked @{profile.handle}. Unblock to see their
                crumbs and trails.
              </Text>
            ) : (
              <Text style={t.atoms.text_contrast_medium}>
                Only friends can see @{profile.handle}&apos;s crumbs
                and trails.
              </Text>
            )}
          </View>
        )}
      </Layout.ModalContent>
    </>
  )
}
