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

const BalanceSheet = () => {
  const dispatch = useDispatch();
  const [pageConfig, setPageConfig] = useState({ query: "bs" });
  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(", ");
  }

  const { balanceSheet: data, loading } =
    useSelector((state) => state?.accounts) || null;
  useEffect(() => {
    dispatch(loadBalanceSheet(pageConfig));
  }, [dispatch, pageConfig]);

  return (
    <>
      <Card className="w-full">
        <div className="w-full">
          <div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 mb-4'>
            <h5 className='text-lg sm:text-xl flex flex-col sm:flex-row gap-2 items-start sm:items-center w-full sm:w-auto'>
              <span className='ml-0 sm:ml-2 whitespace-nowrap'>Balance Sheet</span>
              <div className={"filterTag w-full sm:min-w-[120px] sm:max-w-[150px]"}>
                <Select
                  placeholder={"Select Store"}
                  className='w-full'
                  loading={storeLoading}
                  defaultValue={defaultStore?.id}
                  mode={"multiple"}
                  showSearch={false}
                  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 && (
              <div className="w-full sm:w-auto">
                <BalanceSheetInvoice
                  data={data}
                  title={"Balance Sheet"}
                  store={storeName}
                />
              </div>
            )}
          </div>
          {!loading && (
            <div className='w-full shadow bg-white rounded overflow-hidden'>
              <div className='border-gray-200 w-full rounded bg-white overflow-x-auto'>
                <table className='w-full min-w-[280px]'>
                  <caption className='mt-2 mb-1 ml-2 font-semibold text-xs sm:text-sm md:text-base px-2 text-left'>
                    Assets
                  </caption>
                  <thead className='text-gray-600 text-[10px] sm:text-xs md:text-[13px] font-bold border-gray tracking-wider text-left hover:cursor-pointer uppercase border-b-2 border-gray-200'>
                    <tr className='border-b border-gray'>
                      <th
                        scope='col'
                        className='text-gray-200 border-gray border-b-2 border-t-2 border-gray-200 py-2 px-2 sm:px-3 md:px-4 bg-gray-900 text-left text-[10px] sm:text-xs md:text-sm font-semibold uppercase tracking-wider w-[60%] sm:w-[65%] md:w-[70%]'
                      >
                        Account
                      </th>
                      <th
                        scope='col'
                        className='text-gray-200 border-gray border-b-2 border-t-2 border-gray-200 py-2 px-2 sm:px-3 md:px-4 bg-gray-900 text-left text-[10px] sm:text-xs md:text-sm font-semibold uppercase tracking-wider w-[40%] sm:w-[35%] md:w-[30%]'
                      >
                        Amount
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {data &&
                      data?.assets.map((item, index) => {
                        return (
                          <tr
                            key={index}
                            className='hover:bg-gray-100 hover:cursor-pointer'
                          >
                            <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm break-words'>
                              {item.subAccount}
                            </td>
                            <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm whitespace-nowrap'>
                              {item.balance
                                ? Number(item.balance).toFixed(3)
                                : ""}
                            </td>
                          </tr>
                        );
                      })}

                    <tr className='hover:bg-gray-100 hover:cursor-pointer'>
                      <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm'>
                        {" "}
                        <strong>TOTAL</strong>
                      </td>
                      <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm whitespace-nowrap'>
                        <strong>{data?.totalAsset.toFixed(3) || ""}</strong>
                      </td>
                    </tr>

                    <tr>
                      <td colSpan="2" className='pt-4 pb-1'>
                        <h5 className='ml-2 font-semibold text-xs sm:text-sm md:text-base px-2'>
                          Liabilities
                        </h5>
                      </td>
                    </tr>

                    {data &&
                      data?.liabilities.map((item, index) => {
                        return (
                          <tr
                            key={index}
                            className='hover:bg-gray-100 hover:cursor-pointer'
                          >
                            <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm break-words'>
                              {item.subAccount}
                            </td>
                            <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm whitespace-nowrap'>
                              {item.balance
                                ? Number(item.balance).toFixed(3)
                                : ""}
                            </td>
                          </tr>
                        );
                      })}

                    <tr className='hover:bg-gray-100 hover:cursor-pointer'>
                      <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm'>
                        <strong>TOTAL</strong>
                      </td>
                      <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm whitespace-nowrap'>
                        <strong>{data?.totalLiability || ""}</strong>
                      </td>
                    </tr>

                    <tr>
                      <td colSpan="2" className='pt-4 pb-1'>
                        <h5 className='ml-2 font-semibold text-xs sm:text-sm md:text-base px-2'>
                          Equity
                        </h5>
                      </td>
                    </tr>

                    {data &&
                      data?.equity.map((item, index) => {
                        return (
                          <tr
                            key={index}
                            className='hover:bg-gray-100 hover:cursor-pointer'
                          >
                            <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm break-words'>
                              {item.subAccount}
                            </td>
                            <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm whitespace-nowrap'>
                              {item.balance
                                ? Number(item.balance).toFixed(3)
                                : ""}
                            </td>
                          </tr>
                        );
                      })}

                    <tr className='hover:bg-gray-100 hover:cursor-pointer'>
                      <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm'>
                        <strong>TOTAL</strong>
                      </td>
                      <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm whitespace-nowrap'>
                        <strong>{data?.totalEquity.toFixed(3) || ""}</strong>
                      </td>
                    </tr>
                    <tr className='hover:bg-gray-100 hover:cursor-pointer bg-gray-50'>
                      <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm break-words'>
                        {" "}
                        <strong>Total Liability and Equity</strong>
                      </td>
                      <td className='py-2 sm:py-3 md:py-4 px-2 sm:px-3 md:px-6 border-b border-gray-200 text-gray-900 text-[10px] sm:text-xs md:text-sm whitespace-nowrap'>
                        <strong>
                          {(data?.totalEquity + data?.totalLiability).toFixed(
                            3
                          ) || ""}
                        </strong>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          )}
          {loading && <Loader />}
        </div>
      </Card>
    </>
  );
};

export default BalanceSheet;
