import {pluralize} from '@crumbs/core/text'
import {Stack, useRouter} from 'expo-router'
import {SymbolView} from 'expo-symbols'
import {useEffect} from 'react'
import {View} from 'react-native'

import {Avatar} from '@/components/ui/avatar'
import {Button} from '@/components/ui/button'
import {Card, CardRow, CardRowTitle} from '@/components/ui/card'
import {Layout} from '@/components/ui/layout'
import {Link} from '@/components/ui/link'
import {Text} from '@/components/ui/typography'
import {useBusyAction} from '@/hooks/use-busy-action'
import {pickAvatarImage} from '@/lib/avatar'
import {showActionSheet} from '@/lib/dialogs'
import {atoms as a, useTheme} from '@/sprinkles'
import {useAuth} from '@/stores/auth'
import {useLoadProfile, useProfile} from '@/stores/profile'

export default function YouScreen() {
  const router = useRouter()
  const user = useAuth((s) => s.user)
  const signOut = useAuth((s) => s.signOut)
  const updateAvatar = useAuth((s) => s.updateAvatar)
  const removeAvatar = useAuth((s) => s.removeAvatar)
  const profile = useProfile(user?.id ?? '')
  const loadProfile = useLoadProfile()
  const {busy, run} = useBusyAction({haptic: false})
  const t = useTheme()

  useEffect(() => {
    if (user) void loadProfile(user.id)
  }, [user, loadProfile])

  const count = profile?.friendCount ?? 0

  const onChangePhoto = async () => {
    const uri = await pickAvatarImage()
    if (!uri) return
    await run('avatar', () => updateAvatar(uri))
  }

  const onRemovePhoto = () => run('avatar', () => removeAvatar())

  const onEditAvatar = () => {
    showActionSheet([
      {
        label: 'Upload from library',
        onPress: () => void onChangePhoto(),
      },
      ...(user?.avatarUrl
        ? [
            {
              label: 'Remove avatar',
              destructive: true,
              onPress: () => void onRemovePhoto(),
            },
          ]
        : []),
    ])
  }

  return (
    <>
      <Layout.LargeTitle>{`@${user?.handle}`}</Layout.LargeTitle>
      <Stack.Toolbar placement="right">
        <Stack.Toolbar.Button
          accessibilityLabel="Settings"
          icon="gearshape"
          onPress={() => router.push('/settings')}
        />
      </Stack.Toolbar>
      <Layout.Content>
        <Layout.Column>
          <View style={[a.align_center, a.py_md]}>
            <Button
              label="Edit avatar"
              onPress={onEditAvatar}
              variant="ghost"
              disabled={busy !== null}
              style={{paddingVertical: 0, paddingHorizontal: 0}}
            >
              <Avatar
                handle={user?.handle ?? ''}
                uri={user?.avatarUrl}
                size={96}
              />
              <View
                style={[
                  a.absolute,
                  a.rounded_full,
                  a.border,
                  a.align_center,
                  a.justify_center,
                  t.atoms.bg_contrast_25,
                  t.atoms.border_contrast_low,
                  {bottom: 0, right: 0, width: 28, height: 28},
                ]}
              >
                <SymbolView
                  name="camera.fill"
                  size={14}
                  tintColor={t.palette.contrast_900}
                />
              </View>
            </Button>
          </View>

          <Card>
            <Link href="/friends" accessibilityLabel="Friends">
              {(isPressed) => (
                <CardRow pressed={isPressed}>
                  <CardRowTitle>Friends</CardRowTitle>
                  <Text style={[t.atoms.text_contrast_medium]}>
                    {pluralize(count, 'friend')}
                  </Text>
                </CardRow>
              )}
            </Link>
          </Card>

          <View>
            <Button
              label="Sign out"
              onPress={() => void signOut()}
              variant="ghost"
              color="negative"
              size="large"
              shape="rectangular"
            />
          </View>
        </Layout.Column>
      </Layout.Content>
    </>
  )
}
