import { Ionicons } from "@expo/vector-icons";
import type { ComponentProps } from "react";
import { Alert, Pressable, Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable";
import Reanimated, { useAnimatedStyle } from "react-native-reanimated";
import type { SharedValue } from "react-native-reanimated";
import type { TransactionWithCategory } from "@/src/hooks/useTransactions";

type IoniconName = ComponentProps<typeof Ionicons>["name"];

const CATEGORY_ICONS: Record<string, IoniconName> = {
  "Lebensmittel": "cart-outline",
  "Wohnen": "home-outline",
  "Transport": "car-outline",
  "Gesundheit": "medkit-outline",
  "Freizeit": "game-controller-outline",
  "Kinder": "happy-outline",
  "Urlaub": "airplane-outline",
  "Sonstiges": "ellipsis-horizontal-circle-outline",
  "Gehalt": "briefcase-outline",
  "Sonstiges Einkommen": "cash-outline",
};

function resolveIcon(categoryName: string | null, isIncome: boolean): IoniconName {
  if (categoryName && CATEGORY_ICONS[categoryName]) return CATEGORY_ICONS[categoryName];
  return isIncome ? "cash-outline" : "ellipsis-horizontal-circle-outline";
}

type Props = {
  transaction: TransactionWithCategory;
  onPress: (t: TransactionWithCategory) => void;
  onDelete: (t: TransactionWithCategory) => void;
  locked?: boolean;
};

function formatAmount(amount: string, type: "income" | "expense") {
  const num = parseFloat(amount);
  const formatted = new Intl.NumberFormat("de-DE", {
    style: "currency",
    currency: "EUR",
  }).format(num);
  return type === "income" ? `+${formatted}` : `-${formatted}`;
}

function formatDate(dateStr: string) {
  const date = new Date(dateStr);
  return new Intl.DateTimeFormat("de-DE", { day: "2-digit", month: "short" }).format(date);
}

function DeleteAction({
  prog,
  drag,
  onDelete,
}: {
  prog: SharedValue<number>;
  drag: SharedValue<number>;
  onDelete: () => void;
}) {
  const { t } = useTranslation();
  const animStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: drag.value + 80 }],
  }));

  return (
    <Reanimated.View
      style={[{ width: 80, backgroundColor: "#dc2626", justifyContent: "center", alignItems: "center" }, animStyle]}
    >
      <Pressable
        onPress={onDelete}
        style={{ flex: 1, width: "100%", justifyContent: "center", alignItems: "center" }}
      >
        <Ionicons name="trash-outline" size={20} color="#fff" />
        <Text style={{ color: "#fff", fontSize: 11, marginTop: 3, fontWeight: "600" }}>{t('common.delete')}</Text>
      </Pressable>
    </Reanimated.View>
  );
}

export function TransactionItem({ transaction, onPress, onDelete, locked = false }: Props) {
  const { t } = useTranslation();
  const isIncome = transaction.type === "income";
  const isCarryOver = transaction.isCarryOver;

  const iconName: IoniconName = isCarryOver
    ? "return-down-forward-outline"
    : resolveIcon(transaction.categoryName, isIncome);
  const iconColor = isCarryOver ? "#6366f1" : (transaction.categoryColor ?? "#6b7280");
  const bgColor = isCarryOver ? "#6366f122" : (transaction.categoryColor ?? "#6b7280") + "22";

  function handleDeletePress() {
    const isFixed = transaction.isFixed;
    const hasDebt = (transaction as TransactionWithCategory & { linkedDebtPaymentId?: string | null }).linkedDebtPaymentId;

    let message = t('transaction.deleteMessage');
    if (isFixed) message = t('transaction.deleteFixed');
    if (hasDebt) message = t('transaction.deleteDebt');

    Alert.alert(t('transaction.deleteTitle'), message, [
      { text: t('common.cancel'), style: "cancel" },
      { text: t('common.delete'), style: "destructive", onPress: () => onDelete(transaction) },
    ]);
  }

  // CarryOver: kein Swipe, kein Edit
  if (isCarryOver) {
    return (
      <Pressable className="flex-row items-center px-4 py-3 active:bg-gray-50">
        <View style={{ width: 40, height: 40, borderRadius: 20, backgroundColor: bgColor, alignItems: "center", justifyContent: "center", marginRight: 12 }}>
          <Ionicons name={iconName} size={20} color={iconColor} />
        </View>
        <View className="flex-1">
          <Text className="text-sm font-medium" style={{ color: "#6366f1" }} numberOfLines={1}>
            {transaction.description ?? t('transaction.carryOver')}
          </Text>
          <Text className="text-xs text-gray-400 mt-0.5">{formatDate(transaction.date)}</Text>
        </View>
        <Text className="text-sm font-semibold text-indigo-500">
          {formatAmount(transaction.amount, transaction.type)}
        </Text>
      </Pressable>
    );
  }

  // Locked months: no swipe, no edit — just display
  if (locked) {
    return (
      <View className="flex-row items-center px-4 py-3 bg-white">
        <View style={{ width: 40, height: 40, borderRadius: 20, backgroundColor: bgColor, alignItems: "center", justifyContent: "center", marginRight: 12 }}>
          <Ionicons name={iconName} size={20} color={iconColor} />
        </View>
        <View className="flex-1">
          <Text className="text-sm font-medium text-gray-900" numberOfLines={1}>
            {transaction.description ?? transaction.categoryName ?? "Buchung"}
          </Text>
          <Text className="text-xs text-gray-400 mt-0.5">
            {transaction.categoryName ? `${transaction.categoryName}  ·  ` : ""}
            {formatDate(transaction.date)}
          </Text>
        </View>
        <Text className={`text-sm font-semibold ${isIncome ? "text-green-600" : "text-gray-900"}`}>
          {formatAmount(transaction.amount, transaction.type)}
        </Text>
      </View>
    );
  }

  return (
    <ReanimatedSwipeable
      friction={2}
      rightThreshold={40}
      renderRightActions={(prog, drag) => (
        <DeleteAction prog={prog} drag={drag} onDelete={handleDeletePress} />
      )}
    >
      <Pressable
        onPress={() => onPress(transaction)}
        className="flex-row items-center px-4 py-3 active:bg-gray-50 bg-white"
      >
        <View style={{ width: 40, height: 40, borderRadius: 20, backgroundColor: bgColor, alignItems: "center", justifyContent: "center", marginRight: 12 }}>
          <Ionicons name={iconName} size={20} color={iconColor} />
        </View>
        <View className="flex-1">
          <Text className="text-sm font-medium text-gray-900" numberOfLines={1}>
            {transaction.description ?? transaction.categoryName ?? "Buchung"}
          </Text>
          <Text className="text-xs text-gray-400 mt-0.5">
            {transaction.categoryName ? `${transaction.categoryName}  ·  ` : ""}
            {formatDate(transaction.date)}
          </Text>
        </View>
        <Text className={`text-sm font-semibold ${isIncome ? "text-green-600" : "text-gray-900"}`}>
          {formatAmount(transaction.amount, transaction.type)}
        </Text>
      </Pressable>
    </ReanimatedSwipeable>
  );
}
