import React, { FC, useState, useEffect } from 'react';
import NairaBag from '../../assets/images/dashboard/naira-bag.png';
import {useNavigate} from 'react-router-dom'
import { Button, Icons } from '../';
import { useSelector } from 'react-redux';
import PendingList from '../paginated-list/PendingList';
import { PendingTableList } from '../../core/models';
import { NewDateTimeFormatter } from '../../lib/NewDateTimeFormatter';
import { getUserPendingLoanList } from '../../core/apiRequest';
import {FormatAmount} from '../../lib/FormatAmount'
import PendingLoanPopout from './PendingLoanPopout';
import { RouteHandler } from '../../router/routes';

export interface DashBoardCardProps {
  title?: string;
  desc?: string;
  descSpan?: string;
  descSpanClass?: string;
  onClick?: any;
  cardClass?: string;
  titleClass?: string;
  descClass?: string;
  btnTitle?: string;
  btnTextClass?: string;
  image?: any;
  imgClass?: string;
}

export const DashBoardCard: React.FC<DashBoardCardProps> = ({
  title,
  desc,
  onClick,
  cardClass,
  titleClass,
  descClass,
  descSpan,
  descSpanClass,
  btnTitle,
  btnTextClass,
  image,
  imgClass,
}) => {
  return (
    <div
      className={`h-full w-full rounded-lg p-5 shadow-lg hover:shadow-none bg-no-repeat bg-[90%] flex justify-between gap-4 items-center transition-all duration-300 ${
        cardClass && cardClass
      }`}
      // onClick={onClick}
    >
      <div className="w-3/4 flex flex-col gap-[2.3125rem]">
        {title && (
          <h1
            className={`mb-1 text-[#FFF] text-lg text-left font-bold ${
              titleClass && titleClass
            }`}
          >
            {title}
          </h1>
        )}
        {desc && (
          <p className={`text-lg text-left ${descClass && descClass}`}>
            {desc}{' '}
            {descSpan && (
              <span className={`${descSpanClass && descSpanClass}`}>
                {descSpan}
              </span>
            )}
          </p>
        )}
        {btnTitle && (
          <Button className={btnTextClass} text={btnTitle} onClick={onClick} />
        )}
      </div>
      {image && <img className={imgClass} src={image} alt="card-image" />}
    </div>
  );
};

interface DashboardHomeIntroProps {
  handleNextStep: (value: {}) => any;
  step?: number | string;
}

interface PopoutProps<T> {
  show?: boolean
  data?: T
}

