import { useState } 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 {
  getCategoryLabel,
  getCategoryIcon,
  getStatusLabel,
  getStatusColor,
  getPriorityColor,
  Status,
} from "@/lib/types";
import type { MaintenanceCall } from "@/lib/types";

type FilterType = "todos" | "pendentes" | "concluidos";

export default function MyCallsScreen() {
  const router = useRouter();
  const colors = useColors();
  const { calls, isLoading, getPendingCalls, getCompletedCalls } = useCalls();
  const [filter, setFilter] = useState<FilterType>("todos");

  function getFilteredCalls(): MaintenanceCall[] {
    switch (filter) {
      case "pendentes":
        return getPendingCalls();
      case "concluidos":
        return getCompletedCalls();
      default:
        return calls;
    }
  }

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

  function handleFilterPress(newFilter: FilterType) {
    if (Platform.OS !== "web") {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    }
    setFilter(newFilter);
  }

  function formatDate(timestamp: number): string {
    const date = new Date(timestamp);
    return date.toLocaleDateString("pt-BR", {
      day: "2-digit",
      month: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  }

  function renderCallItem({ item }: { item: MaintenanceCall }) {
    const statusColor = getStatusColor(item.status);
    const priorityColor = getPriorityColor(item.priority);

    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-start 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>
              <Text className="text-muted text-xs mt-1">{formatDate(item.createdAt)}</Text>
            </View>
          </View>
          <View className="items-end">
            <View
              className="px-3 py-1 rounded-full mb-2"
              style={{ backgroundColor: statusColor + "20" }}
            >
              <Text style={{ color: statusColor }} className="text-xs font-semibold">
                {getStatusLabel(item.status)}
              </Text>
            </View>
            <View className="flex-row items-center">
              <IconSymbol name="flag" size={14} color={priorityColor} />
            </View>
          </View>
        </View>
        <Text className="text-muted text-sm mt-2" numberOfLines={2}>
          {item.description}
        </Text>
      </TouchableOpacity>
    );
  }

  const filteredCalls = getFilteredCalls();

  if (isLoading) {
    return (
      <ScreenContainer className="items-center justify-center">
        <ActivityIndicator size="large" color={colors.primary} />
      </ScreenContainer>
    );
  }

  return (
    <ScreenContainer className="p-4">
      {/* Header */}
      <View className="mb-4">
        <Text className="text-2xl font-bold text-foreground">Meus Chamados</Text>
        <Text className="text-muted text-sm mt-1">
          {calls.length} chamado{calls.length !== 1 ? "s" : ""} no total
        </Text>
      </View>

      {/* Filtros */}
      <View className="flex-row mb-4 gap-2">
        {[
          { id: "todos" as FilterType, label: "Todos" },
          { id: "pendentes" as FilterType, label: "Pendentes" },
          { id: "concluidos" as FilterType, label: "Concluídos" },
        ].map((f) => (
          <TouchableOpacity
            key={f.id}
            onPress={() => handleFilterPress(f.id)}
            activeOpacity={0.7}
            className="px-4 py-2 rounded-full"
            style={{
              backgroundColor: filter === f.id ? colors.primary : colors.surface,
              borderWidth: 1,
              borderColor: filter === f.id ? colors.primary : colors.border,
            }}
          >
            <Text
              className="font-medium"
              style={{
                color: filter === f.id ? "#FFFFFF" : colors.foreground,
              }}
            >
              {f.label}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      {/* Lista */}
      {filteredCalls.length === 0 ? (
        <View className="flex-1 items-center justify-center">
          <IconSymbol name="info" size={48} color={colors.muted} />
          <Text className="text-muted text-center mt-4 text-base">
            {filter === "todos"
              ? "Nenhum chamado ainda."
              : filter === "pendentes"
              ? "Nenhum chamado pendente."
              : "Nenhum chamado concluído."}
          </Text>
        </View>
      ) : (
        <FlatList
          data={filteredCalls}
          renderItem={renderCallItem}
          keyExtractor={(item) => item.id}
          showsVerticalScrollIndicator={false}
          contentContainerStyle={{ paddingBottom: 20 }}
        />
      )}
    </ScreenContainer>
  );
}
