import { Card, Select } from "antd";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { loadTrailBalance } from "../../redux/rtk/features/account/accountSlice";
import TrailBalanceInvoice from "../Invoice/TrailBalanceInvoice";
import Loader from "../Loader/Loader";

const TrialBalance = () => {
  const dispatch = useDispatch();
  
  const { trailBalance: data, loading } =
  useSelector((state) => state?.accounts) || [];

  const [pageConfig, setPageConfig] = useState({ query: "tb" });
  const {list: store,loading: storeLoading,defaultStore} = useSelector((state) => state.store);

  const handleChange = (value, key) => {
    setPageConfig({ ...pageConfig, [key]: value });
  };
  let storeName = null;
  if (store && pageConfig.storeId) {
    const filteredStore = store.filter((item) =>
      pageConfig.storeId.includes(item.id)
    );
    storeName = filteredStore.map((item) => item.name).join(", ");
  }

  useEffect(() => {
    dispatch(loadTrailBalance(pageConfig));
  }, [dispatch, pageConfig]);
  return (
    <>
      <Card>
        <div>
          <div className='flex flex-col sm:flex-row justify-between items-start sm:items-center mb-2 gap-3'>
            <h5 className='text-lg sm:text-xl flex flex-col sm:flex-row gap-2 mb-0 sm:mb-3 w-full sm:w-auto'>
              <span className='ml-0 sm:ml-2'>Trail Balance</span>
              <div className={"filterTag min-w-full sm:min-w-[120px] sm:max-w-[150px]"}>
                <Select
                  placeholder={"Select Store"}
                  className=''
                  loading={storeLoading}
                  defaultValue={defaultStore?.id}
                  mode={"multiple"}
                  showSearch={false}
                  style={{ width: "100%" }}
                  maxTagPlaceholder={(item) => (
                    <div className=''>{item.length} Selected</div>
                  )}
                  maxTagCount={0}
                  onChange={(value) => handleChange(value, "storeId")}
                >
                  {store.map((option) => (
                    <Select.Option key={option.id} value={option.id}>
                      {option.name}
                    </Select.Option>
                  ))}
                </Select>
              </div>
            </h5>
            {data && (
              <TrailBalanceInvoice
                data={data}
                title={"Trail Balance"}
                store={storeName}
              />
            )}
          </div>
          {!loading && (
            <div className='border-gray-200 w-full rounded bg-white overflow-x-auto'>
              <table className='table report-section-table w-full min-w-[500px]'>
                <thead className='font-Popins text-black/70 bg-tableHeaderBg border-gray-200'>
                  <tr className='border-b border-gray'>
                    <th
                      scope='col'
                      className='py-3 sm:py-[14px] pl-2 sm:pl-3 text-left whitespace-nowrap tracking-wide text-sm sm:text-base'
                    >
                      Account
                    </th>
                    <th
                      scope='col'
                      className='py-3 sm:py-[14px] pl-2 sm:pl-3 text-left whitespace-nowrap tracking-wide text-sm sm:text-base'
                    >
                      Debit
                    </th>
                    <th
                      scope='col'
                      className='py-3 sm:py-[14px] pl-2 sm:pl-3 text-left whitespace-nowrap tracking-wide text-sm sm:text-base'
                    >
                      Credit
                    </th>
                  </tr>
                </thead>
                <tbody className='bg-tableBg'>
                  {data &&
                    data?.debits?.map((item, index) => {
                      return (
                        <tr
                          key={index}
                          className='hover:bg-slate-900/10 border-b'
                        >
                          <td className='py-2 pl-2 sm:pl-3 whitespace-nowrap text-sm sm:text-base'>
                            {item.subAccount}
                          </td>
                          <td className='py-2 pl-2 sm:pl-3 whitespace-nowrap text-sm sm:text-base'>
                            {item.balance
                              ? Number(item.balance).toFixed(3)
                              : ""}
                          </td>
                          <td className='py-2 pl-2 sm:pl-3 whitespace-nowrap text-sm sm:text-base'></td>
                        </tr>
                      );
                    })}
                  {data &&
                    data?.credits?.map((item, index) => {
                      return (
                        <tr
                          key={index}
                          className='hover:bg-slate-900/10 border-b'
                        >
                          <td className='py-2 pl-2 sm:pl-3 whitespace-nowrap text-sm sm:text-base'>
                            {item.subAccount}
                          </td>
                          <td className='py-2 pl-2 sm:pl-3 whitespace-nowrap text-sm sm:text-base'></td>
                          <td className='py-2 pl-2 sm:pl-3 whitespace-nowrap text-sm sm:text-base'>
                            {item.balance
                              ? Number(item.balance).toFixed(3)
                              : ""}
                          </td>
                        </tr>
                      );
                    })}

                  <tr className='hover:bg-gray-100 hover:cursor-pointer font-semibold'>
                    <td className='py-3 sm:py-4 px-3 sm:px-6 border-b border-gray-200 text-gray-900 text-sm'>
                      TOTAL
                    </td>
                    <td className='py-3 sm:py-4 px-3 sm:px-6 border-b border-gray-200 text-gray-900 text-sm'>
                      {data?.totalDebit
                        ? Number(data?.totalDebit).toFixed(3)
                        : "-"}
                    </td>
                    <td className='py-3 sm:py-4 px-3 sm:px-6 border-b border-gray-200 text-gray-900 text-sm'>
                      {data?.totalCredit
                        ? Number(data?.totalCredit).toFixed(3)
                        : "-"}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          )}
          {loading && <Loader />}
        </div>
      </Card>
    </>
  );
};

export default TrialBalance;
