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

export default function LoanCalculator() {
  const [amount, setAmount] = useState(100000);
  const [tenure, setTenure] = useState(12);
  const [fixedRate, setFixedRate] = useState<number | "">(8.5);
  const [reducingRate, setReducingRate] = useState<number | "">("");
  const [mobile, setMobile] = useState("");
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const router = useRouter();

  const validate = () => {
    const newErrors: { [key: string]: string } = {};
    if (!amount || amount < 1000) newErrors.amount = "Enter a valid loan amount (min 1000)";
    if (!tenure || tenure < 1) newErrors.tenure = "Enter valid months (min 1)";
    const hasFixedRate = fixedRate !== "";
    const hasReducingRate = reducingRate !== "";
    if (!hasFixedRate && !hasReducingRate) newErrors.rate = "Enter fixed rate and/or reducing rate";
    if (hasFixedRate && Number(fixedRate) < 0.1) newErrors.fixedRate = "Enter valid fixed rate (min 0.1%)";
    if (hasReducingRate && Number(reducingRate) < 0.1) newErrors.reducingRate = "Enter valid reducing rate (min 0.1%)";
    if (!mobile || !/^\d{10}$/.test(mobile)) newErrors.mobile = "Enter valid 10-digit mobile number";
    return newErrors;
  };

  const handleCalculate = (e: React.FormEvent) => {
    e.preventDefault();
    const validationErrors = validate();
    setErrors(validationErrors);
    if (Object.keys(validationErrors).length === 0) {
      const query = new URLSearchParams({
        amount: String(amount),
        tenure: String(tenure),
      });
      if (fixedRate !== "") query.set("fixedRate", String(fixedRate));
      if (reducingRate !== "") query.set("reducingRate", String(reducingRate));
      router.push(`/loan/calculator/result?${query.toString()}`);
    }
  };

  return (
    <div className="max-w-4xl mx-auto p-4 bg-white rounded-2xl shadow border border-gray-200">
      <form onSubmit={handleCalculate} className="flex flex-col gap-2">
        <div className="flex flex-wrap items-center gap-3 p-4">
          <div className="flex-1 min-w-[180px]">
            <input
              type="number"
              value={amount}
              onChange={e => setAmount(Number(e.target.value))}
              className={`w-full border border-gray-200 rounded px-3 py-2 text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-200 ${errors.amount ? 'border-red-500' : ''}`}
              min={1000}
              placeholder="Loan Amount"
              required
            />
            {errors.amount && <div className="text-red-500 text-xs mt-1">{errors.amount}</div>}
          </div>
          <div className="flex-1 min-w-[120px]">
            <input
              type="number"
              value={tenure}
              onChange={e => setTenure(Number(e.target.value))}
              className={`w-full border border-gray-200 rounded px-3 py-2 text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-200 ${errors.tenure ? 'border-red-500' : ''}`}
              min={1}
              placeholder="Months"
              required
            />
            {errors.tenure && <div className="text-red-500 text-xs mt-1">{errors.tenure}</div>}
          </div>
          <div className="flex-1 min-w-[140px]">
            <input
              type="number"
              value={fixedRate}
              onChange={e => setFixedRate(e.target.value === "" ? "" : Number(e.target.value))}
              className={`w-full border border-gray-200 rounded px-3 py-2 text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-200 ${(errors.rate || errors.fixedRate) ? 'border-red-500' : ''}`}
              min={0.1}
              step={0.01}
              placeholder="Fixed Rate %"
            />
            {(errors.rate || errors.fixedRate) && <div className="text-red-500 text-xs mt-1">{errors.fixedRate || errors.rate}</div>}
          </div>
          <div className="flex-1 min-w-[140px]">
            <input
              type="number"
              value={reducingRate}
              onChange={e => setReducingRate(e.target.value === "" ? "" : Number(e.target.value))}
              className={`w-full border border-gray-200 rounded px-3 py-2 text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-200 ${(errors.rate || errors.reducingRate) ? 'border-red-500' : ''}`}
              min={0.1}
              step={0.01}
              placeholder="Reducing Rate %"
            />
            {(errors.rate || errors.reducingRate) && <div className="text-red-500 text-xs mt-1">{errors.reducingRate || errors.rate}</div>}
          </div>
          <div className="flex-1 min-w-[140px]">
            <input
              type="tel"
              value={mobile}
              onChange={e => setMobile(e.target.value.replace(/[^0-9]/g, ""))}
              className={`w-full border border-gray-200 rounded px-3 py-2 text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-200 ${errors.mobile ? 'border-red-500' : ''}`}
              placeholder="Mobile No."
              maxLength={10}
              pattern="[0-9]{10}"
              required
            />
            {errors.mobile && <div className="text-red-500 text-xs mt-1">{errors.mobile}</div>}
          </div>
          <button type="submit" className="bg-blue-600 text-white px-8 py-2 rounded transition hover:bg-blue-700">Calculate</button>
        </div>
      </form>
    </div>
  );
}
