import { useState } from "react";
import {
  Modal,
  Text,
  TextInput,
  View,
} from "react-native";
import { useCreateDebtPayment, type Debt } from "@/src/hooks/useDebts";
import { useTranslation } from "react-i18next";
import { ModalHeader } from "@/src/components/ui/ModalHeader";
import { Numpad } from "@/src/components/ui/Numpad";
import { todayIso } from "@/src/utils/date";
import { formatEur } from "@/src/utils/format";
import { handleNumpadKey, parseAmountStr } from "@/src/utils/numpad";

type Props = {
  visible: boolean;
  debt: Debt;
  onClose: () => void;
};

export function AddDebtPaymentModal({ visible, debt, onClose }: Props) {
  const [amountStr, setAmountStr] = useState("0");
  const [note, setNote] = useState("");

  const { mutate: createPayment, isPending } = useCreateDebtPayment();
  const { t } = useTranslation();

  function handleNumpad(key: string) {
    setAmountStr((prev) => handleNumpadKey(prev, key));
  }

  function handleSave() {
    const amount = parseAmountStr(amountStr);
    if (!amount || amount <= 0) return;
    createPayment(
      {
        debtId: debt.id,
        amount,
        date: todayIso(),
        note: note.trim() || undefined,
      },
      {
        onSuccess: () => {
          resetAndClose();
        },
      },
    );
  }

  function resetAndClose() {
    setAmountStr("0");
    setNote("");
    onClose();
  }

  const parsedAmount = parseAmountStr(amountStr);
  const canSave = parsedAmount > 0;
  const isOverpaying = parsedAmount > debt.remainingAmount + 0.005;

  return (
    <Modal visible={visible} animationType="slide" presentationStyle="pageSheet" onRequestClose={resetAndClose}>
      <View className="flex-1 bg-white">
        {/* Header */}
        <ModalHeader
          title={t('debts.payRate')}
          onClose={resetAndClose}
          closeLabel={t('common.cancel')}
          onSave={handleSave}
          saveLabel={t('common.book')}
          saveDisabled={!canSave}
          saveLoading={isPending}
          saveColor="#7c3aed"
        />

        {/* Debt info */}
        <View className="mx-4 mt-4 p-4 bg-purple-50 rounded-2xl mb-2">
          <Text className="text-sm font-semibold text-purple-900">{debt.label}</Text>
          {debt.creditor && (
            <Text className="text-xs text-purple-500 mt-0.5">{debt.creditor}</Text>
          )}
          <Text className="text-xs text-purple-600 mt-2">
            {t('debts.remaining', { amount: formatEur(debt.remainingAmount, false) })}
          </Text>
        </View>

        {/* Amount display */}
        <View className="items-center py-6">
          <Text className="text-5xl font-bold text-gray-900">€ {amountStr}</Text>
          {isOverpaying && (
            <Text className="text-xs text-orange-500 mt-1">
              {t('debts.overpayingWarning')}
            </Text>
          )}
        </View>

        {/* Note field */}
        <View className="px-4 mb-4">
          <TextInput
            className="bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-base text-gray-900"
            placeholder={t('debts.noteOptional')}
            value={note}
            onChangeText={setNote}
          />
        </View>

        {/* Numpad */}
        <Numpad onKeyPress={handleNumpad} />
      </View>
    </Modal>
  );
}
