import { useEffect } from "react";
import { Text, View, TouchableOpacity, FlatList, 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 { useCalls } from "@/lib/calls-context";
import { useColors } from "@/hooks/use-colors";
import { useAppAuth } from "@/lib/auth-context";
import { getCategoryLabel, getCategoryIcon, getStatusLabel, getStatusColor } from "@/lib/types";
import type { MaintenanceCall } from "@/lib/types";

export default function HomeScreen() {
  const router = useRouter();
  const colors = useColors();
  const { calls, isLoading } = useCalls();
  const { user, isAuthenticated, isLoading: authLoading } = useAppAuth();

  // Redirecionar para login se não autenticado
  useEffect(() => {
    if (!authLoading && !isAuthenticated) {
      router.replace("/login");
    }
  }, [authLoading, isAuthenticated, router]);

  // Pegar os 5 chamados mais recentes
  const recentCalls = calls.slice(0, 5);

  function handleNewCall() {
    if (Platform.OS !== "web") {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
    }
    router.push("/new-call");
  }

  function handleCallPress(call: MaintenanceCall) {
    if (Platform.OS !== "web") {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    }
    router.push({ pathname: "/call-details", params: { id: call.id } });
  }

  function renderCallItem({ item }: { item: MaintenanceCall }) {
    const statusColor = getStatusColor(item.status);
    return (
      <TouchableOpacity
        onPress={() => handleCallPress(item)}
        activeOpacity={0.7}
        className="bg-surface rounded-xl p-4 mb-3 border border-border"
      >
        <View className="flex-row items-center justify-between">
          <View className="flex-row items-center flex-1">
            <View 
              className="w-12 h-12 rounded-full items-center justify-center mr-3"
              style={{ backgroundColor: colors.primary + '20' }}
            >
              <IconSymbol name={getCategoryIcon(item.category) as any} size={24} color={colors.primary} />
            </View>
            <View className="flex-1">
              <Text className="text-foreground font-semibold text-base" numberOfLines={1}>
                {getCategoryLabel(item.category)}
              </Text>
              <Text className="text-muted text-sm" numberOfLines={1}>
                {item.unit}
              </Text>
            </View>
          </View>
          <View className="items-end">
            <View 
              className="px-3 py-1 rounded-full"
              style={{ backgroundColor: statusColor + '20' }}
            >
              <Text style={{ color: statusColor }} className="text-xs font-semibold">
                {getStatusLabel(item.status)}
              </Text>
            </View>
          </View>
        </View>
      </TouchableOpacity>
    );
  }

  // Mostrar loading enquanto verifica autenticação
  if (authLoading || isLoading) {
    return (
      <ScreenContainer className="items-center justify-center">
        <ActivityIndicator size="large" color={colors.primary} />
      </ScreenContainer>
    );
  }

  // Se não autenticado, não renderizar (será redirecionado)
  if (!isAuthenticated) {
    return null;
  }

  return (
    <ScreenContainer className="p-4">
      {/* Header */}
      <View className="mb-6">
        <Text className="text-3xl font-bold text-foreground">
          Olá, {user?.name?.split(' ')[0]}!
        </Text>
        <Text className="text-muted text-base mt-1">
          {user?.company}
        </Text>
      </View>

      {/* Botão Principal - ABRIR CHAMADO */}
      <TouchableOpacity
        onPress={handleNewCall}
        activeOpacity={0.8}
        className="bg-primary rounded-2xl p-6 mb-8 shadow-lg"
        style={{ 
          shadowColor: colors.primary,
          shadowOffset: { width: 0, height: 4 },
          shadowOpacity: 0.3,
          shadowRadius: 8,
          elevation: 8,
        }}
      >
        <View className="flex-row items-center justify-center">
          <IconSymbol name="add-circle" size={32} color="#FFFFFF" />
          <Text className="text-white text-xl font-bold ml-3">
            ABRIR CHAMADO
          </Text>
        </View>
      </TouchableOpacity>

      {/* Chamados Recentes */}
      <View className="flex-1">
        <View className="flex-row items-center justify-between mb-4">
          <Text className="text-lg font-semibold text-foreground">
            Chamados Recentes
          </Text>
          {calls.length > 0 && (
            <TouchableOpacity 
              onPress={() => router.push("/(tabs)/my-calls")}
              activeOpacity={0.7}
            >
              <Text className="text-primary font-medium">Ver todos</Text>
            </TouchableOpacity>
          )}
        </View>

        {recentCalls.length === 0 ? (
          <View className="bg-surface rounded-xl p-8 items-center border border-border">
            <IconSymbol name="info" size={48} color={colors.muted} />
            <Text className="text-muted text-center mt-4 text-base">
              Nenhum chamado ainda.{"\n"}Toque no botão acima para abrir um novo.
            </Text>
          </View>
        ) : (
          <FlatList
            data={recentCalls}
            renderItem={renderCallItem}
            keyExtractor={(item) => item.id}
            showsVerticalScrollIndicator={false}
          />
        )}
      </View>
    </ScreenContainer>
  );
}
