"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function LoanCalculator() {
  const router = useRouter();
  const [amount, setAmount] = useState<string>("");
  const [months, setMonths] = useState<string>("");
  const [fixedRate, setFixedRate] = useState<string>("");
  const [reducingRate, setReducingRate] = useState<string>("");
  const [mobile, setMobile] = useState<string>("");
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validate = () => {
    const nextErrors: Record<string, string> = {};
    const amountNum = Number(amount);
    const monthsNum = Number(months);
    const fixedRateNum = Number(fixedRate);
    const reducingRateNum = Number(reducingRate);
    const hasFixedRate = fixedRate.trim() !== "";
    const hasReducingRate = reducingRate.trim() !== "";
    if (!amount || Number.isNaN(amountNum) || amountNum < 1000) nextErrors.amount = "Enter a valid loan amount (min 1000)";
    if (!months || Number.isNaN(monthsNum) || monthsNum < 1) nextErrors.months = "Enter valid months (min 1)";
    if (!hasFixedRate && !hasReducingRate) nextErrors.rate = "Enter fixed rate and/or reducing rate";
    if (hasFixedRate && (Number.isNaN(fixedRateNum) || fixedRateNum < 0.1)) nextErrors.fixedRate = "Enter valid fixed rate (min 0.1%)";
    if (hasReducingRate && (Number.isNaN(reducingRateNum) || reducingRateNum < 0.1)) nextErrors.reducingRate = "Enter valid reducing rate (min 0.1%)";
    if (!mobile || !/^\d{10}$/.test(mobile)) nextErrors.mobile = "Enter valid 10-digit mobile number";
    return nextErrors;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const nextErrors = validate();
    setErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) return;

    const query = new URLSearchParams({
      amount: String(Number(amount)),
      tenure: String(Number(months)),
    });
    if (fixedRate.trim() !== "") query.set("fixedRate", String(Number(fixedRate)));
    if (reducingRate.trim() !== "") query.set("reducingRate", String(Number(reducingRate)));
    router.push(`/loan/calculator/result?${query.toString()}`);
  };

  return (
    <section className="bg-white shadow p-4 rounded-2xl border border-gray-200">
      <h2 className="text-lg font-semibold mb-3">Loan Calculator</h2>
      <form onSubmit={handleSubmit} className="flex flex-col gap-2">
        <div className="flex flex-wrap items-center gap-3">
          <div className="flex-1 min-w-[160px]">
            <input
              type="number"
              placeholder="Loan Amount"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              className={`p-2 border rounded w-full ${errors.amount ? "border-red-500" : "border-gray-200"}`}
            />
            {errors.amount && <p className="text-xs text-red-500 mt-1">{errors.amount}</p>}
          </div>
          <div className="flex-1 min-w-[140px]">
            <input
              type="number"
              placeholder="Months"
              value={months}
              onChange={(e) => setMonths(e.target.value)}
              className={`p-2 border rounded w-full ${errors.months ? "border-red-500" : "border-gray-200"}`}
            />
            {errors.months && <p className="text-xs text-red-500 mt-1">{errors.months}</p>}
          </div>
          <div className="flex-1 min-w-[160px]">
            <input
              type="number"
              placeholder="Fixed Rate %"
              value={fixedRate}
              onChange={(e) => setFixedRate(e.target.value)}
              className={`p-2 border rounded w-full ${errors.fixedRate || errors.rate ? "border-red-500" : "border-gray-200"}`}
              step="0.01"
            />
            {(errors.fixedRate || errors.rate) && <p className="text-xs text-red-500 mt-1">{errors.fixedRate || errors.rate}</p>}
          </div>
          <div className="flex-1 min-w-[160px]">
            <input
              type="number"
              placeholder="Reducing Rate %"
              value={reducingRate}
              onChange={(e) => setReducingRate(e.target.value)}
              className={`p-2 border rounded w-full ${errors.reducingRate || errors.rate ? "border-red-500" : "border-gray-200"}`}
              step="0.01"
            />
            {(errors.reducingRate || errors.rate) && <p className="text-xs text-red-500 mt-1">{errors.reducingRate || errors.rate}</p>}
          </div>
          <div className="flex-1 min-w-[160px]">
            <input
              type="text"
              placeholder="Mobile No."
              value={mobile}
              onChange={(e) => setMobile(e.target.value.replace(/[^0-9]/g, ""))}
              className={`p-2 border rounded w-full ${errors.mobile ? "border-red-500" : "border-gray-200"}`}
              maxLength={10}
              inputMode="numeric"
            />
            {errors.mobile && <p className="text-xs text-red-500 mt-1">{errors.mobile}</p>}
          </div>
          <button type="submit" className="bg-blue-600 text-white rounded px-6 py-2 hover:bg-blue-700 min-w-[120px]">
            Calculate
          </button>
        </div>
      </form>
    </section>
  );
}
