import { useState } from "react";
import {
  Text,
  View,
  TouchableOpacity,
  FlatList,
  ActivityIndicator,
  Modal,
  Alert,
  TextInput,
} 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,
  getPriorityLabel,
  getPriorityColor,
  PRIORITIES,
  STATUSES,
  UNITS,
  Priority,
  Status,
} from "@/lib/types";
import type { MaintenanceCall } from "@/lib/types";

export default function MaintenanceScreen() {
  const router = useRouter();
  const colors = useColors();
  const { calls, isLoading, getPendingCalls, updateStatus, updatePriority } = useCalls();

  const [filterUnit, setFilterUnit] = useState<string>("Todas");
  const [showUnitFilter, setShowUnitFilter] = useState(false);
  const [selectedCall, setSelectedCall] = useState<MaintenanceCall | null>(null);
  const [showActionModal, setShowActionModal] = useState(false);
  const [comment, setComment] = useState("");

  const pendingCalls = getPendingCalls();
  const filteredCalls =
    filterUnit === "Todas"
      ? pendingCalls
      : pendingCalls.filter((c) => c.unit === filterUnit);

  // Ordenar por prioridade (urgente primeiro)
  const sortedCalls = [...filteredCalls].sort((a, b) => {
    const priorityOrder: Record<Priority, number> = {
      urgente: 0,
      alta: 1,
      media: 2,
      baixa: 3,
    };
    return priorityOrder[a.priority] - priorityOrder[b.priority];
  });

  function handleCallPress(call: MaintenanceCall) {
    if (Platform.OS !== "web") {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    }
    setSelectedCall(call);
    setShowActionModal(true);
    setComment("");
  }

  function handleViewDetails() {
    if (selectedCall) {
      setShowActionModal(false);
      router.push({ pathname: "/call-details", params: { id: selectedCall.id } });
    }
  }

  async function handleUpdatePriority(priority: Priority) {
    if (!selectedCall) return;
    if (Platform.OS !== "web") {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
    }
    await updatePriority(selectedCall.id, priority);
    setSelectedCall({ ...selectedCall, priority });
    Alert.alert("Prioridade Atualizada", `Prioridade alterada para ${getPriorityLabel(priority)}`);
  }

  async function handleUpdateStatus(status: Status) {
    if (!selectedCall) return;
    if (Platform.OS !== "web") {
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
    }
    await updateStatus(selectedCall.id, status, comment || undefined);
    setShowActionModal(false);
    setSelectedCall(null);
    setComment("");
    Alert.alert("Status Atualizado", `Chamado atualizado para ${getStatusLabel(status)}`);
  }

  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-l-4"
        style={{
          borderColor: priorityColor,
          borderRightWidth: 1,
          borderTopWidth: 1,
          borderBottomWidth: 1,
          borderRightColor: colors.border,
          borderTopColor: colors.border,
          borderBottomColor: colors.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">
              <View className="flex-row items-center">
                <Text className="text-foreground font-semibold text-base" numberOfLines={1}>
                  {getCategoryLabel(item.category)}
                </Text>
                <View
                  className="ml-2 px-2 py-0.5 rounded"
                  style={{ backgroundColor: priorityColor + "20" }}
                >
                  <Text style={{ color: priorityColor }} className="text-xs font-bold">
                    {getPriorityLabel(item.priority).toUpperCase()}
                  </Text>
                </View>
              </View>
              <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"
              style={{ backgroundColor: statusColor + "20" }}
            >
              <Text style={{ color: statusColor }} className="text-xs font-semibold">
                {getStatusLabel(item.status)}
              </Text>
            </View>
          </View>
        </View>
        <Text className="text-muted text-sm mt-2" numberOfLines={2}>
          {item.description}
        </Text>
      </TouchableOpacity>
    );
  }

  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">Manutenção</Text>
        <Text className="text-muted text-sm mt-1">
          {pendingCalls.length} chamado{pendingCalls.length !== 1 ? "s" : ""} pendente
          {pendingCalls.length !== 1 ? "s" : ""}
        </Text>
      </View>

      {/* Filtro por Unidade */}
      <TouchableOpacity
        onPress={() => setShowUnitFilter(true)}
        activeOpacity={0.7}
        className="flex-row items-center justify-between bg-surface rounded-xl p-4 mb-4 border border-border"
      >
        <View className="flex-row items-center">
          <IconSymbol name="location-on" size={20} color={colors.primary} />
          <Text className="text-foreground font-medium ml-2">Unidade: {filterUnit}</Text>
        </View>
        <IconSymbol name="chevron-right" size={20} color={colors.muted} />
      </TouchableOpacity>

      {/* Lista */}
      {sortedCalls.length === 0 ? (
        <View className="flex-1 items-center justify-center">
          <IconSymbol name="check-circle" size={64} color={colors.success} />
          <Text className="text-foreground text-lg font-semibold mt-4">Tudo em dia!</Text>
          <Text className="text-muted text-center mt-2">
            {filterUnit === "Todas"
              ? "Não há chamados pendentes."
              : `Não há chamados pendentes em ${filterUnit}.`}
          </Text>
        </View>
      ) : (
        <FlatList
          data={sortedCalls}
          renderItem={renderCallItem}
          keyExtractor={(item) => item.id}
          showsVerticalScrollIndicator={false}
          contentContainerStyle={{ paddingBottom: 20 }}
        />
      )}

      {/* Modal de Filtro de Unidade */}
      <Modal visible={showUnitFilter} transparent animationType="slide">
        <View className="flex-1 justify-end" style={{ backgroundColor: "rgba(0,0,0,0.5)" }}>
          <View
            className="rounded-t-3xl p-6"
            style={{ backgroundColor: colors.background }}
          >
            <View className="flex-row items-center justify-between mb-4">
              <Text className="text-xl font-bold text-foreground">Filtrar por Unidade</Text>
              <TouchableOpacity onPress={() => setShowUnitFilter(false)}>
                <IconSymbol name="close" size={24} color={colors.foreground} />
              </TouchableOpacity>
            </View>
            <TouchableOpacity
              onPress={() => {
                setFilterUnit("Todas");
                setShowUnitFilter(false);
              }}
              className="py-4 border-b border-border"
            >
              <Text
                className="text-lg"
                style={{
                  color: filterUnit === "Todas" ? colors.primary : colors.foreground,
                  fontWeight: filterUnit === "Todas" ? "600" : "400",
                }}
              >
                Todas as Unidades
              </Text>
            </TouchableOpacity>
            {UNITS.map((unit) => (
              <TouchableOpacity
                key={unit}
                onPress={() => {
                  setFilterUnit(unit);
                  setShowUnitFilter(false);
                }}
                className="py-4 border-b border-border"
              >
                <Text
                  className="text-lg"
                  style={{
                    color: filterUnit === unit ? colors.primary : colors.foreground,
                    fontWeight: filterUnit === unit ? "600" : "400",
                  }}
                >
                  {unit}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      </Modal>

      {/* Modal de Ações do Chamado */}
      <Modal visible={showActionModal} transparent animationType="slide">
        <View className="flex-1 justify-end" style={{ backgroundColor: "rgba(0,0,0,0.5)" }}>
          <View
            className="rounded-t-3xl p-6 max-h-[90%]"
            style={{ backgroundColor: colors.background }}
          >
            <View className="flex-row items-center justify-between mb-4">
              <Text className="text-xl font-bold text-foreground">Gerenciar Chamado</Text>
              <TouchableOpacity onPress={() => setShowActionModal(false)}>
                <IconSymbol name="close" size={24} color={colors.foreground} />
              </TouchableOpacity>
            </View>

            {selectedCall && (
              <>
                {/* Info do Chamado */}
                <View className="bg-surface rounded-xl p-4 mb-4 border border-border">
                  <Text className="text-foreground font-semibold">
                    {getCategoryLabel(selectedCall.category)}
                  </Text>
                  <Text className="text-muted text-sm">{selectedCall.unit}</Text>
                  <Text className="text-muted text-sm mt-2" numberOfLines={2}>
                    {selectedCall.description}
                  </Text>
                </View>

                {/* Prioridade */}
                <Text className="text-foreground font-semibold mb-2">Definir Prioridade:</Text>
                <View className="flex-row flex-wrap gap-2 mb-4">
                  {PRIORITIES.map((p) => (
                    <TouchableOpacity
                      key={p.id}
                      onPress={() => handleUpdatePriority(p.id)}
                      className="px-4 py-2 rounded-full"
                      style={{
                        backgroundColor:
                          selectedCall.priority === p.id ? p.color : colors.surface,
                        borderWidth: 1,
                        borderColor: p.color,
                      }}
                    >
                      <Text
                        style={{
                          color: selectedCall.priority === p.id ? "#FFFFFF" : p.color,
                          fontWeight: "600",
                        }}
                      >
                        {p.label}
                      </Text>
                    </TouchableOpacity>
                  ))}
                </View>

                {/* Comentário */}
                <Text className="text-foreground font-semibold mb-2">Comentário (opcional):</Text>
                <TextInput
                  value={comment}
                  onChangeText={setComment}
                  placeholder="Adicione um comentário..."
                  placeholderTextColor={colors.muted}
                  multiline
                  className="bg-surface border border-border rounded-xl p-3 mb-4"
                  style={{ color: colors.foreground, minHeight: 60 }}
                />

                {/* Atualizar Status */}
                <Text className="text-foreground font-semibold mb-2">Atualizar Status:</Text>
                <View className="gap-2 mb-4">
                  {STATUSES.filter((s) => s.id !== "aberto").map((s) => (
                    <TouchableOpacity
                      key={s.id}
                      onPress={() => handleUpdateStatus(s.id)}
                      className="flex-row items-center p-4 rounded-xl"
                      style={{ backgroundColor: s.color + "20" }}
                    >
                      <View
                        className="w-3 h-3 rounded-full mr-3"
                        style={{ backgroundColor: s.color }}
                      />
                      <Text style={{ color: s.color }} className="font-semibold">
                        {s.label}
                      </Text>
                    </TouchableOpacity>
                  ))}
                </View>

                {/* Ver Detalhes */}
                <TouchableOpacity
                  onPress={handleViewDetails}
                  className="flex-row items-center justify-center p-4 rounded-xl border border-border"
                >
                  <IconSymbol name="info" size={20} color={colors.primary} />
                  <Text className="text-primary font-semibold ml-2">Ver Detalhes Completos</Text>
                </TouchableOpacity>
              </>
            )}
          </View>
        </View>
      </Modal>
    </ScreenContainer>
  );
}
