import { useState } from "react";
import { Text, View, TouchableOpacity, TextInput, ScrollView, Alert } 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 { useCalls } from "@/lib/calls-context";
import { useColors } from "@/hooks/use-colors";
import { UNITS, CATEGORIES, Category } from "@/lib/types";

export default function NewCallScreen() {
  const router = useRouter();
  const colors = useColors();
  const { addCall } = useCalls();

  const [selectedUnit, setSelectedUnit] = useState<string>("");
  const [selectedCategory, setSelectedCategory] = useState<Category | null>(null);
  const [description, setDescription] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  function handleSelectUnit(unit: string) {
    if (Platform.OS !== "web") {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    }
    setSelectedUnit(unit);
  }

  function handleSelectCategory(category: Category) {
    if (Platform.OS !== "web") {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    }
    setSelectedCategory(category);
  }

  async function handleSubmit() {
    if (!selectedUnit) {
      Alert.alert("Atenção", "Selecione a unidade onde está o problema.");
      return;
    }
    if (!selectedCategory) {
      Alert.alert("Atenção", "Selecione o tipo de manutenção.");
      return;
    }
    if (!description.trim()) {
      Alert.alert("Atenção", "Descreva o problema.");
      return;
    }

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

    setIsSubmitting(true);
    try {
      await addCall(selectedUnit, selectedCategory, description.trim());
      Alert.alert(
        "Chamado Aberto!",
        "Seu chamado foi registrado com sucesso. A equipe de manutenção irá analisar.",
        [{ text: "OK", onPress: () => router.back() }]
      );
    } catch (error) {
      Alert.alert("Erro", "Não foi possível abrir o chamado. Tente novamente.");
    } finally {
      setIsSubmitting(false);
    }
  }

  function handleClose() {
    router.back();
  }

  return (
    <ScreenContainer edges={["top", "left", "right", "bottom"]} className="p-4">
      {/* Header */}
      <View className="flex-row items-center justify-between mb-6">
        <TouchableOpacity onPress={handleClose} activeOpacity={0.7} className="p-2 -ml-2">
          <IconSymbol name="close" size={28} color={colors.foreground} />
        </TouchableOpacity>
        <Text className="text-xl font-bold text-foreground">Novo Chamado</Text>
        <View className="w-10" />
      </View>

      <ScrollView showsVerticalScrollIndicator={false} className="flex-1">
        {/* Seleção de Unidade */}
        <View className="mb-6">
          <Text className="text-lg font-semibold text-foreground mb-3">
            Onde está o problema?
          </Text>
          <View className="flex-row flex-wrap gap-2">
            {UNITS.map((unit) => (
              <TouchableOpacity
                key={unit}
                onPress={() => handleSelectUnit(unit)}
                activeOpacity={0.7}
                className="px-4 py-3 rounded-xl border"
                style={{
                  backgroundColor: selectedUnit === unit ? colors.primary : colors.surface,
                  borderColor: selectedUnit === unit ? colors.primary : colors.border,
                }}
              >
                <Text
                  className="font-medium"
                  style={{
                    color: selectedUnit === unit ? "#FFFFFF" : colors.foreground,
                  }}
                >
                  {unit}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>

        {/* Seleção de Categoria */}
        <View className="mb-6">
          <Text className="text-lg font-semibold text-foreground mb-3">
            Qual o tipo de manutenção?
          </Text>
          <View className="flex-row flex-wrap gap-3">
            {CATEGORIES.map((cat) => (
              <TouchableOpacity
                key={cat.id}
                onPress={() => handleSelectCategory(cat.id)}
                activeOpacity={0.7}
                className="w-[30%] aspect-square rounded-2xl border items-center justify-center p-2"
                style={{
                  backgroundColor: selectedCategory === cat.id ? colors.primary : colors.surface,
                  borderColor: selectedCategory === cat.id ? colors.primary : colors.border,
                }}
              >
                <IconSymbol
                  name={cat.icon as any}
                  size={36}
                  color={selectedCategory === cat.id ? "#FFFFFF" : colors.primary}
                />
                <Text
                  className="text-xs font-medium text-center mt-2"
                  style={{
                    color: selectedCategory === cat.id ? "#FFFFFF" : colors.foreground,
                  }}
                  numberOfLines={2}
                >
                  {cat.label}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>

        {/* Descrição do Problema */}
        <View className="mb-6">
          <Text className="text-lg font-semibold text-foreground mb-3">
            Descreva o problema
          </Text>
          <TextInput
            value={description}
            onChangeText={setDescription}
            placeholder="Ex: O ar-condicionado da sala de reuniões não está gelando..."
            placeholderTextColor={colors.muted}
            multiline
            numberOfLines={4}
            textAlignVertical="top"
            returnKeyType="done"
            className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
            style={{
              minHeight: 120,
              color: colors.foreground,
            }}
          />
        </View>
      </ScrollView>

      {/* Botão Enviar */}
      <TouchableOpacity
        onPress={handleSubmit}
        disabled={isSubmitting}
        activeOpacity={0.8}
        className="bg-primary rounded-2xl p-5 mt-4"
        style={{
          opacity: isSubmitting ? 0.7 : 1,
        }}
      >
        <View className="flex-row items-center justify-center">
          <IconSymbol name="send" size={24} color="#FFFFFF" />
          <Text className="text-white text-lg font-bold ml-2">
            {isSubmitting ? "ENVIANDO..." : "ENVIAR CHAMADO"}
          </Text>
        </View>
      </TouchableOpacity>
    </ScreenContainer>
  );
}
