import { ENDPOINTS } from "@/api/apiEndpoints";
import API, { ApiMethods } from "@/api/apiFunction";
import functions from "@/utils/functions";
import React, { useEffect, useState } from "react";
import FullPageLoader from "../common/loader/FullPageLoader";
import DataTableCommon from "../common/Datatable";
import { ColumnArrayType } from "../common/Datatable/type";
import viewDetails from "../../assets/view_icon.svg";
import Link from "next/link";
import { useRouter } from "next/router";

const Dealers = () => {
  const [dealersData, setDealersData] = useState<object[]>([]);
  const [loader, setLoader] = useState<boolean>(true);
  const router = useRouter();
  // TABLE COLUMN
  const tableColumns = [
    {
      name: "DEALER ID",
      selector: (row: { dealerID: string }) => row.dealerID,
      sortable: true,
      cell: (row: { dealerID: string; leadData: unknown }) => (
        <Link href={`dealers/details/${(row?.leadData as { id: string })?.id}`}>
          {row.dealerID}
        </Link>
      ),
    },
    {
      name: "name",
      selector: (row: { name: string }) => row.name,
      sortable: true,
    },
    {
      name: "email",
      selector: (row: { email: string }) => row.email,
      sortable: true,
    },
    {
      name: "phone",
      selector: (row: { phone: string }) => row.phone,
      sortable: true,
    },
    {
      name: "totle inventory count",
      selector: (row: { totleInventoryCount: string }) => row.totleInventoryCount,
      sortable: true,
    },
    {
      name: "totle leads count",
      selector: (row: { totleLeadsCount: string }) => row.totleLeadsCount,
      sortable: true,
    },
    {
      name: "Action",
      selector: (row: { action: string }) => row.action,
      cell: (row: { leadData: object }) => (
        <div className="action_buttons">
          <button
            className="btn btn_green"
            onClick={() => {
              router?.push(`dealers/details/${(row?.leadData as { id: string })?.id}`)
            }}
          >
            <img src={viewDetails?.src ?? ""} alt="Reject" />
            View Details
          </button>
        </div>
      ),
    },
  ];

  

  // GET DEALERS DATA
  const getDealersData = async () => {
    setLoader(true);
    try {
      const leadsRes = await API(ENDPOINTS.getDealers, ApiMethods.GET); 
      const data = (leadsRes?.data as { data: [] })?.data;
      setLoader(false);
      if (leadsRes?.status && Array.isArray(data) && data?.length) {
        // Get require data from res
        const getRequreData = data.map((lead: Record<string, string>) => {
          return {
            dealerID: functions.checkEmpty(lead?.DealerID) ??"N/A",
            name: functions.applyCharactersLimits(lead?.Name, 15) ?functions.applyCharactersLimits(lead?.Name, 15):"N/A",
            email: functions.checkEmpty(lead?.dealeremail),
            phone: functions.checkEmpty(lead?.phone),
            totleInventoryCount: lead?.inventory_count!='0'?functions.checkEmpty(lead?.inventory_count):0,
            totleLeadsCount: lead?.marketplacelead_count!='0'?functions.checkEmpty(lead?.marketplacelead_count):0,
            leadData: lead as object,
          };
        });
        setDealersData(getRequreData);
      } else {
        setDealersData([]);
      }
    } catch (e) {
      console.log(e, "error");
      setDealersData([]);
      setLoader(false);
    }
  };

  useEffect(() => {
    getDealersData();
  }, []);

  return (
    <div className="ds_inr_box">
      {loader ? (
        <FullPageLoader />
      ) : (
        <>
          <h1>Dealers</h1>
          <div className="ds_data_table">
            <DataTableCommon
              title="Dealer Leads"
              columns={tableColumns as unknown as ColumnArrayType[]}
              rowsData={dealersData as ColumnArrayType[]}
            />
          </div>
        </>
      )}
    </div>
  );
};

export default Dealers;
