/* eslint-disable @typescript-eslint/no-explicit-any */
'use client'

import React, { useEffect, useState } from 'react';
import { formatAmount } from '../../lib/utils/helpers';
import Link from 'next/link';
import { useAuth } from '../../context/AuthContext';
import Loader from '../loader';

export interface LoanHistoryItem {
  loanId: string;
  amount: number;
  status: string;
  createdOn: string;
  dueDate: string;
  dateApproved: string;
  dateRejected: string;
}

export interface LoanRowProps {
  history: LoanHistoryItem;
  index: number;
}

export const formatDate = (dateString: string) => {
  if (dateString === "N/A") return "N/A";
    
    const date = new Date(dateString);
    const day = date.getDate();
    const month = date.toLocaleString("en-US", { month: "long" });
    const year = date.getFullYear();
  
    const getOrdinal = (n: number) => {
      const s = ["th", "st", "nd", "rd"];
      const v = n % 100;
      return s[(v - 20) % 10] || s[v] || s[0];
    };
  
    return `${month} ${day}${getOrdinal(day)}, ${year}`;
};
  
const LoanRow: React.FC<LoanRowProps> = ({ history, index }) => {
  const isCredit = true;
  
  return (
    <tr key={index} className="border-b border-gray-50 grid grid-cols-[1fr_1fr_1fr_1fr_1fr_1fr]">
      <td className={`py-4 sm:py-1 text-sm sm:text-base font-medium ${isCredit ? 'text-green-600' : 'text-red-600'}`}>
        {isCredit ? '+' : ''}{formatAmount(history.amount)}
      </td>
      <td className="py-4 sm:py-1 text-gray-600 text-sm sm:text-base hidden sm:table-cell">
        {formatDate(history.createdOn)}
      </td>
      <td className="py-4 sm:py-1 text-gray-600 text-sm sm:text-base hidden sm:table-cell">
        {history.dateApproved ? formatDate(history.dateApproved) : "-"}
      </td>
      <td className="py-4 sm:py-1 text-gray-600 text-sm sm:text-base hidden sm:table-cell">
        {history.dateRejected ? formatDate(history.dateRejected) : "-"}
      </td>
      <td className="py-4 sm:py-1 text-gray-600 text-sm sm:text-base hidden sm:table-cell">
        {formatDate(history.dueDate)}
      </td>
      <td className="py-4 sm:py-1 text-sm sm:text-base hidden sm:table-cell">
        <span className={`inline-flex items-center px-2 sm:px-2.5 py-0.5 rounded-full text-xs font-medium ${
          history.status === "Paid" ? 'text-green-700 bg-green-50' : 'text-red-700 bg-red-50'
        }`}>
          {history.status}
        </span>
      </td>
    </tr>
  );
};

interface LoanHistoryProps {
  transactionHeader?: string;
  transactionDescription?: string;
  limit?: number;
}

export const LoanHistory: React.FC<LoanHistoryProps> = ({ 
  transactionHeader = "Savings History", 
  transactionDescription = "This is an overview of your savings activities", 
  limit 
}) => {
  const { token, user, setLoanHistory } = useAuth();
  const [loading, setLoading] = useState(true);
  const [history, setHistory] = useState<LoanHistoryItem[]>([]);
  const userId = user?.id;

  const getLoanHistory = async () => {
    if (!token || !userId) {
      setLoading(false);
      return;
    }

    setLoading(true);
    try {
      const requestUrl = `https://webapidev.subacapital.co/api/Loan/loan-history/${userId}`;
  
      const response = await fetch(requestUrl, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      });
  
      const result = await response.json();
  
      if (!response.ok) {
        const errorMessage =
          result?.message ||
          result?.error ||
          (result?.errors?.length > 0 ? result.errors[0].message : null) ||
          "Something went wrong, please try again.";
  
        throw new Error(errorMessage);
      }
        
        if (result.isSuccessful && result.data) {
        setHistory(result.data);
        setLoanHistory(result.data);
      }      

    } catch (error: any) {
      console.error('Error fetching savings history:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getLoanHistory();
  }, [token, userId]);

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64 bg-white">
        <Loader />
      </div>
    );
  }

  // Apply limit if provided
  const displayedHistory = limit ? history.slice(0, limit) : history;
  
  return (
    <div className="bg-white shadow-sm mt-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between mb-4 sm:mb-6">
        <div className="mb-4 sm:mb-0">
          <h3 className="text-base sm:text-xl font-semibold text-gray-900 mb-1">
            {transactionHeader}
          </h3>
          <p className="text-gray-600 text-xs sm:text-sm">
            {transactionDescription}
          </p>
        </div>
        {history.length > 0 && (
          <Link
            href="/loan/loanHistory"
            className="text-sm sm:text-base font-medium text-purple-600 hover:underline">
            View All
          </Link>
        )}
      </div>

      <div className="overflow-x-auto bg-[#F5F5F599] rounded-t-3xl p-4 px-10 border border-[#1C1C1C1A]">
        <table className="w-full min-w-full">
          <thead>
            <tr className="grid grid-cols-[1fr_1fr_1fr_1fr_1fr_1fr] border-b border-gray-100">
              <th className="text-left py-2 sm:py-3 text-gray-600 font-medium text-sm sm:text-base">
                Loan Amount
              </th>
              <th className="text-left py-2 sm:py-3 text-gray-600 font-medium text-sm sm:text-base">
                Date Requested
              </th>
              <th className="text-left py-2 sm:py-3 text-gray-600 font-medium text-sm sm:text-base">
                Date Approved
              </th>
              <th className="text-left py-2 sm:py-3 text-gray-600 font-medium text-sm sm:text-base">
                Date Rejected
              </th>
              <th className="text-left py-2 sm:py-3 text-gray-600 font-medium text-sm sm:text-base">
                Due Date
              </th>
              <th className="text-left py-2 sm:py-3 text-gray-600 font-medium text-sm sm:text-base">
                Status
              </th>
            </tr>
          </thead>
          <tbody>
            {displayedHistory.length > 0 ? (
              displayedHistory.map((item, index) => (
                <LoanRow 
                  key={item.loanId} 
                  history={item} 
                  index={index} 
                />
              ))
            ) : (
              <tr>
                <td colSpan={4} className="py-8 text-center text-gray-500">
                  No Loan history available
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};