"use client";

import React from "react";
import { useSearchParams } from "next/navigation";

function calculateEMI(P: number, N: number, R: number, rateType: string) {
  const monthlyRate = R / 12 / 100;

  // Guard against invalid values (prevents NaN/Infinity)
  if (P <= 0 || N <= 0 || R <= 0) return 0;

  if (rateType === "fixed") {
    const pow = Math.pow(1 + monthlyRate, N);
    const denom = pow - 1;
    if (denom === 0) return 0;
    return (P * monthlyRate * pow) / denom;
  }

  // Reducing balance (simple approximation)
  return (P / N) + (P * monthlyRate);
}

export default function LoanCalculatorResultClient() {
  const params = useSearchParams();
  const amount = Number(params.get("amount") || 0);
  const tenure = Number(params.get("tenure") || 0);
  const rate = Number(params.get("rate") || 0);
  const rateType = params.get("rateType") || "fixed";

  const emi =
    amount > 0 && tenure > 0 && rate > 0
      ? calculateEMI(amount, tenure, rate, rateType)
      : 0;

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col items-center py-10">
      <div className="bg-white rounded-xl shadow-lg p-8 w-full max-w-md">
        <h1 className="text-2xl font-bold text-blue-700 mb-2 text-center">
          Loan EMI Result
        </h1>

        <p className="text-gray-600 text-center mb-6">
          Here is your estimated monthly EMI based on the details you provided.
        </p>

        <div className="space-y-3 text-lg">
          <div className="flex justify-between">
            <span className="text-gray-700">Loan Amount:</span>
            <span className="font-semibold">AED {amount.toLocaleString()}</span>
          </div>

          <div className="flex justify-between">
            <span className="text-gray-700">Tenure:</span>
            <span className="font-semibold">{tenure} months</span>
          </div>

          <div className="flex justify-between">
            <span className="text-gray-700">Interest Rate:</span>
            <span className="font-semibold">
              {rate}% {rateType === "fixed" ? "(Fixed)" : "(Reducing)"}
            </span>
          </div>

          <div className="flex justify-between text-blue-700 text-xl mt-4">
            <span className="font-bold">Monthly EMI:</span>
            <span className="font-bold">
              AED{" "}
              {emi > 0
                ? emi.toLocaleString(undefined, { maximumFractionDigits: 2 })
                : "-"}
            </span>
          </div>
        </div>

        <div className="mt-8 text-center">
          <a href="/loan/calculator/emi-page" className="text-blue-600 underline">
            Calculate Again
          </a>
        </div>
      </div>
    </div>
  );
}
