import { useState } from "react";
import {
  Text,
  View,
  TouchableOpacity,
  TextInput,
  ScrollView,
  Alert,
  Switch,
  ActivityIndicator,
} from "react-native";
import { useRouter } from "expo-router";
import * as Haptics from "expo-haptics";
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 RegisterScreen() {
  const router = useRouter();
  const colors = useColors();
  const { login } = useAppAuth();

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [role, setRole] = useState("");
  const [company, setCompany] = useState("");
  const [isMaintenance, setIsMaintenance] = useState(false);
  const [showCompanyPicker, setShowCompanyPicker] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const registerMutation = trpc.appAuth.register.useMutation();

  async function handleRegister() {
    if (!name.trim()) {
      Alert.alert("Atenção", "Digite seu nome completo.");
      return;
    }
    if (!email.trim()) {
      Alert.alert("Atenção", "Digite seu e-mail.");
      return;
    }
    if (!password.trim()) {
      Alert.alert("Atenção", "Digite uma senha.");
      return;
    }
    if (password.length < 4) {
      Alert.alert("Atenção", "A senha deve ter pelo menos 4 caracteres.");
      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 registerMutation.mutateAsync({
        name: name.trim(),
        email: email.trim().toLowerCase(),
        password: password,
        role: role.trim(),
        company: company,
        isMaintenance: isMaintenance,
      });

      if (result.success && result.userId) {
        // Fazer login automático após cadastro
        await login({
          id: result.userId,
          name: name.trim(),
          email: email.trim().toLowerCase(),
          role: role.trim(),
          company: company,
          isMaintenance: isMaintenance,
        });

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

        Alert.alert("Cadastro realizado!", "Bem-vindo ao Grupo Samam!", [
          { text: "OK", onPress: () => router.replace("/(tabs)") },
        ]);
      }
    } catch (error: any) {
      Alert.alert("Erro", error.message || "Não foi possível realizar o cadastro.");
    } finally {
      setIsSubmitting(false);
    }
  }

  function handleGoToLogin() {
    router.push("/login");
  }

  return (
    <ScreenContainer edges={["top", "left", "right", "bottom"]} className="p-4">
      <ScrollView showsVerticalScrollIndicator={false} className="flex-1">
        {/* Header */}
        <View className="items-center mb-6 mt-4">
          <Text className="text-3xl font-bold text-foreground">Grupo Samam</Text>
          <Text className="text-muted text-base mt-2">Crie sua conta</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 */}
          <View>
            <Text className="text-foreground font-medium mb-2">E-mail</Text>
            <TextInput
              value={email}
              onChangeText={setEmail}
              placeholder="Digite seu e-mail"
              placeholderTextColor={colors.muted}
              keyboardType="email-address"
              autoCapitalize="none"
              autoComplete="email"
              className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
              style={{ color: colors.foreground }}
            />
          </View>

          {/* Senha */}
          <View>
            <Text className="text-foreground font-medium mb-2">Senha</Text>
            <TextInput
              value={password}
              onChangeText={setPassword}
              placeholder="Digite sua senha"
              placeholderTextColor={colors.muted}
              secureTextEntry
              className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
              style={{ color: colors.foreground }}
            />
          </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>

          {/* Equipe de Manutenção */}
          <View className="bg-surface border border-border rounded-xl p-4">
            <View className="flex-row items-center justify-between">
              <View className="flex-1 mr-4">
                <Text className="text-foreground font-medium">Equipe de Manutenção</Text>
                <Text className="text-muted text-sm mt-1">
                  Marque se você faz parte da equipe de manutenção
                </Text>
              </View>
              <Switch
                value={isMaintenance}
                onValueChange={setIsMaintenance}
                trackColor={{ false: colors.border, true: colors.primary }}
                thumbColor="#FFFFFF"
              />
            </View>
          </View>
        </View>

        {/* Botão Cadastrar */}
        <TouchableOpacity
          onPress={handleRegister}
          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">CADASTRAR</Text>
          )}
        </TouchableOpacity>

        {/* Link para Login */}
        <TouchableOpacity onPress={handleGoToLogin} activeOpacity={0.7} className="mt-6 mb-8">
          <Text className="text-center text-muted">
            Já tem uma conta?{" "}
            <Text className="text-primary font-semibold">Fazer login</Text>
          </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>
  );
}