const DashboardHomeIntro: FC<DashboardHomeIntroProps> = ({
  handleNextStep,
  step,
}) => {

  const navigate = useNavigate()
  const { userDetails } = useSelector((state: any) => state?.userDetails); // CHECKS IF USER Details are avaliable

  const [loanPopout, setLoanPopout] = useState<PopoutProps<PendingTableList>>({show:false, data:{}})
  const closePopout = () => {
    setLoanPopout({show:false, data:{}})
  }

  const [userLoanList, setUserLoanList] = useState<{
    loading: boolean;
    data: Array<PendingTableList>;
  }>({ loading: true, data: [] });

  useEffect(() => {
    let token = localStorage.getItem('token');
    let uid = localStorage.getItem('uid');
    if (!token || !uid) {
      return;
    }
    getUserPendingLoanList(uid)
      .then((res) => {
        if (!res || !res.data.loans) {
          setUserLoanList({ loading: false, data: [] });
          return;
        }
        setUserLoanList({ loading: false, data: res?.data?.loans });
      })
      .catch((err) => {
        setUserLoanList({ loading: false, data: [] });
        console.log(err)
      });
  }, []);

  return (
    <>
      <div className="w-full">
        {step == 1 ? (
          <>
            <h1 className="font-bold my-5 text-2xl">
              Hello, {userDetails.firstname}
            </h1>
            <div className="group w-full lg:w-[27.8125rem] h-[12.75rem] mt-7 ">
              <DashBoardCard
                cardClass="bg-[#5C2684] relative"
                desc="Begin your application and get up to "
                descSpan="5 million naira loan."
                descClass="leading-[1.5625rem] text-lg text-white"
                descSpanClass="font-bold"
                btnTitle="Apply here"
                btnTextClass="w-[11.125rem] h-[2.8125rem] flex justify-center item-center btn-W text-[#FBB700]"
                image={NairaBag}
                imgClass="translate-y-4 -rotate-6"
                onClick={() => handleNextStep({})}
              />
            </div>
          </>
        ) : (
          <>
            <h1 className="font-bold my-5 text-2xl">
              Welcome Back, {userDetails.firstname}
            </h1>
            <div className="group w-full lg:w-[27.8125rem] h-[12.75rem] mt-7 ">
              <DashBoardCard
                cardClass="bg-[#5C2684] relative"
                desc="Your loan application has been reviewed and accepted, please confirm for disbursement."
                // descSpan="5 million naira loan."
                descClass="leading-[1.5625rem] text-lg text-white"
                // descSpanClass="font-bold"
                btnTitle="View and accept"
                btnTextClass="w-[11.125rem] h-[2.8125rem] flex justify-center item-center btn-W text-[#FBB700]"
                image={NairaBag}
                imgClass="translate-y-4 -rotate-6"
                // onClick={handleNextStep}
              />
            </div>
          </>
        )}
        {userLoanList.loading ? null : (
          <div className="mt-5 w-full">
            <PendingList
              data={userLoanList.data}
              itemsPerPage={5}
              tableTitle="Current Applications"
            >
              {(data: any) => (
                <div className="w-full p-4 rounded-lg shadow-lg bg-white overflow-x-auto min-h-[250px] max-h-[450px]">
                  <table className="text-[12px] sm:text-base w-full table-auto">
                    <thead>
                      <tr className="text-left border-b-2">
                        <th className="px-1 py-4">Date</th>
                        <th className="px-1 py-4 text-right">Amount</th>
                        <th className="px-1 py-4 text-center min-w-[110px]">
                          Payment Term
                        </th>
                        <th className="px-1 py-4 text-center">Status</th>
                        <th className="px-1 py-4 text-right">Action</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.map((item: any, index: any) => (
                        <tr key={index || item} className="even:bg-slate-100">
                          <td className="px-1 py-2">
                            {NewDateTimeFormatter(item?.added)}
                          </td>
                          <td className="px-1 py-2 text-right">
                            {FormatAmount(item?.loan_amount)}
                          </td>
                          <td className="px-1 py-2 text-center">
                            {item?.payment_month}
                          </td>
                          <td className="px-1 py-2 text-center">
                            <button 
                              className={`${!item?.status_text?.button && 'pointer-events-none border-0'} border p-2`}
                              onClick={()=>setLoanPopout({show:true, data:item})}
                            >
                              {item?.status_text?.text || 'Pending'}
                            </button> 
                          </td>
                          <td className="flex justify-end px-1 py-2 text-right">
                            <button className="flex flex-nowrap items-center px-2 py-1 border-2 border-black" onClick={()=>navigate(RouteHandler.dashboardReference, {state:{application_uid: item?.application_uid}})}>
                              View
                              <Icons name="arrow-right" />
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </PendingList>
          </div>
        )}
      </div>
      
      {loanPopout.show && <PendingLoanPopout data={loanPopout.data} action={closePopout} />}
    </>
  );
};

export default DashboardHomeIntro;

//  {/* <div className="group w-full lg:w-96 h-32">
//         <DefaultCard
//           descText="You currently do not have any open application. Click on apply for a loan to get started."
//           iconName="arrow"
//           iconColor="#FBB700"
//           cardClass={`p-4 bg-[#FFFAFA] border border-[#EE4040]`}
//           descTextClass="text-[#423131] leading-5"
//           onClick={() => {
//             console.log("working");
//           }}
//         />
//       </div> */}

//       {/* <div className="w-full mt-20 flex gap-16 flex-wrap">
//         <div className="group h-40 w-full lg:w-80">
//           <DefaultCard
//             title="Apply for a loan"
//             descText="You currently do not have any open application. Click on apply for a loan to get started."
//             iconName="greater-than"
//             iconColor="#FFF"
//             cardClass={`bg-[#5C2684] bg-[url('../../../src/assets/images/dashboard/card_bg.png')]`}
//             titleClass="text-[#FFF]"
//             descTextClass="text-[#EFEFEF] leading-5"
//             onClick={() => {
//               console.log("working");
//             }}
//           />
//         </div>
//         <div className="group h-40 w-full lg:w-80">
//           <DefaultCard
//             title="Loan history"
//             descText="You currently do not have any open application. Click on apply for a loan to get started."
//             iconName="greater-than"
//             iconColor="#FFF"
//             cardClass={`bg-[#635D4D] bg-[url('../../../src/assets/images/dashboard/card_bg.png')]`}
//             titleClass="text-[#FFF]"
//             descTextClass="text-[#EFEFEF] leading-5"
//             onClick={() => {
//               console.log("working");
//             }}
//           />
//         </div>
//         <div className="group h-40 w-full lg:w-80">
//           <DefaultCard
//             title="How it works?"
//             descText="Steps to follow to complete your loan application successfully."
//             iconName="greater-than"
//             iconColor="#FFF"
//             cardClass={`bg-[#635D4D] bg-[url('../../../src/assets/images/dashboard/card_bg.png')]`}
//             titleClass="text-[#FFF]"
//             descTextClass="text-[#EFEFEF] leading-5"
//             onClick={() => {
//               console.log("working");
//             }}
//           />
//         </div>
//       </div> */}
