import { Text, View, TouchableOpacity, ScrollView } from "react-native";
import { useRouter, useLocalSearchParams } from "expo-router";

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,
  getPriorityLabel,
  getPriorityColor,
  STATUSES,
  Status,
} from "@/lib/types";

const STATUS_ORDER: Status[] = ['aberto', 'em_analise', 'em_execucao', 'concluido'];

export default function CallDetailsScreen() {
  const router = useRouter();
  const colors = useColors();
  const { id } = useLocalSearchParams<{ id: string }>();
  const { getCallById } = useCalls();

  const call = getCallById(id || "");

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

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

  function getStatusIndex(status: Status): number {
    return STATUS_ORDER.indexOf(status);
  }

  if (!call) {
    return (
      <ScreenContainer edges={["top", "left", "right", "bottom"]} className="p-4">
        <View className="flex-row items-center mb-6">
          <TouchableOpacity onPress={handleClose} activeOpacity={0.7} className="p-2 -ml-2">
            <IconSymbol name="arrow-back" size={28} color={colors.foreground} />
          </TouchableOpacity>
        </View>
        <View className="flex-1 items-center justify-center">
          <Text className="text-muted text-lg">Chamado não encontrado</Text>
        </View>
      </ScreenContainer>
    );
  }

  const currentStatusIndex = getStatusIndex(call.status);
  const isCancelled = call.status === 'cancelado';

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

      <ScrollView showsVerticalScrollIndicator={false} className="flex-1">
        {/* Card Principal */}
        <View className="bg-surface rounded-2xl p-5 border border-border mb-6">
          {/* Categoria e Status */}
          <View className="flex-row items-center justify-between mb-4">
            <View className="flex-row items-center">
              <View
                className="w-14 h-14 rounded-full items-center justify-center mr-3"
                style={{ backgroundColor: colors.primary + "20" }}
              >
                <IconSymbol
                  name={getCategoryIcon(call.category) as any}
                  size={28}
                  color={colors.primary}
                />
              </View>
              <View>
                <Text className="text-lg font-bold text-foreground">
                  {getCategoryLabel(call.category)}
                </Text>
                <Text className="text-muted text-sm">{call.unit}</Text>
              </View>
            </View>
            <View
              className="px-4 py-2 rounded-full"
              style={{ backgroundColor: getStatusColor(call.status) + "20" }}
            >
              <Text
                className="font-semibold"
                style={{ color: getStatusColor(call.status) }}
              >
                {getStatusLabel(call.status)}
              </Text>
            </View>
          </View>

          {/* Prioridade */}
          <View className="flex-row items-center mb-4">
            <IconSymbol name="flag" size={20} color={getPriorityColor(call.priority)} />
            <Text className="text-foreground ml-2">
              Prioridade:{" "}
              <Text style={{ color: getPriorityColor(call.priority), fontWeight: "600" }}>
                {getPriorityLabel(call.priority)}
              </Text>
            </Text>
          </View>

          {/* Descrição */}
          <View className="bg-background rounded-xl p-4 mb-4">
            <Text className="text-muted text-sm mb-1">Descrição do problema:</Text>
            <Text className="text-foreground text-base">{call.description}</Text>
          </View>

          {/* Data */}
          <View className="flex-row items-center">
            <IconSymbol name="schedule" size={18} color={colors.muted} />
            <Text className="text-muted text-sm ml-2">
              Aberto em: {formatDate(call.createdAt)}
            </Text>
          </View>
        </View>

        {/* Timeline de Status */}
        <View className="mb-6">
          <Text className="text-lg font-semibold text-foreground mb-4">
            Progresso do Chamado
          </Text>

          {isCancelled ? (
            <View className="bg-surface rounded-xl p-4 border border-border items-center">
              <IconSymbol name="cancel" size={48} color={colors.error} />
              <Text className="text-error font-semibold mt-2">Chamado Cancelado</Text>
            </View>
          ) : (
            <View className="bg-surface rounded-xl p-4 border border-border">
              {STATUS_ORDER.map((status, index) => {
                const statusInfo = STATUSES.find((s) => s.id === status);
                const isCompleted = index <= currentStatusIndex;
                const isCurrent = index === currentStatusIndex;

                return (
                  <View key={status} className="flex-row">
                    {/* Linha e Círculo */}
                    <View className="items-center mr-4">
                      <View
                        className="w-8 h-8 rounded-full items-center justify-center"
                        style={{
                          backgroundColor: isCompleted
                            ? statusInfo?.color
                            : colors.border,
                        }}
                      >
                        {isCompleted ? (
                          <IconSymbol name="check-circle" size={20} color="#FFFFFF" />
                        ) : (
                          <View className="w-3 h-3 rounded-full bg-muted" />
                        )}
                      </View>
                      {index < STATUS_ORDER.length - 1 && (
                        <View
                          className="w-1 flex-1 min-h-[40px]"
                          style={{
                            backgroundColor: index < currentStatusIndex
                              ? statusInfo?.color
                              : colors.border,
                          }}
                        />
                      )}
                    </View>

                    {/* Conteúdo */}
                    <View className="flex-1 pb-4">
                      <Text
                        className="font-semibold text-base"
                        style={{
                          color: isCompleted ? colors.foreground : colors.muted,
                        }}
                      >
                        {statusInfo?.label}
                      </Text>
                      {isCurrent && (
                        <Text className="text-muted text-sm mt-1">
                          Status atual
                        </Text>
                      )}
                    </View>
                  </View>
                );
              })}
            </View>
          )}
        </View>

        {/* Histórico */}
        <View className="mb-6">
          <Text className="text-lg font-semibold text-foreground mb-4">
            Histórico de Atualizações
          </Text>
          <View className="bg-surface rounded-xl border border-border">
            {call.history.map((update, index) => (
              <View
                key={update.id}
                className="p-4"
                style={{
                  borderBottomWidth: index < call.history.length - 1 ? 1 : 0,
                  borderBottomColor: colors.border,
                }}
              >
                <View className="flex-row items-center justify-between mb-1">
                  <View
                    className="px-3 py-1 rounded-full"
                    style={{ backgroundColor: getStatusColor(update.status) + "20" }}
                  >
                    <Text
                      className="text-xs font-semibold"
                      style={{ color: getStatusColor(update.status) }}
                    >
                      {getStatusLabel(update.status)}
                    </Text>
                  </View>
                  <Text className="text-muted text-xs">
                    {formatDate(update.timestamp)}
                  </Text>
                </View>
                {update.comment && (
                  <Text className="text-foreground text-sm mt-2">{update.comment}</Text>
                )}
              </View>
            ))}
          </View>
        </View>
      </ScrollView>
    </ScreenContainer>
  );
}
