"use client";

import { use, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import BankLoanCard from "@/components/customui/BankLoanCard";
import LoanCalculator from "@/components/customui/LoanCalculator";

type LoanFeature = { id: number; details: string };
type LoanOffer = { id: number; details: string };

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

type LoanTypeConfig = {
  code: string;
  label: string;
  slug: string;
  description: string;
};

const LOAN_TYPES: LoanTypeConfig[] = [
  {
    code: "STL",
    label: "Salary Transfer Loan",
    slug: "salary-transfer-loan",
    description: "Loans that reward customers for transferring their salary to the lending bank.",
  },
  {
    code: "BOL",
    label: "Buy Out Loan",
    slug: "buy-out-loan",
    description: "Designed to consolidate or buy out existing personal loans with better terms.",
  },
  {
    code: "NWSTL",
    label: "Loan Without Salary Transfer",
    slug: "loan-without-salary-transfer",
    description: "Flexible loans that do not require moving your salary to the provider.",
  },
  {
    code: "NLC",
    label: "Loan For Non Listed Company",
    slug: "loan-for-non-listed-company",
    description: "Options tailored for employees of private or non-listed companies.",
  },
  {
    code: "NTC",
    label: "Loan For New to Country/Company",
    slug: "loan-for-new-to-country-company",
    description: "Support for newcomers to the UAE or to a new employer with shorter history.",
  },
  {
    code: "EMIRATI",
    label: "Emirati/UAE National Loan",
    slug: "emirati-uae-national-loan",
    description: "Exclusive benefits crafted for UAE nationals across banks.",
  },
  {
    code: "ISLAMIC",
    label: "Islamic Finance",
    slug: "islamic-finance",
    description: "Sharia-compliant personal finance products with profit-based pricing.",
  },
  {
    code: "SME",
    label: "SME Business Loan",
    slug: "sme-business-loan",
    description: "Personalised lending lines for small and medium enterprises.",
  },
];

const toTitleCase = (value: string) =>
  value
    .split(/[-\s]+/)
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ");

const normalizeSlug = (value: string) => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");

const resolveLoanType = (identifier: string) => {
  const normalized = normalizeSlug(identifier);
  const bySlug = LOAN_TYPES.find((type) => type.slug === normalized);
  if (bySlug) return bySlug;

  const byCode = LOAN_TYPES.find((type) => type.code.toLowerCase() === identifier.toLowerCase());
  if (byCode) return byCode;

  const title = toTitleCase(identifier.replace(/-/g, " "));
  return {
    code: identifier,
    label: title,
    slug: normalized,
    description: "Personal loan options for the selected category.",
  } satisfies LoanTypeConfig;
};

type LoanTypePageProps = {
  params: Promise<{ loantype: string }>;
  searchParams?: Promise<{ bank?: string; minIncome?: string }>;
};

export default function LoanTypePage({ params, searchParams }: LoanTypePageProps) {
  const resolvedParams = use(params);
  const resolvedSearchParams = searchParams ? use(searchParams) : {};
  const typeInfo = useMemo(() => resolveLoanType(resolvedParams.loantype), [resolvedParams.loantype]);

  const [loans, setLoans] = useState<Loan[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [compareList, setCompareList] = useState<{ id: number; name: string }[]>([]);
  const router = useRouter();

  useEffect(() => {
    const query = new URLSearchParams();
    query.append("loantype", typeInfo.code);
    if (resolvedSearchParams?.bank) query.append("bank", resolvedSearchParams.bank);
    if (resolvedSearchParams?.minIncome) query.append("minIncome", resolvedSearchParams.minIncome);

    const fetchLoans = async () => {
      try {
        setLoading(true);
        setError(null);
        const res = await fetch(`/api/loan?${query.toString()}`);
        if (!res.ok) {
          throw new Error(`Request failed with status ${res.status}`);
        }
        const data: Loan[] = await res.json();
        setLoans(data);
      } catch (err) {
        console.error("Loan API Fetch Error:", err);
        setError("Unable to load loans right now. Please try again in a moment.");
      } finally {
        setLoading(false);
      }
    };

    fetchLoans();
  }, [typeInfo.code, resolvedSearchParams?.bank, resolvedSearchParams?.minIncome]);

  const handleCompareChange = (checked: boolean, loan: { id: number; name: string }) => {
    setCompareList((prev) => {
      if (checked) {
        const exists = prev.find((p) => p.id === loan.id);
        if (exists) return prev;
        if (prev.length >= 3) return prev; // limit to 3
        return [...prev, loan];
      }
      return prev.filter((p) => p.id !== loan.id);
    });
  };

  const handleCompareNavigate = () => {
    if (compareList.length === 0) return;
    const ids = compareList.map((c) => c.id).join(",");
    router.push(`/loan/compare?ids=${ids}`);
  };

  const renderContent = () => {
    if (loading) return <p className="text-gray-600">Loading {typeInfo.label} options...</p>;
    if (error) return <p className="text-red-600">{error}</p>;
    if (loans.length === 0)
      return <p className="text-gray-600">No loans found for {typeInfo.label} right now.</p>;

    return loans.map((loan) => (
      <BankLoanCard
          id={loan.id}
        key={loan.id}
        bankLogo={loan.image || "/default.webp"}
        bankName={loan.bankname}
        planName={loan.name}
        minSalary={loan.minIncome}
        flatRate={loan.flatInterestRate !== null ? `${loan.flatInterestRate}%` : "N/A"}
        reducingRate={loan.reducingInterestRate !== null ? `${loan.reducingInterestRate}%` : "N/A"}
        loanUrl={loan.loanurl}
        features={loan.features.map((f) => f.details)}
        offers={loan.offers?.map((o) => o.details) ?? []}
        onCompareChange={handleCompareChange}
      />
    ));
  };

  return (
    <div className="p-6">
      <div className="max-w-5xl mx-auto space-y-6">
        <div className="space-y-2">
          <div className="text-xs text-gray-600">Home {">"} Personal Loan {">"} {typeInfo.label}</div>
        </div>

        <div className="bg-gradient-to-r from-blue-600 to-blue-500 text-white rounded-xl shadow-md p-3 md:p-4 space-y-1.5">
          <p className="text-[11px] uppercase tracking-wide text-blue-50">Personal Loan Type</p>
          <h1 className="text-xl md:text-2xl font-semibold leading-snug">Top {typeInfo.label} Personal Loans in UAE</h1>
          <p className="text-sm text-blue-50/80 max-w-3xl">{typeInfo.description}</p>
        </div>

        <div className="bg-white border rounded-xl shadow-sm p-4">
          <LoanCalculator />
        </div>

        <div className="space-y-4">{renderContent()}</div>
      </div>

      <div className="fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-white shadow-lg border px-6 py-3 rounded-xl flex items-center space-x-4">
        <p className="text-sm text-gray-700">{compareList.length} selected (max 3)</p>
        <button
          className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 disabled:opacity-50"
          onClick={handleCompareNavigate}
          disabled={compareList.length === 0}
        >
          Compare Now
        </button>
      </div>
    </div>
  );
}
