import { Ionicons } from "@expo/vector-icons";
import { useState } from "react";
import { ActivityIndicator, Pressable, Text, View } from "react-native";
import { useDebts, useDeleteDebt, type Debt } from "@/src/hooks/useDebts";
import { DebtCard } from "./DebtCard";
import { AddDebtModal } from "./AddDebtModal";
import { AddDebtPaymentModal } from "./AddDebtPaymentModal";
import { useTranslation } from "react-i18next";

type ModalState =
  | { kind: "idle" }
  | { kind: "addDebt" }
  | { kind: "addPayment"; debt: Debt };

export function DebtsSection() {
  const { data: debts = [], isLoading } = useDebts();
  const { mutate: deleteDebt } = useDeleteDebt();
  const [modal, setModal] = useState<ModalState>({ kind: "idle" });
  const [showClosed, setShowClosed] = useState(false);
  const { t } = useTranslation();

  const openDebts = debts.filter((d) => d.closedAt === null);
  const closedDebts = debts.filter((d) => d.closedAt !== null);

  function handleDelete(debt: Debt) {
    deleteDebt(debt.id);
  }

  return (
    <>
      <View className="mb-2">
        {/* Section header */}
        <View className="flex-row items-center justify-between px-4 py-3">
          <View className="flex-row items-center gap-2">
            <Ionicons name="card-outline" size={18} color="#7c3aed" />
            <Text className="text-sm font-semibold text-gray-800">{t('debts.title')}</Text>
          </View>
          <Pressable
            onPress={() => setModal({ kind: "addDebt" })}
            className="flex-row items-center gap-1 px-3 py-1.5 rounded-full"
            style={{ backgroundColor: "#ede9fe" }}
          >
            <Ionicons name="add" size={14} color="#7c3aed" />
            <Text className="text-xs font-semibold" style={{ color: "#7c3aed" }}>{t('common.new')}</Text>
          </Pressable>
        </View>

        {/* Content */}
        {isLoading ? (
          <View className="py-6 items-center">
            <ActivityIndicator size="small" color="#7c3aed" />
          </View>
        ) : openDebts.length === 0 && closedDebts.length === 0 ? (
          <View className="mx-4 mb-3 p-4 bg-gray-50 rounded-2xl items-center">
            <Text className="text-sm text-gray-400 text-center">
              {t('debts.noDebtsEntered')}
            </Text>
          </View>
        ) : (
          <>
            {openDebts.map((debt) => (
              <DebtCard
                key={debt.id}
                debt={debt}
                onAddPayment={(d) => setModal({ kind: "addPayment", debt: d })}
                onDelete={handleDelete}
              />
            ))}

            {closedDebts.length > 0 && (
              <Pressable
                onPress={() => setShowClosed((v) => !v)}
                className="flex-row items-center gap-1 mx-4 mb-2"
              >
                <Text className="text-xs text-gray-400">
                  {t(showClosed ? 'debts.toggleClosed_hide' : 'debts.toggleClosed_show', { count: closedDebts.length, plural: closedDebts.length === 1 ? '' : 'r' })}
                </Text>
                <Ionicons
                  name={showClosed ? "chevron-up" : "chevron-down"}
                  size={12}
                  color="#9ca3af"
                />
              </Pressable>
            )}

            {showClosed &&
              closedDebts.map((debt) => (
                <DebtCard
                  key={debt.id}
                  debt={debt}
                  onAddPayment={() => {}}
                  onDelete={handleDelete}
                />
              ))}
          </>
        )}
      </View>

      {/* Modals — only one open at a time */}
      <AddDebtModal
        visible={modal.kind === "addDebt"}
        onClose={() => setModal({ kind: "idle" })}
      />
      {modal.kind === "addPayment" && (
        <AddDebtPaymentModal
          visible
          debt={modal.debt}
          onClose={() => setModal({ kind: "idle" })}
        />
      )}
    </>
  );
}
