"use client";

import { useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import ClientSuspense from "@/components/customui/ClientSuspense";

type MonthlyRow = {
  principal: number;
  interest: number;
  emi: number;
  balance: number;
};

type EmiBreakdown = {
  emi: number;
  total: number;
  interest: number;
  breakdown: MonthlyRow[];
};

function calculateEMI(amount: number, tenure: number, rate: number, type: "fixed" | "reducing"): EmiBreakdown {
  const monthlyRate = rate / 12 / 100;
  const breakdown: MonthlyRow[] = [];

  if (type === "fixed") {
    const principalPerMonth = amount / tenure;
    const interestPerMonth = amount * monthlyRate;
    const emi = principalPerMonth + interestPerMonth;
    let balance = amount;

    for (let i = 0; i < tenure; i++) {
      const principal = i === tenure - 1 ? balance : principalPerMonth;
      const interest = interestPerMonth;
      balance = Math.max(0, balance - principal);
      breakdown.push({ principal, interest, emi: principal + interest, balance });
    }
  } else {
    const emi =
      monthlyRate === 0
        ? amount / tenure
        : (amount * monthlyRate * Math.pow(1 + monthlyRate, tenure)) / (Math.pow(1 + monthlyRate, tenure) - 1);
    let balance = amount;

    for (let i = 0; i < tenure; i++) {
      const interest = balance * monthlyRate;
      const principal = i === tenure - 1 ? balance : Math.min(balance, emi - interest);
      const monthlyEmi = principal + interest;
      balance = Math.max(0, balance - principal);
      breakdown.push({ principal, interest, emi: monthlyEmi, balance });
    }
  }

  const total = breakdown.reduce((sum, row) => sum + row.emi, 0);
  const interest = breakdown.reduce((sum, row) => sum + row.interest, 0);
  return { emi: breakdown[0]?.emi ?? 0, total, interest, breakdown };
}

function formatMoney(value?: number) {
  return typeof value === "number" ? `Rs.${value.toFixed(2)}` : "N/A";
}

function LoanCalculatorResultContent() {
  const params = useSearchParams();
  const amount = Number(params.get("amount") || 0);
  const tenure = Number(params.get("tenure") || 0);
  const legacyRate = params.get("rate");
  const legacyType = params.get("type") || params.get("rateType") || "fixed";

  const fixedRateFromQuery = params.get("fixedRate") ?? (legacyRate && legacyType !== "reducing" ? legacyRate : "");
  const reducingRateFromQuery = params.get("reducingRate") ?? (legacyRate && legacyType === "reducing" ? legacyRate : "");

  const [amountInput, setAmountInput] = useState<string>(amount ? String(amount) : "");
  const [tenureInput, setTenureInput] = useState<string>(tenure ? String(tenure) : "");
  const [fixedRateInput, setFixedRateInput] = useState<string>(fixedRateFromQuery || "");
  const [reducingRateInput, setReducingRateInput] = useState<string>(reducingRateFromQuery || "");
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validate = () => {
    const nextErrors: Record<string, string> = {};
    const amountNum = Number(amountInput);
    const tenureNum = Number(tenureInput);
    const fixedRateNum = Number(fixedRateInput);
    const reducingRateNum = Number(reducingRateInput);
    const hasFixedRate = fixedRateInput.trim() !== "";
    const hasReducingRate = reducingRateInput.trim() !== "";

    if (!amountInput || Number.isNaN(amountNum) || amountNum < 1000) nextErrors.amount = "Enter a valid amount (min 1000)";
    if (!tenureInput || Number.isNaN(tenureNum) || tenureNum < 1) nextErrors.tenure = "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%)";
    return nextErrors;
  };

  const parsedAmount = Number(amountInput);
  const parsedTenure = Number(tenureInput);
  const parsedFixedRate = Number(fixedRateInput);
  const parsedReducingRate = Number(reducingRateInput);
  const hasFixedRate = fixedRateInput.trim() !== "";
  const hasReducingRate = reducingRateInput.trim() !== "";

  const fixedResult = useMemo(() => {
    if (!hasFixedRate || Number.isNaN(parsedAmount) || Number.isNaN(parsedTenure) || Number.isNaN(parsedFixedRate)) return null;
    if (parsedAmount < 1000 || parsedTenure < 1 || parsedFixedRate < 0.1) return null;
    return calculateEMI(parsedAmount, parsedTenure, parsedFixedRate, "fixed");
  }, [hasFixedRate, parsedAmount, parsedTenure, parsedFixedRate]);

  const reducingResult = useMemo(() => {
    if (!hasReducingRate || Number.isNaN(parsedAmount) || Number.isNaN(parsedTenure) || Number.isNaN(parsedReducingRate)) return null;
    if (parsedAmount < 1000 || parsedTenure < 1 || parsedReducingRate < 0.1) return null;
    return calculateEMI(parsedAmount, parsedTenure, parsedReducingRate, "reducing");
  }, [hasReducingRate, parsedAmount, parsedTenure, parsedReducingRate]);

  if (!amount || !tenure || (!fixedRateFromQuery && !reducingRateFromQuery)) {
    return <div className="max-w-xl mx-auto p-8 bg-white rounded-2xl shadow border border-red-100 text-red-700">Invalid input. Please go back and enter valid loan details.</div>;
  }

  const rowCount = Math.max(fixedResult?.breakdown.length ?? 0, reducingResult?.breakdown.length ?? 0);
  const rows = Array.from({ length: rowCount }, (_, i) => ({
    month: i + 1,
    fixed: fixedResult?.breakdown[i],
    reducing: reducingResult?.breakdown[i],
  }));
  const emiDifference = reducingResult && fixedResult ? reducingResult.emi - fixedResult.emi : undefined;
  const interestDifference = reducingResult && fixedResult ? reducingResult.interest - fixedResult.interest : undefined;
  const totalDifference = reducingResult && fixedResult ? reducingResult.total - fixedResult.total : undefined;

  return (
    <div className="max-w-6xl mx-auto p-4 md:p-6">
      <div className="bg-gradient-to-r from-blue-600 to-blue-500 text-white rounded-2xl p-6 shadow-lg flex flex-col gap-3">
        <div className="flex flex-wrap justify-between items-start gap-4">
          <div>
            <p className="text-xs uppercase tracking-wide text-blue-100">EMI Breakdown</p>
            <h1 className="text-2xl font-semibold">Loan Summary</h1>
            <p className="text-sm text-blue-100/90">Fixed vs reducing rate comparison</p>
          </div>
          <div className="flex items-center gap-2 text-sm bg-white/10 px-3 py-2 rounded-full backdrop-blur">
            <span className="inline-block px-2 py-1 text-xs rounded-full bg-white/20">Loan Rs.{parsedAmount.toLocaleString()}</span>
            <span className="inline-block px-2 py-1 text-xs rounded-full bg-white/20">{tenure} months</span>
            {hasFixedRate && <span className="inline-block px-2 py-1 text-xs rounded-full bg-white/20">Fixed {parsedFixedRate}%</span>}
            {hasReducingRate && <span className="inline-block px-2 py-1 text-xs rounded-full bg-white/20">Reducing {parsedReducingRate}%</span>}
          </div>
        </div>

        <div className="bg-white/10 rounded-xl border border-white/20 divide-y divide-white/15">
          {[
            {
              title: "Loan Overview",
              items: [
                { label: "Total Loan Amount", value: formatMoney(parsedAmount) },
                { label: "Fixed Rate", value: hasFixedRate ? `${parsedFixedRate}% p.a.` : "N/A" },
                { label: "Reducing Rate", value: hasReducingRate ? `${parsedReducingRate}% p.a.` : "N/A" },
              ],
            },
            {
              title: "Fixed Rate Summary",
              items: [
                { label: "Fixed EMI", value: formatMoney(fixedResult?.emi) },
                { label: "Total Fixed Interest Paid", value: formatMoney(fixedResult?.interest) },
                { label: "Total Paid (Fixed)", value: formatMoney(fixedResult?.total) },
              ],
            },
            {
              title: "Reducing Rate Summary",
              items: [
                { label: "Reducing EMI", value: formatMoney(reducingResult?.emi) },
                { label: "Total Reducing Interest Paid", value: formatMoney(reducingResult?.interest) },
                { label: "Total Paid (Reducing)", value: formatMoney(reducingResult?.total) },
              ],
            },
          ].map((section) => (
            <div key={section.title} className="px-4 py-3">
              <div className="grid grid-cols-1 md:grid-cols-[190px_repeat(3,minmax(0,1fr))] gap-3 md:gap-4 items-center">
                <p className="text-[11px] uppercase tracking-[0.08em] text-blue-100">{section.title}</p>
                {section.items.map((item) => (
                  <div key={item.label} className="text-sm leading-tight">
                    <p className="text-[11px] uppercase tracking-wide text-blue-100">{item.label}</p>
                    <p className="font-semibold text-white mt-1">{item.value}</p>
                  </div>
                ))}
              </div>
            </div>
          ))}
          <div className="px-4 py-3">
            <div className="grid grid-cols-1 md:grid-cols-[190px_repeat(3,minmax(0,1fr))] gap-3 md:gap-4 items-center">
              <p className="text-[11px] uppercase tracking-[0.08em] text-blue-100">Difference (Reducing - Fixed)</p>
              <div className="text-sm leading-tight">
                <p className="text-[11px] uppercase tracking-wide text-blue-100">EMI</p>
                <p className="font-semibold text-white mt-1">{formatMoney(emiDifference)}</p>
              </div>
              <div className="text-sm leading-tight">
                <p className="text-[11px] uppercase tracking-wide text-blue-100">Interest</p>
                <p className="font-semibold text-white mt-1">{formatMoney(interestDifference)}</p>
              </div>
              <div className="text-sm leading-tight">
                <p className="text-[11px] uppercase tracking-wide text-blue-100">Total Paid</p>
                <p className="font-semibold text-white mt-1">{formatMoney(totalDifference)}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="mt-6 grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-1 bg-white rounded-2xl shadow border p-6 space-y-4">
          <h2 className="text-lg font-semibold">Recalculate</h2>
          <div className="space-y-4 text-sm text-gray-700">
            <div>
              <div className="flex justify-between text-xs text-gray-500 mb-1">
                <span>Loan Amount</span>
                <span>{amountInput ? `Rs.${Number(amountInput).toLocaleString()}` : ""}</span>
              </div>
              <input
                type="range"
                min={10000}
                max={5000000}
                step={10000}
                value={amountInput ? Number(amountInput) : 10000}
                onChange={(e) => setAmountInput(e.target.value)}
                className="w-full accent-blue-600"
              />
              <input
                type="number"
                value={amountInput}
                onChange={(e) => setAmountInput(e.target.value)}
                className={`w-full border rounded px-3 py-2 mt-2 focus:outline-none focus:ring-2 focus:ring-blue-200 ${errors.amount ? "border-red-500" : "border-gray-200"}`}
                min={1000}
                placeholder="e.g. 100000"
              />
              {errors.amount && <p className="text-red-500 text-xs mt-1">{errors.amount}</p>}
            </div>

            <div>
              <div className="flex justify-between text-xs text-gray-500 mb-1">
                <span>Tenure (months)</span>
                <span>{tenureInput || ""}</span>
              </div>
              <input
                type="range"
                min={1}
                max={240}
                step={1}
                value={tenureInput ? Number(tenureInput) : 1}
                onChange={(e) => setTenureInput(e.target.value)}
                className="w-full accent-blue-600"
              />
              <input
                type="number"
                value={tenureInput}
                onChange={(e) => setTenureInput(e.target.value)}
                className={`w-full border rounded px-3 py-2 mt-2 focus:outline-none focus:ring-2 focus:ring-blue-200 ${errors.tenure ? "border-red-500" : "border-gray-200"}`}
                min={1}
                placeholder="e.g. 12"
              />
              {errors.tenure && <p className="text-red-500 text-xs mt-1">{errors.tenure}</p>}
            </div>

            <div>
              <label className="block text-gray-600 mb-1">Fixed Rate (% p.a.)</label>
              <input
                type="number"
                value={fixedRateInput}
                onChange={(e) => setFixedRateInput(e.target.value)}
                className={`w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-200 ${(errors.fixedRate || errors.rate) ? "border-red-500" : "border-gray-200"}`}
                step={0.01}
                min={0.1}
                placeholder="Optional"
              />
              {(errors.fixedRate || errors.rate) && <p className="text-red-500 text-xs mt-1">{errors.fixedRate || errors.rate}</p>}
            </div>

            <div>
              <label className="block text-gray-600 mb-1">Reducing Rate (% p.a.)</label>
              <input
                type="number"
                value={reducingRateInput}
                onChange={(e) => setReducingRateInput(e.target.value)}
                className={`w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-200 ${(errors.reducingRate || errors.rate) ? "border-red-500" : "border-gray-200"}`}
                step={0.01}
                min={0.1}
                placeholder="Optional"
              />
              {(errors.reducingRate || errors.rate) && <p className="text-red-500 text-xs mt-1">{errors.reducingRate || errors.rate}</p>}
            </div>

            <div className="pt-1 flex gap-2">
              <button
                type="button"
                onClick={() => setErrors(validate())}
                className="flex-1 text-center bg-blue-600 text-white rounded-lg py-2 hover:bg-blue-700"
              >
                Update EMI
              </button>
              <button type="button" className="flex-1 text-center border border-blue-600 text-blue-600 rounded-lg py-2 hover:bg-blue-50">Apply Now</button>
            </div>
          </div>
        </div>

        <div className="lg:col-span-2 bg-white rounded-2xl shadow border p-6">
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-lg font-semibold">Month-wise Breakdown</h2>
            <span className="text-xs text-gray-500">Compare fixed and reducing values</span>
          </div>
          {rowCount > 0 ? (
            <div className="overflow-x-auto max-h-[420px] rounded-lg border">
              <table className="min-w-full text-sm">
                <thead className="bg-gray-50 sticky top-0">
                  <tr>
                    <th className="px-3 py-2 text-left text-gray-600 font-semibold border-b">Month</th>
                    <th className="px-3 py-2 text-left text-gray-600 font-semibold border-b">Fixed Interest</th>
                    <th className="px-3 py-2 text-left text-gray-600 font-semibold border-b">Fixed EMI</th>
                    <th className="px-3 py-2 text-left text-gray-600 font-semibold border-b">Fixed Balance</th>
                    <th className="px-3 py-2 text-left text-gray-600 font-semibold border-b">Reducing Interest</th>
                    <th className="px-3 py-2 text-left text-gray-600 font-semibold border-b">Reducing EMI</th>
                    <th className="px-3 py-2 text-left text-gray-600 font-semibold border-b">Reducing Balance</th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((row, i) => (
                    <tr key={row.month} className={i % 2 ? "bg-gray-50" : "bg-white"}>
                      <td className="px-3 py-2 border-b">{row.month}</td>
                      <td className="px-3 py-2 border-b">{formatMoney(row.fixed?.interest)}</td>
                      <td className="px-3 py-2 border-b">{formatMoney(row.fixed?.emi)}</td>
                      <td className="px-3 py-2 border-b">{formatMoney(row.fixed?.balance)}</td>
                      <td className="px-3 py-2 border-b">{formatMoney(row.reducing?.interest)}</td>
                      <td className="px-3 py-2 border-b">{formatMoney(row.reducing?.emi)}</td>
                      <td className="px-3 py-2 border-b">{formatMoney(row.reducing?.balance)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className="text-sm text-red-500">Please enter valid values to see the breakdown.</div>
          )}
        </div>
      </div>
    </div>
  );
}

export default function LoanCalculatorResult() {
  return (
    <ClientSuspense fallback={<div className="max-w-xl mx-auto p-6">Loading calculator...</div>}>
      <LoanCalculatorResultContent />
    </ClientSuspense>
  );
}
