import { useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  Image,
  Pressable,
  Text,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import * as ImagePicker from 'expo-image-picker';
import { Camera } from 'lucide-react-native';
import { toast } from 'sonner-native';
import { apiClient } from '@/api/client';
import { useAuthStore } from '@/stores/auth-store';
import { useAvatarUrl } from '@/hooks/use-avatar-url';
import { toUserMessage } from '@/lib/errors';
import type { RootStackScreenProps } from '@/navigation/types';

export function AccountScreen({ navigation }: RootStackScreenProps<'Account'>) {
  const user = useAuthStore((s) => s.user);
  const refreshUser = useAuthStore((s) => s.refreshUser);
  const avatarUrl = useAvatarUrl(user?.avatar_object_id);
  const initials = user?.email_prefix?.slice(0, 2).toUpperCase() ?? '?';
  const [busy, setBusy] = useState(false);

  const pickAndUpload = async () => {
    const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (!permission.granted) {
      toast.error('Photo library access is needed to set an avatar.');
      return;
    }
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      allowsEditing: true,
      aspect: [1, 1],
      quality: 0.8,
    });
    if (result.canceled) return;
    const asset = result.assets[0];
    if (!asset) return;

    setBusy(true);
    try {
      await apiClient.uploadAvatar(asset.uri, asset.mimeType ?? 'image/jpeg');
      await refreshUser();
      toast.success('Avatar updated');
    } catch (err) {
      toast.error(toUserMessage(err));
    } finally {
      setBusy(false);
    }
  };

  const removeAvatar = () => {
    Alert.alert('Remove avatar?', 'Your initials will be shown instead.', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Remove',
        style: 'destructive',
        onPress: async () => {
          setBusy(true);
          try {
            await apiClient.deleteAvatar();
            await refreshUser();
          } catch (err) {
            toast.error(toUserMessage(err));
          } finally {
            setBusy(false);
          }
        },
      },
    ]);
  };

  return (
    <SafeAreaView className="flex-1 bg-background" edges={['top']}>
      <View className="flex-row items-center px-3 py-3 border-b border-border">
        <Pressable onPress={() => navigation.goBack()} className="px-2 py-1">
          <Text className="text-foreground text-2xl">‹</Text>
        </Pressable>
        <Text className="flex-1 text-center text-foreground text-base font-semibold">
          Account
        </Text>
        <View className="w-8" />
      </View>

      <View className="items-center px-6 py-8">
        <Pressable
          onPress={pickAndUpload}
          disabled={busy}
          accessibilityLabel="Change profile picture"
          className="relative"
        >
          <View className="h-24 w-24 items-center justify-center overflow-hidden rounded-full bg-muted">
            {busy ? (
              <ActivityIndicator />
            ) : avatarUrl ? (
              <Image source={{ uri: avatarUrl }} className="h-full w-full" />
            ) : (
              <Text className="text-foreground text-3xl font-medium">
                {initials}
              </Text>
            )}
          </View>
          <View className="absolute bottom-0 right-0 h-7 w-7 items-center justify-center rounded-full bg-primary border-2 border-background">
            <Camera size={13} color="#000000" />
          </View>
        </Pressable>

        {user?.avatar_object_id ? (
          <Pressable onPress={removeAvatar} disabled={busy} className="mt-3">
            <Text className="text-destructive text-sm">Remove photo</Text>
          </Pressable>
        ) : null}
      </View>

      <View className="px-6 gap-4">
        <Field label="Email" value={user?.email ?? '—'} />
      </View>
    </SafeAreaView>
  );
}

function Field({ label, value }: { label: string; value: string }) {
  return (
    <View className="gap-1">
      <Text className="text-muted-foreground text-xs uppercase tracking-wide">
        {label}
      </Text>
      <Text className="text-foreground text-base">{value}</Text>
    </View>
  );
}
