import React, { useState, useEffect, useRef } from 'react';
import {
  View, Text, StyleSheet, Image, Pressable, Animated,
  KeyboardAvoidingView, Platform, ScrollView,
} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import Input from '../components/Input';
import Button from '../components/Button';
import useAuthStore from '../store/useAuthStore';
import { getProfile, saveProfile } from '../services/profileService';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

export default function EditProfileScreen({ navigation }) {
  const user = useAuthStore((s) => s.user);

  const [nickname, setNickname] = useState('');
  const [fullName, setFullName] = useState('');
  const [photoUri, setPhotoUri] = useState(null);
  const [loading, setLoading] = useState(false);
  const [initialLoading, setInitialLoading] = useState(true);

  const fadeAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    const load = async () => {
      if (user?.id) {
        const profile = await getProfile(user.id);
        if (profile) {
          setNickname(profile.nickname || '');
          setFullName(profile.fullName || '');
          setPhotoUri(profile.photoUri || null);
        }
      }
      setInitialLoading(false);
      Animated.timing(fadeAnim, { toValue: 1, duration: 500, useNativeDriver: true }).start();
    };
    load();
  }, []);

  const pickFromGallery = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        allowsEditing: true,
        aspect: [1, 1],
        quality: 0.5,
        exif: false,
      });
      if (!result.canceled && result.assets?.[0]?.uri) {
        setPhotoUri(result.assets[0].uri);
      }
    } catch (_) {}
  };

  const takePhoto = async () => {
    try {
      const result = await ImagePicker.launchCameraAsync({
        allowsEditing: true,
        aspect: [1, 1],
        quality: 0.5,
        exif: false,
      });
      if (!result.canceled && result.assets?.[0]?.uri) {
        setPhotoUri(result.assets[0].uri);
      }
    } catch (_) {}
  };

  const handlePickPhoto = () => {
    pickFromGallery();
  };

  const handleSave = async () => {
    if (!nickname.trim() && !fullName.trim()) {
      showAlert('Almost there', 'Fill in at least your nickname or full name.');
      return;
    }

    setLoading(true);
    try {
      await saveProfile(user.id, {
        nickname: nickname.trim(),
        fullName: fullName.trim(),
        photoUri,
      });
      showAlert('Saved', 'Your profile has been updated.', [
        { text: 'OK', onPress: () => navigation.goBack() },
      ]);
    } catch (e) {
      showAlert('Oops', e.message || 'Could not save your profile.');
    } finally {
      setLoading(false);
    }
  };

  const displayInitial = nickname?.[0] || fullName?.[0] || user?.email?.[0] || 'N';

  if (initialLoading) return <ScreenWrapper />;

  return (
    <ScreenWrapper>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        style={styles.flex}
      >
        <Animated.ScrollView
          style={[styles.flex, { opacity: fadeAnim }]}
          contentContainerStyle={styles.scrollContent}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps="handled"
        >
          <Text style={styles.title}>Edit Profile</Text>
          <Text style={styles.subtitle}>Make it yours — this is how we'll greet you.</Text>

          {/* Photo */}
          <Pressable style={styles.photoSection} onPress={handlePickPhoto}>
            {photoUri ? (
              <Image source={{ uri: photoUri }} style={styles.photo} />
            ) : (
              <View style={styles.photoPlaceholder}>
                <Text style={styles.photoInitial}>{displayInitial.toUpperCase()}</Text>
              </View>
            )}
          </Pressable>
          <View style={styles.photoActions}>
            <Pressable style={({ pressed }) => [styles.photoBtn, pressed && { opacity: 0.6 }]} onPress={pickFromGallery}>
              <Text style={styles.photoBtnText}>Gallery</Text>
            </Pressable>
            <Pressable style={({ pressed }) => [styles.photoBtn, pressed && { opacity: 0.6 }]} onPress={takePhoto}>
              <Text style={styles.photoBtnText}>Camera</Text>
            </Pressable>
          </View>

          {/* Fields */}
          <View style={styles.form}>
            <Input
              label="Nickname"
              value={nickname}
              onChangeText={setNickname}
              placeholder="What should we call you?"
            />
            <Input
              label="Full name"
              value={fullName}
              onChangeText={setFullName}
              placeholder="Your real name (optional)"
              autoCapitalize="words"
            />

            {/* Email (read-only) */}
            <View style={styles.readonlyField}>
              <Text style={styles.readonlyLabel}>Email</Text>
              <Text style={styles.readonlyValue}>{user?.email || '—'}</Text>
            </View>
          </View>

          <Button
            title={loading ? 'Saving...' : 'Save Profile'}
            onPress={handleSave}
            loading={loading}
            style={styles.saveBtn}
          />

          <Button
            title="Cancel"
            onPress={() => navigation.goBack()}
            variant="secondary"
            style={styles.cancelBtn}
          />
        </Animated.ScrollView>
      </KeyboardAvoidingView>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1 },
  scrollContent: {
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.xxl,
    paddingBottom: spacing.xxl * 2,
    alignItems: 'center',
  },
  title: {
    color: colors.text,
    fontSize: fonts.sizes.xxl,
    fontWeight: fonts.weights.bold,
    marginBottom: spacing.xs,
    alignSelf: 'flex-start',
  },
  subtitle: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    marginBottom: spacing.xl,
    alignSelf: 'flex-start',
  },

  // Photo
  photoSection: {
    position: 'relative',
    marginBottom: spacing.sm,
  },
  photo: {
    width: 100,
    height: 100,
    borderRadius: 50,
    borderWidth: 3,
    borderColor: colors.primary,
  },
  photoPlaceholder: {
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    shadowColor: colors.primary,
    shadowOffset: { width: 0, height: 0 },
    shadowOpacity: 0.4,
    shadowRadius: 12,
    elevation: 6,
  },
  photoInitial: {
    color: colors.text,
    fontSize: fonts.sizes.hero,
    fontWeight: fonts.weights.bold,
  },
  photoBadge: {
    position: 'absolute',
    bottom: 0,
    right: 0,
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: colors.surface,
    borderWidth: 2,
    borderColor: colors.border,
    alignItems: 'center',
    justifyContent: 'center',
  },
  photoBadgeText: {
    fontSize: 14,
  },
  photoActions: {
    flexDirection: 'row',
    gap: spacing.md,
    marginTop: spacing.sm,
    marginBottom: spacing.xl,
  },
  photoBtn: {
    paddingVertical: spacing.xs + 2,
    paddingHorizontal: spacing.lg,
    borderRadius: borderRadius.full,
    borderWidth: 1,
    borderColor: colors.border,
    backgroundColor: colors.surface,
  },
  photoBtnText: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.medium,
  },

  // Form
  form: {
    width: '100%',
    marginBottom: spacing.lg,
  },
  readonlyField: {
    backgroundColor: colors.surface,
    borderRadius: borderRadius.md,
    padding: spacing.md,
    borderWidth: 1,
    borderColor: colors.border,
    marginBottom: spacing.md,
  },
  readonlyLabel: {
    color: colors.textMuted,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.medium,
    marginBottom: spacing.xs,
  },
  readonlyValue: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
  },

  saveBtn: {
    width: '100%',
    marginBottom: spacing.sm,
  },
  cancelBtn: {
    width: '100%',
  },
});
