"use client";
import { useModal } from "@/context/ModalContext";
import React, { useState, useEffect } from "react";

const MortgageCalculator = () => {
  const [propertyPrice, setPropertyPrice] = useState(1200000);
  const [downPayment, setDownPayment] = useState(20);
  const [loanDuration, setLoanDuration] = useState(1);
  const [interestRate, setInterestRate] = useState(5);
  const { toggleModal } = useModal();
  const [monthlyRepayment, setMonthlyRepayment] = useState(0);

  useEffect(() => {
    calculate();
  }, [propertyPrice, downPayment, loanDuration, interestRate]);

  const formatCurrency = (amount) => {
    return "AED " + amount.toFixed(0).replace(/\d(?=(\d{3})+$)/g, "$&,");
  };

  const calculate = () => {
    const downPaymentAmount = (propertyPrice * downPayment) / 100;
    const loanAmount = propertyPrice - downPaymentAmount;
    const monthlyInterestRate = interestRate / 12 / 100;
    const months = loanDuration * 12;
    const repayment =
      (loanAmount * monthlyInterestRate) /
      (1 - Math.pow(1 + monthlyInterestRate, -months));
    setMonthlyRepayment(repayment);
  };

  const handlePropertyPriceChange = (event) => {
    const value = event.target.value;
    // Remove non-numeric characters except for the decimal point
    const numericValue = value.replace(/[^0-9.]/g, "");
    if (numericValue === "") {
      setPropertyPrice("");
    } else if (!isNaN(parseFloat(numericValue))) {
      setPropertyPrice(parseFloat(numericValue));
    }
  };

  const handleDownPaymentChange = (event) => {
    const value = parseInt(event.target.value);
    if (!isNaN(value) && value >= 0 && value <= 100) {
      setDownPayment(value);
    }
  };

  const handleLoanDurationChange = (event) => {
    const value = parseInt(event.target.value);
    if (!isNaN(value) && value >= 1 && value <= 30) {
      setLoanDuration(value);
    }
  };

  const handleInterestRateChange = (event) => {
    const value = parseFloat(event.target.value);
    if (!isNaN(value) && value >= 0 && value <= 20) {
      setInterestRate(value);
    }
  };

  const handleClearPropertyPrice = () => {
    setPropertyPrice("");
  };

  const handleClearDownPayment = () => {
    setDownPayment(0);
  };

  const handleClearLoanDuration = () => {
    setLoanDuration(1);
  };

  const handleClearInterestRate = () => {
    setInterestRate(0);
  };

  const downPaymentAmount = propertyPrice
    ? (propertyPrice * downPayment) / 100
    : 0;

  return (
    <div className="mortage-bac">
      <div className="container">
        <div className="row">
          <div className="col-md-12">
            <div className="mort_details">
              <h2>Mortgage Calculator</h2>
              <p>Check your monthly mortgage payment</p>
            </div>
          </div>
        </div>
        <div className="row mt-4">
          <div className="col-md-6">
            <div className="form-group">
              <label>Property Price</label>
              <div className="input-group">
                <input
                  type="text"
                  className="form-control"
                  value={propertyPrice.toLocaleString() || ""}
                  onChange={handlePropertyPriceChange}
                  placeholder="Enter property price"
                />
              </div>
            </div>
            <div className="form-group">
              <label>Down Payment ({downPayment} %)</label>
              <input
                type="range"
                min="0"
                max="100"
                value={downPayment}
                className="form-range form-control-range"
                onChange={handleDownPaymentChange}
              />
              <div>
                Down Payment Amount: {formatCurrency(downPaymentAmount)}
              </div>
            </div>
            <div className="form-group">
              <label>Loan Duration ({loanDuration} Years)</label>
              <input
                type="range"
                min="1"
                max="30"
                value={loanDuration}
                className="form-range form-control-range"
                onChange={handleLoanDurationChange}
              />
            </div>
            <div className="form-group">
              <label>Interest Rate ({interestRate} %)</label>
              <input
                type="number"
                min="0"
                max="20"
                step="0.01"
                value={interestRate}
                className="form-control"
                onChange={handleInterestRateChange}
                placeholder="Enter interest rate"
              />
            </div>
          </div>
          <div className="col-md-6">
            <div className="right-mortage">
              <h4>Monthly Repayment</h4>
              <h4>{formatCurrency(monthlyRepayment)}</h4>
              <p>
                Estimated initial monthly payments based on a AED{" "}
                {propertyPrice.toLocaleString()}
                &nbsp; purchase price with a {interestRate}% fixed interest
                rate.
              </p>
              <button
                className="webbutton mt-4"
                onClick={() => toggleModal("Request a consultation")}
              >
                Request a consultation
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MortgageCalculator;
