/* 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';

// Updated interface to match API response
export interface SavingsHistoryItem {
  savingsPlanId: string;
  amountSaved: number;
  date: string;
  savingsCategory: string;
}

export interface SavingsRowProps {
  history: SavingsHistoryItem;
  index: number;
}

const SavingsRow: React.FC<SavingsRowProps> = ({ history, index }) => {
  const isCredit = true;
  
  const formatDate = (dateString: string) => {
    // Returns: "04 July 2025"
    return dateString.split(',')[0];
  };
  
  return (
    <tr key={index} className="border-b border-gray-50 grid grid-cols-[3fr_1fr_1fr_1fr]">
      <td className="py-4 sm:py-1 text-gray-900 text-sm sm:text-base">
        {history.savingsCategory} Savings
      </td>
      <td className={`py-4 sm:py-1 text-sm sm:text-base font-medium ${isCredit ? 'text-green-600' : 'text-red-600'}`}>
        {isCredit ? '+' : ''}{formatAmount(history.amountSaved)}
      </td>
      <td className="py-4 sm:py-1 text-gray-600 text-sm sm:text-base hidden sm:table-cell">
        {formatDate(history.date)}
      </td>
      <td className="py-4 sm:py-1">
        <span className={`inline-flex items-center px-2 sm:px-2.5 py-0.5 rounded-full text-xs font-medium ${
          isCredit ? 'text-green-700 bg-green-50' : 'text-red-700 bg-red-50'
        }`}>
          Saved
        </span>
      </td>
    </tr>
  );
};

// Transaction History Component
interface SavingsHistoryProps {
  transactionHeader?: string;
  transactionDescription?: string;
  limit?: number;
}

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

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

    setLoading(true);
    try {
      const requestUrl = `https://webapidev.subacapital.co/api/savings/savings-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);
        setSavingsHistory(result.data)
      }

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

  useEffect(() => {
    getSavingsHistory();
  }, [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="/savings/allearnings"
            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-[3fr_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">
                Description
              </th>
              <th className="text-left py-2 sm:py-3 text-gray-600 font-medium text-sm sm:text-base">
                Amount
              </th>
              <th className="text-left py-2 sm:py-3 text-gray-600 font-medium text-sm sm:text-base hidden sm:table-cell">
                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) => (
                <SavingsRow 
                  key={item.savingsPlanId} 
                  history={item} 
                  index={index} 
                />
              ))
            ) : (
              <tr>
                <td colSpan={4} className="py-8 text-center text-gray-500">
                  No savings history available
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};