import { useState } from "react";
import {
  Text,
  View,
  TouchableOpacity,
  TextInput,
  ScrollView,
  Alert,
  ActivityIndicator,
  Image,
} from "react-native";
import { useRouter } from "expo-router";
import * as Haptics from "expo-haptics";
import * as ImagePicker from "expo-image-picker";
import { Platform } from "react-native";

import { ScreenContainer } from "@/components/screen-container";
import { IconSymbol } from "@/components/ui/icon-symbol";
import { useColors } from "@/hooks/use-colors";
import { useAppAuth } from "@/lib/auth-context";
import { trpc } from "@/lib/trpc";
import { UNITS } from "@/lib/types";

export default function EditProfileScreen() {
  const router = useRouter();
  const colors = useColors();
  const { user, updateUser } = useAppAuth();

  const [name, setName] = useState(user?.name || "");
  const [role, setRole] = useState(user?.role || "");
  const [company, setCompany] = useState(user?.company || "");
  const [photoUrl, setPhotoUrl] = useState(user?.photoUrl || "");
  const [showCompanyPicker, setShowCompanyPicker] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const updateProfileMutation = trpc.appAuth.updateProfile.useMutation();

  async function handlePickImage() {
    try {
      const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
      
      if (!permissionResult.granted) {
        Alert.alert("Permissão necessária", "Precisamos de acesso à galeria para selecionar uma foto.");
        return;
      }

      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        aspect: [1, 1],
        quality: 0.5,
      });

      if (!result.canceled && result.assets[0]) {
        setPhotoUrl(result.assets[0].uri);
      }
    } catch (error) {
      console.error("Erro ao selecionar imagem:", error);
      Alert.alert("Erro", "Não foi possível selecionar a imagem.");
    }
  }

  async function handleSave() {
    if (!name.trim()) {
      Alert.alert("Atenção", "Digite seu nome.");
      return;
    }
    if (!role.trim()) {
      Alert.alert("Atenção", "Digite sua função/cargo.");
      return;
    }
    if (!company.trim()) {
      Alert.alert("Atenção", "Selecione sua empresa/unidade.");
      return;
    }

    if (Platform.OS !== "web") {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
    }

    setIsSubmitting(true);
    try {
      const result = await updateProfileMutation.mutateAsync({
        userId: user!.id,
        name: name.trim(),
        role: role.trim(),
        company: company,
        photoUrl: photoUrl || undefined,
      });

      if (result.success && result.user) {
        await updateUser(result.user);

        if (Platform.OS !== "web") {
          Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
        }

        Alert.alert("Sucesso", "Perfil atualizado com sucesso!", [
          { text: "OK", onPress: () => router.back() },
        ]);
      }
    } catch (error: any) {
      Alert.alert("Erro", error.message || "Não foi possível atualizar o perfil.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <ScreenContainer edges={["top", "left", "right", "bottom"]} className="p-4">
      <ScrollView showsVerticalScrollIndicator={false} className="flex-1">
        {/* Header */}
        <View className="flex-row items-center mb-6">
          <TouchableOpacity onPress={() => router.back()} className="mr-4">
            <IconSymbol name="arrow-back" size={24} color={colors.foreground} />
          </TouchableOpacity>
          <Text className="text-2xl font-bold text-foreground">Editar Perfil</Text>
        </View>

        {/* Foto de Perfil */}
        <View className="items-center mb-6">
          <TouchableOpacity onPress={handlePickImage} activeOpacity={0.7}>
            <View 
              className="w-28 h-28 rounded-full items-center justify-center border-2 overflow-hidden"
              style={{ borderColor: colors.primary, backgroundColor: colors.surface }}
            >
              {photoUrl ? (
                <Image 
                  source={{ uri: photoUrl }} 
                  className="w-full h-full"
                  resizeMode="cover"
                />
              ) : (
                <IconSymbol name="person.fill" size={48} color={colors.muted} />
              )}
            </View>
            <View 
              className="absolute bottom-0 right-0 w-8 h-8 rounded-full items-center justify-center"
              style={{ backgroundColor: colors.primary }}
            >
              <IconSymbol name="camera" size={18} color="#FFFFFF" />
            </View>
          </TouchableOpacity>
          <Text className="text-muted text-sm mt-2">Toque para alterar a foto</Text>
        </View>

        {/* Formulário */}
        <View className="gap-4">
          {/* Nome */}
          <View>
            <Text className="text-foreground font-medium mb-2">Nome Completo</Text>
            <TextInput
              value={name}
              onChangeText={setName}
              placeholder="Digite seu nome"
              placeholderTextColor={colors.muted}
              autoCapitalize="words"
              className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
              style={{ color: colors.foreground }}
            />
          </View>

          {/* E-mail (não editável) */}
          <View>
            <Text className="text-foreground font-medium mb-2">E-mail</Text>
            <View className="bg-surface border border-border rounded-xl p-4 opacity-60">
              <Text className="text-muted text-base">{user?.email}</Text>
            </View>
            <Text className="text-muted text-xs mt-1">O e-mail não pode ser alterado</Text>
          </View>

          {/* Função/Cargo */}
          <View>
            <Text className="text-foreground font-medium mb-2">Função/Cargo</Text>
            <TextInput
              value={role}
              onChangeText={setRole}
              placeholder="Ex: Vendedor, Gerente, Técnico..."
              placeholderTextColor={colors.muted}
              autoCapitalize="words"
              className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
              style={{ color: colors.foreground }}
            />
          </View>

          {/* Empresa/Unidade */}
          <View>
            <Text className="text-foreground font-medium mb-2">Empresa/Unidade</Text>
            <TouchableOpacity
              onPress={() => setShowCompanyPicker(true)}
              activeOpacity={0.7}
              className="bg-surface border border-border rounded-xl p-4 flex-row items-center justify-between"
            >
              <Text
                className="text-base"
                style={{ color: company ? colors.foreground : colors.muted }}
              >
                {company || "Selecione sua unidade"}
              </Text>
              <IconSymbol name="chevron-right" size={20} color={colors.muted} />
            </TouchableOpacity>
          </View>
        </View>

        {/* Botão Salvar */}
        <TouchableOpacity
          onPress={handleSave}
          disabled={isSubmitting}
          activeOpacity={0.8}
          className="bg-primary rounded-2xl p-5 mt-6"
          style={{ opacity: isSubmitting ? 0.7 : 1 }}
        >
          {isSubmitting ? (
            <ActivityIndicator color="#FFFFFF" />
          ) : (
            <Text className="text-white text-lg font-bold text-center">SALVAR ALTERAÇÕES</Text>
          )}
        </TouchableOpacity>

        {/* Link para alterar senha */}
        <TouchableOpacity 
          onPress={() => router.push("/change-password" as any)} 
          activeOpacity={0.7} 
          className="mt-4 mb-8"
        >
          <Text className="text-center text-primary font-semibold">Alterar senha</Text>
        </TouchableOpacity>
      </ScrollView>

      {/* Modal de seleção de empresa */}
      {showCompanyPicker && (
        <View
          className="absolute inset-0 justify-end"
          style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
        >
          <View className="rounded-t-3xl p-6 max-h-[70%]" style={{ backgroundColor: colors.background }}>
            <View className="flex-row items-center justify-between mb-4">
              <Text className="text-xl font-bold text-foreground">Selecione a Unidade</Text>
              <TouchableOpacity onPress={() => setShowCompanyPicker(false)}>
                <IconSymbol name="close" size={24} color={colors.foreground} />
              </TouchableOpacity>
            </View>
            <ScrollView showsVerticalScrollIndicator={false}>
              {UNITS.map((unit) => (
                <TouchableOpacity
                  key={unit}
                  onPress={() => {
                    setCompany(unit);
                    setShowCompanyPicker(false);
                  }}
                  className="py-4 border-b border-border"
                >
                  <Text
                    className="text-lg"
                    style={{
                      color: company === unit ? colors.primary : colors.foreground,
                      fontWeight: company === unit ? "600" : "400",
                    }}
                  >
                    {unit}
                  </Text>
                </TouchableOpacity>
              ))}
            </ScrollView>
          </View>
        </View>
      )}
    </ScreenContainer>
  );
}
