import { TAB_COLORS } from "@/src/constants/colors";
import { QuickAddModal } from "./QuickAddModal";
import { MonthSummaryHeader } from "./MonthSummaryHeader";
import { TransactionItem } from "./TransactionItem";
import { EditTransactionModal } from "./EditTransactionModal";
import { CarryOverBanner } from "./CarryOverBanner";
import { AddCategoryModal } from "@/src/components/features/categories/AddCategoryModal";
import { EmptyState } from "@/src/components/ui/EmptyState";
import { useTransactions, useMonthBalance, useActivateFixed, useDeleteTransaction } from "@/src/hooks/useTransactions";
import type { TransactionWithCategory } from "@/src/hooks/useTransactions";
import type { Category } from "@/src/hooks/useCategories";
import { currentMonthStr, addMonths, monthLabel, monthDateRange } from "@/src/utils/date";
import { Ionicons } from "@expo/vector-icons";
import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import {
  ActivityIndicator,
  FlatList,
  Pressable,
  RefreshControl,
  Text,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

type FilterType = "all" | "income" | "expense";
type Scope = "household" | "private" | "child";

type Props = {
  scope: Scope;
  childId?: string;
  accentColor?: string;
  emptyTitle?: string;
  emptySubtitle?: string;
  disableTopInset?: boolean;
  headerExtra?: React.ReactNode;
};

const ACCENT_COLORS: Record<Scope, string> = {
  household: TAB_COLORS.household,
  private: TAB_COLORS.private,
  child: TAB_COLORS.children,
};

export function TransactionScreen({
  scope,
  childId,
  accentColor,
  emptyTitle,
  emptySubtitle,
  disableTopInset = false,
  headerExtra,
}: Props) {
  const insets = useSafeAreaInsets();
  const { t } = useTranslation();
  const resolvedEmptyTitle = emptyTitle ?? t('household.noTransactions');
  const resolvedEmptySubtitle = emptySubtitle ?? t('household.noTransactionsHint');
  const [filter, setFilter] = useState<FilterType>("all");
  const [month, setMonth] = useState(currentMonthStr());
  const [showAddModal, setShowAddModal] = useState(false);
  const [showAddCategory, setShowAddCategory] = useState(false);
  const [addCategoryType, setAddCategoryType] = useState<"expense" | "income">("expense");
  const [newCategory, setNewCategory] = useState<Category | null>(null);
  const [editTransaction, setEditTransaction] = useState<TransactionWithCategory | null>(null);
  const { mutate: deleteTransaction } = useDeleteTransaction();

  const color = accentColor ?? ACCENT_COLORS[scope];
  const isCurrent = month === currentMonthStr();

  // 11a: activate fixed transactions silently on mount + when month changes to current
  const { mutate: activateFixed } = useActivateFixed();
  useEffect(() => {
    if (isCurrent) {
      activateFixed({ month, scope, ...(childId ? { childId } : {}) });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [month, scope, childId]);

  const [fromDate, toDate] = monthDateRange(month);

  const transactionFilter = {
    scope,
    from: fromDate,
    to: toDate,
    ...(childId ? { childId } : {}),
    ...(filter !== "all" ? { type: filter as "income" | "expense" } : {}),
  };

  const { data: transactions = [], isLoading, refetch, isRefetching } = useTransactions(transactionFilter);
  const { data: balance, isLoading: balanceLoading } = useMonthBalance(scope, month, childId);

  function renderEmpty() {
    if (isLoading) {
      return (
        <View className="flex-1 items-center justify-center py-20">
          <ActivityIndicator size="large" color={color} />
        </View>
      );
    }
    return (
      <EmptyState
        icon="wallet-outline"
        title={resolvedEmptyTitle}
        subtitle={resolvedEmptySubtitle}
      />
    );
  }

  return (
    <View className="flex-1 bg-gray-50">
      {/* Neutral header — paddingTop for safe area when used as top-level screen */}
      <View style={{ backgroundColor: "#fff", borderBottomWidth: 1, borderBottomColor: "#f3f4f6", paddingTop: disableTopInset ? 0 : insets.top }}>
        {/* Month Switcher */}
        <View className="flex-row items-center justify-center gap-4 py-3">
          <Pressable onPress={() => setMonth((m) => addMonths(m, -1))} className="p-1 active:opacity-50">
            <Ionicons name="chevron-back" size={18} color="#6b7280" />
          </Pressable>
          <Text className="text-sm font-semibold w-32 text-center text-gray-800">
            {monthLabel(month)}
          </Text>
          <Pressable
            onPress={() => setMonth((m) => addMonths(m, 1))}
            disabled={isCurrent}
            className="p-1 active:opacity-50"
            style={{ opacity: isCurrent ? 0.3 : 1 }}
          >
            <Ionicons name="chevron-forward" size={18} color="#6b7280" />
          </Pressable>
        </View>
      </View>

      {headerExtra}

      <MonthSummaryHeader
        income={balance?.income}
        expense={balance?.expense}
        balance={balance?.balance}
        isLoading={balanceLoading}
        accentColor={color}
      />

      {/* Filter Bar */}
      <View className="flex-row px-4 py-3 gap-2 bg-white border-b border-gray-100 mt-3">
        {(["all", "expense", "income"] as const).map((f) => (
          <Pressable
            key={f}
            onPress={() => setFilter(f)}
            style={{ backgroundColor: filter === f ? color : "#f3f4f6" }}
            className="px-4 py-1.5 rounded-full"
          >
            <Text
              className="text-sm font-medium"
              style={{ color: filter === f ? "#fff" : "#4b5563" }}
            >
              {f === "all" ? t('household.all') : f === "expense" ? t('household.expenses') : t('household.income')}
            </Text>
          </Pressable>
        ))}
      </View>

      {/* List */}
      <FlatList
        data={transactions}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <View className="bg-white">
            <TransactionItem
              transaction={item}
              onPress={setEditTransaction}
              onDelete={(t) => deleteTransaction(t.id)}
            />
          </View>
        )}
        ListHeaderComponent={
          !isCurrent ? (
            <CarryOverBanner month={month} scope={scope} childId={childId} />
          ) : null
        }
        ListEmptyComponent={renderEmpty}
        refreshControl={
          <RefreshControl refreshing={isRefetching} onRefresh={() => void refetch()} tintColor={color} />
        }
        ItemSeparatorComponent={() => <View className="h-px bg-gray-50 ml-16" />}
        contentContainerStyle={transactions.length === 0 ? { flex: 1 } : undefined}
      />


      {/* FAB */}
      <Pressable
        onPress={() => setShowAddModal(true)}
        style={{ backgroundColor: color }}
        className="absolute bottom-6 right-6 w-14 h-14 rounded-full items-center justify-center shadow-lg active:opacity-80"
      >
        <Ionicons name="add" size={28} color="#fff" />
      </Pressable>

      <QuickAddModal
        visible={showAddModal}
        onClose={() => { setShowAddModal(false); setNewCategory(null); }}
        onRequestAddCategory={(t) => { setAddCategoryType(t); setShowAddModal(false); setShowAddCategory(true); }}
        newCategory={newCategory}
        defaultScope={scope}
        defaultChildId={childId}
      />
      <AddCategoryModal
        visible={showAddCategory}
        onClose={() => { setShowAddCategory(false); setShowAddModal(true); }}
        defaultType={addCategoryType}
        onCreated={(cat) => { setNewCategory(cat); setShowAddCategory(false); setShowAddModal(true); }}
      />
      {editTransaction && (
        <EditTransactionModal
          transaction={editTransaction}
          onClose={() => setEditTransaction(null)}
        />
      )}
    </View>
  );
}
