"use client";

import { useState, useMemo } from "react";
import { Calculator, ChevronDown, ChevronUp, IndianRupee } from "lucide-react";
import { cn } from "@/lib/utils";

interface Props {
  carPrice: number; // in lakhs
}

function calcEMI(principal: number, annualRate: number, months: number): number {
  if (principal <= 0 || months <= 0) return 0;
  const r = annualRate / (12 * 100);
  if (r === 0) return principal / months;
  return (principal * r * Math.pow(1 + r, months)) / (Math.pow(1 + r, months) - 1);
}

const TENURE_OPTIONS = [12, 24, 36, 48, 60, 72, 84];

export default function EMICalculator({ carPrice }: Props) {
  const [open, setOpen] = useState(false);
  // default: 20% down payment
  const defaultDown = Math.round(carPrice * 0.2 * 100) / 100;
  const [downPct, setDownPct] = useState(20); // percent
  const [interestRate, setInterestRate] = useState(9.0);
  const [tenureMonths, setTenureMonths] = useState(60);

  const loanAmount = useMemo(
    () => Math.max(0, carPrice * (1 - downPct / 100)),
    [carPrice, downPct]
  );

  const emi = useMemo(
    () => calcEMI(loanAmount * 100000, interestRate, tenureMonths),
    [loanAmount, interestRate, tenureMonths]
  );

  const totalPayout = emi * tenureMonths;
  const totalInterest = totalPayout - loanAmount * 100000;

  function fmt(n: number): string {
    if (n >= 100000) return `₹${(n / 100000).toFixed(2)} L`;
    return `₹${Math.round(n).toLocaleString("en-IN")}`;
  }

  const downAmount = carPrice * (downPct / 100);

  return (
    <div className="rounded-[28px] bg-white border border-gray-200/60 overflow-hidden shadow-[0_8px_30px_rgba(0,0,0,0.05)]">
      {/* Header — always visible */}
      <button
        onClick={() => setOpen((v) => !v)}
        className="w-full flex items-center justify-between px-6 py-5 hover:bg-gray-50 transition-colors"
      >
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-2xl bg-gradient-to-br from-blue-50 to-cyan-50 flex items-center justify-center">
            <Calculator className="w-5 h-5 text-blue-600" />
          </div>
          <div className="text-left">
            <p className="text-base font-black text-gray-900">EMI Calculator</p>
            {!open && emi > 0 && (
              <p className="text-sm text-blue-600 font-semibold">
                ≈ {fmt(emi)} / month
              </p>
            )}
          </div>
        </div>
        {open ? (
          <ChevronUp className="w-5 h-5 text-gray-400" />
        ) : (
          <ChevronDown className="w-5 h-5 text-gray-400" />
        )}
      </button>

      {open && (
        <div className="px-6 pb-6 border-t border-gray-100">
          {/* Summary chips */}
          <div className="grid grid-cols-3 gap-3 my-5">
            {[
              { label: "Monthly EMI", value: fmt(emi), highlight: true },
              { label: "Total Interest", value: fmt(totalInterest) },
              { label: "Total Payout", value: fmt(totalPayout) },
            ].map(({ label, value, highlight }) => (
              <div
                key={label}
                className={cn(
                  "rounded-2xl p-4 text-center border",
                  highlight
                    ? "bg-gradient-to-br from-blue-600 to-cyan-500 border-transparent text-white"
                    : "bg-gray-50 border-gray-100 text-gray-800"
                )}
              >
                <p className={cn("text-[10px] uppercase tracking-wide font-bold mb-1",
                  highlight ? "text-blue-100" : "text-gray-400"
                )}>
                  {label}
                </p>
                <p className="text-sm font-black leading-tight">{value}</p>
              </div>
            ))}
          </div>

          {/* Down Payment */}
          <div className="mb-5">
            <div className="flex items-center justify-between mb-2">
              <label className="text-sm font-bold text-gray-700">
                Down Payment
              </label>
              <span className="text-sm font-black text-blue-600">
                ₹{downAmount.toFixed(2)} L ({downPct}%)
              </span>
            </div>
            <input
              type="range"
              min={0}
              max={90}
              step={5}
              value={downPct}
              onChange={(e) => setDownPct(+e.target.value)}
              className="w-full h-2 rounded-full accent-blue-600 cursor-pointer"
            />
            <div className="flex justify-between text-[11px] text-gray-400 mt-1">
              <span>0%</span>
              <span>Loan: ₹{loanAmount.toFixed(2)} L</span>
              <span>90%</span>
            </div>
          </div>

          {/* Interest Rate */}
          <div className="mb-5">
            <div className="flex items-center justify-between mb-2">
              <label className="text-sm font-bold text-gray-700">
                Interest Rate
              </label>
              <span className="text-sm font-black text-blue-600">
                {interestRate.toFixed(1)}% p.a.
              </span>
            </div>
            <input
              type="range"
              min={6}
              max={18}
              step={0.5}
              value={interestRate}
              onChange={(e) => setInterestRate(+e.target.value)}
              className="w-full h-2 rounded-full accent-blue-600 cursor-pointer"
            />
            <div className="flex justify-between text-[11px] text-gray-400 mt-1">
              <span>6%</span>
              <span>18%</span>
            </div>
          </div>

          {/* Tenure */}
          <div className="mb-2">
            <p className="text-sm font-bold text-gray-700 mb-2">Loan Tenure</p>
            <div className="flex flex-wrap gap-2">
              {TENURE_OPTIONS.map((m) => (
                <button
                  key={m}
                  onClick={() => setTenureMonths(m)}
                  className={cn(
                    "px-3 py-1.5 rounded-xl text-xs font-bold border transition-all",
                    tenureMonths === m
                      ? "bg-blue-600 text-white border-transparent shadow-md"
                      : "bg-white text-gray-600 border-gray-200 hover:border-blue-200"
                  )}
                >
                  {m >= 12 ? `${m / 12} yr` : `${m} mo`}
                </button>
              ))}
            </div>
          </div>

          <p className="text-[10px] text-gray-400 mt-4 leading-relaxed">
            * EMI is indicative. Actual rates vary by lender. Does not include GST,
            insurance, or registration charges.
          </p>
        </div>
      )}
    </div>
  );
}
