import { useState } from ‘react’;
import { Card, CardContent } from ‘@/components/ui/card’;
import { Input } from ‘@/components/ui/input’;
import { Button } from ‘@/components/ui/button’;
import { Label } from ‘@/components/ui/label’;
import { format } from ‘date-fns’;
import * as XLSX from ‘xlsx’;
export default function HomeLoanCalculator() {
const [loanAmount, setLoanAmount] = useState(6000000);
const [interestRate, setInterestRate] = useState(8.5);
const [tenureYears, setTenureYears] = useState(20);
const [startDate, setStartDate] = useState(‘2023-11-01’);
const [schedule, setSchedule] = useState([]);
const [partPayments, setPartPayments] = useState({});
const handlePartPaymentChange = (month, amount) => {
setPartPayments(prev => ({ …prev, [month]: Number(amount) }));
};
const calculateEMI = () => {
const principal = loanAmount;
const r = interestRate / 12 / 100;
const n = tenureYears * 12;
const emi = (principal * r * Math.pow(1 + r, n)) / (Math.pow(1 + r, n) – 1);
const amortization = [];
let balance = principal;
let currentDate = new Date(startDate);
for (let i = 0; i < n; i++) {
const monthKey = format(currentDate, 'MMM-yy');
const interest = balance * r;
const principalPaid = emi – interest;
let partPayment = partPayments[monthKey] || 0;
amortization.push({
month: monthKey,
balance: balance.toFixed(2),
interestRate: r,
emi: emi.toFixed(2),
principalPaid: principalPaid.toFixed(2),
interestPaid: interest.toFixed(2),
partPayment: partPayment.toFixed(2),
});
balance = balance – principalPaid – partPayment;
if (balance {
const worksheet = XLSX.utils.json_to_sheet(schedule);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, ‘EMI Schedule’);
XLSX.writeFile(workbook, ‘home_loan_schedule.xlsx’);
};
return (
🏡 Home Loan Calculator
Loan Amount (₹)
setLoanAmount(Number(e.target.value))} />
Interest Rate (%)
setInterestRate(Number(e.target.value))} step=”0.01″ />
Tenure (Years)
setTenureYears(Number(e.target.value))} />
Start Date
setStartDate(e.target.value)} />
Calculate EMI
Download to Excel
{schedule.length > 0 && (
| Month |
Principal (₹) |
Interest Rate |
Monthly EMI (₹) |
Principal Paid (₹) |
Interest Paid (₹) |
Part Payment (₹) |
Add Part Payment |
{schedule.map((row, index) => (
| {row.month} |
{row.balance} |
{(row.interestRate * 100).toFixed(2)}% |
{row.emi} |
{row.principalPaid} |
{row.interestPaid} |
{row.partPayment} |
handlePartPaymentChange(row.month, e.target.value)}
className=”w-24″
/>
|
))}
)}
);
}