"use client";

import { Suspense, useEffect, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";

interface Loan {
  id: number;
  name: string;
  bankname: string;
  minIncome: number;
  annualFee: string | null;
  image: string;
  loanurl: string;
  reducingInterestRate: number | null;
  flatInterestRate: number | null;
  loantypecode?: string | null;
  loantypedesc?: string | null;
  features: { id: number; details: string }[];
  offers: { id: number; details: string }[];
}

function LoanComparePageContent() {
  const params = useSearchParams();
  const router = useRouter();
  const [loans, setLoans] = useState<Loan[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const idsParam = params.get("ids") || "";
    if (!idsParam) {
      setLoading(false);
      setLoans([]);
      return;
    }
    const fetchLoans = async () => {
      try {
        setLoading(true);
        setError(null);
        const res = await fetch(`/api/loan?ids=${idsParam}`);
        if (!res.ok) throw new Error(`Request failed (${res.status})`);
        const data: Loan[] = await res.json();
        setLoans(data.slice(0, 3));
      } catch (err) {
        setError((err as Error).message || "Unable to load comparison");
      } finally {
        setLoading(false);
      }
    };
    fetchLoans();
  }, [params]);

  const backToLoan = () => router.push("/loan");

  if (loading) {
    return <div className="max-w-6xl mx-auto p-6">Loading selected loans...</div>;
  }

  if (error) {
    return (
      <div className="max-w-6xl mx-auto p-6">
        <p className="text-red-600">{error}</p>
        <button onClick={backToLoan} className="mt-3 px-4 py-2 bg-blue-600 text-white rounded">Back</button>
      </div>
    );
  }

  if (!loans.length) {
    return (
      <div className="max-w-6xl mx-auto p-6">
        <p className="text-gray-700">No loans selected. Please choose up to 3 loans to compare.</p>
        <button onClick={backToLoan} className="mt-3 px-4 py-2 bg-blue-600 text-white rounded">Go to Loans</button>
      </div>
    );
  }

  const headers = ["Bank", "Plan", "Min Income", "Fixed Rate", "Reducing Rate"];

  return (
    <div className="max-w-6xl mx-auto p-4 md:p-6 space-y-6">
      <div className="bg-gradient-to-r from-blue-600 to-blue-500 text-white rounded-2xl p-5 shadow-lg flex items-center justify-between">
        <div>
          <p className="text-[11px] uppercase tracking-wide text-blue-100">Personal Loan Utilities</p>
          <h1 className="text-2xl font-semibold">Compare Personal Loans</h1>
          <p className="text-sm text-blue-50/80">Select up to 3 loans and review the details side by side.</p>
        </div>
        <button onClick={backToLoan} className="px-4 py-2 border border-white/70 text-white rounded-lg hover:bg-white/10">
          Back to loans
        </button>
      </div>

      <div className={`grid gap-4`} style={{ gridTemplateColumns: `repeat(${loans.length}, minmax(0, 1fr))` }}>
        {loans.map((loan) => (
          <div key={loan.id} className="bg-white border border-gray-200 rounded-2xl shadow-sm p-4 space-y-3">
            <div className="flex items-start justify-between gap-2">
              <div>
                <div className="text-sm font-semibold text-gray-900">{loan.bankname}</div>
                <div className="text-sm text-gray-600">{loan.name}</div>
                <div className="text-[11px] text-blue-600 font-medium mt-1">{loan.loantypedesc || loan.loantypecode || "Personal Loan"}</div>
              </div>
              <span className="text-[11px] px-2 py-1 rounded-full bg-blue-50 text-blue-700 border border-blue-100">#{loan.id}</span>
            </div>

            <div className="grid grid-cols-1 gap-2 text-sm text-gray-700">
              <div className="flex justify-between"><span>Min Income</span><span className="font-semibold">AED {loan.minIncome}</span></div>
              <div className="flex justify-between"><span>Fixed Rate</span><span className="font-semibold">{loan.flatInterestRate !== null ? `${loan.flatInterestRate}%` : "N/A"}</span></div>
              <div className="flex justify-between"><span>Reducing Rate</span><span className="font-semibold">{loan.reducingInterestRate !== null ? `${loan.reducingInterestRate}%` : "N/A"}</span></div>
            </div>

            <div className="flex gap-2 pt-1">
              <a href={loan.loanurl || "#"} className="flex-1 text-center bg-blue-600 text-white rounded-lg py-2 hover:bg-blue-700">Apply</a>
              <a href={loan.loanurl || "#"} className="flex-1 text-center border border-blue-600 text-blue-600 rounded-lg py-2 hover:bg-blue-50">Details</a>
            </div>
          </div>
        ))}
      </div>

      <div className="bg-white border border-gray-200 rounded-2xl shadow-sm overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-3 py-3 text-left text-gray-700 font-semibold">Field</th>
              {loans.map((loan) => (
                <th key={loan.id} className="px-3 py-3 text-left text-gray-700 font-semibold">{loan.bankname}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {headers.map((field, idx) => (
              <tr key={field} className={idx % 2 ? "bg-gray-50" : "bg-white"}>
                <td className="px-3 py-2 font-semibold text-gray-800 border-t">{field}</td>
                {loans.map((loan) => {
                  const value = (() => {
                    switch (field) {
                      case "Bank":
                        return loan.bankname;
                      case "Plan":
                        return loan.name;
                      case "Min Income":
                        return `AED ${loan.minIncome}`;
                      case "Fixed Rate":
                        return loan.flatInterestRate !== null ? `${loan.flatInterestRate}%` : "N/A";
                      case "Reducing Rate":
                        return loan.reducingInterestRate !== null ? `${loan.reducingInterestRate}%` : "N/A";
                      default:
                        return "";
                    }
                  })();
                  return (
                    <td key={`${loan.id}-${field}`} className="px-3 py-2 text-gray-700 border-t">{value}</td>
                  );
                })}
              </tr>
            ))}
            <tr className="border-t align-top bg-gray-50">
              <td className="px-3 py-2 font-semibold text-gray-800">Top Features</td>
              {loans.map((loan) => (
                <td key={`${loan.id}-features`} className="px-3 py-3 text-gray-700">
                  <ul className="list-disc list-inside space-y-1 text-xs">
                    {loan.features.slice(0, 5).map((f) => (
                      <li key={f.id}>{f.details}</li>
                    ))}
                  </ul>
                </td>
              ))}
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default function LoanComparePage() {
  return (
    <Suspense fallback={<div className="max-w-6xl mx-auto p-6">Loading comparison...</div>}>
      <LoanComparePageContent />
    </Suspense>
  );
}
