import { TAB_COLORS } from "@/src/constants/colors";
import { useMonthBalance, useCarryOver } from "@/src/hooks/useTransactions";
import { currentMonthStr, addMonths, monthLabel } from "@/src/utils/date";
import { formatEur } from "@/src/utils/format";
import { Ionicons } from "@expo/vector-icons";
import { Alert, Pressable, Text, View } from "react-native";
import { useTranslation } from "react-i18next";

type Props = {
  month: string;      // "YYYY-MM" — the displayed (past) month
  scope: "household" | "private" | "child";
  childId?: string;
  accentColor?: string;
};

export function CarryOverBanner({ month, scope, childId, accentColor = TAB_COLORS.household }: Props) {
  const isCurrent = month >= currentMonthStr();

  // Don't show for current or future months
  if (isCurrent) return null;

  return (
    <CarryOverBannerInner
      month={month}
      scope={scope}
      childId={childId}
      accentColor={accentColor}
    />
  );
}

function CarryOverBannerInner({
  month,
  scope,
  childId,
  accentColor,
}: Required<Pick<Props, "month" | "scope" | "accentColor">> & { childId?: string }) {
  const { data: balanceData } = useMonthBalance(scope, month, childId);
  const { mutate: carryOver, isPending } = useCarryOver();
  const { t } = useTranslation();

  const balance = balanceData?.balance ?? 0;

  // No banner if balance is ~zero
  if (Math.abs(balance) < 0.01) return null;

  const toMonth = addMonths(month, 1);
  const toMonthLabel = monthLabel(toMonth);
  const balanceLabel = balance > 0 ? `+${formatEur(balance)}` : `-${formatEur(balance)}`;
  const isPositive = balance > 0;

  function handleCarryOver() {
    Alert.alert(
      t('carryOver.title'),
      t('carryOver.confirmMessage', {
        balance: balanceLabel,
        type: isPositive ? t('carryOver.expense') : t('carryOver.income'),
        month: toMonthLabel,
      }),
      [
        { text: t('common.cancel'), style: "cancel" },
        {
          text: t('carryOver.transfer'),
          onPress: () => {
            carryOver(
              { fromMonth: month, toMonth, scope, childId },
              {
                onError: (err) => {
                  Alert.alert(t('common.notice'), err.message);
                },
              },
            );
          },
        },
      ],
    );
  }

  return (
    <View
      className="mx-4 my-3 rounded-2xl p-4"
      style={{ backgroundColor: "#f5f3ff", borderWidth: 1, borderColor: "#ddd6fe" }}
    >
      <View className="flex-row items-center gap-3">
        <Ionicons name="return-down-forward-outline" size={24} color="#6366f1" />
        <View className="flex-1">
          <Text className="text-xs text-gray-400 mb-0.5">{t('carryOver.openBalance', { month: monthLabel(month) })}</Text>
          <Text className="text-xl font-bold" style={{ color: "#6366f1" }}>
            {balanceLabel}
          </Text>
        </View>
      </View>
      <Pressable
        onPress={handleCarryOver}
        disabled={isPending}
        className="mt-3 py-2 rounded-xl items-center active:opacity-70"
        style={{ backgroundColor: "#6366f1" }}
      >
        <Text className="text-sm font-semibold text-white">
          {isPending ? t('carryOver.transferring') : t('carryOver.transferButton', { month: toMonthLabel })}
        </Text>
      </Pressable>
    </View>
  );
}
