import React, { useEffect, useState } from 'react'
import { Table } from 'react-bootstrap'
import ReactPaginate from 'react-paginate'
import { useSelector } from 'react-redux'
import { useLocation } from 'react-router-dom'
import Select from 'react-select'
import Swal from 'sweetalert2'
import { useImmer } from 'use-immer'
import DeleteIcon from '../../../components/AllSvgIcon/DeleteIcon'
import EditIcon from '../../../components/AllSvgIcon/EditIcon'
import HKBadge from '../../../components/Badges'
import Loader from '../../../components/Loader'
import CustomToast from '../../../components/Toast/CustomToast'
import { customStyles } from '../../../components/customStyles'
import { showToast } from '../../../lib/AllGlobalFunction'
import {
  allCrudNames,
  allPages,
  checkPageAccess
} from '../../../lib/AllPageNames'
import {
  currencyIcon,
  pageRangeDisplayed
} from '../../../lib/AllStaticVariables'
import axiosProvider from '../../../lib/AxiosProvider'
import { _productImg_ } from '../../../lib/ImagePath'
import { _SwalDelete, _exception } from '../../../lib/exceptionMessage'
import FlashSalePriceUpdate from './FlashSalePriceUpdate'

const FlashSaleCollectionMapping = () => {
  const [data, setData] = useState()
  const [dropDownData, setDropDownData] = useState()
  const [loading, setLoading] = useState(false)
  const [flashSalePriceMaster, setFlashSalePriceMaster] = useState({
    id: null,
    show: false,
    isDataUpdated: false
  })
  const [filterDetails, setFilterDetails] = useImmer({
    pageSize: 10,
    pageIndex: 1,
    collectionId: ''
  })
  const [toast, setToast] = useState({
    show: false,
    text: null,
    variation: null
  })
  const { pageAccess } = useSelector((state) => state.user)
  const { userId } = useSelector((state) => state?.user?.userInfo)
  const location = useLocation()

  const fetchData = async (id, pageIndex) => {
    try {
      setLoading(true)
      const response = await axiosProvider({
        method: 'GET',
        endpoint: 'ManageCollectionMapping/byCollectionId',
        queryString: `?pageIndex=${
          pageIndex ? pageIndex : filterDetails?.pageIndex
        }&pageSize=${filterDetails?.pageSize}&collectionId=${
          id ? id : filterDetails?.collectionId
        }`
      })
      setLoading(false)
      if (response?.status === 200) {
        setData(response)
      }
    } catch {
      setLoading(false)
    }
  }

  const fetchDropDownData = async () => {
    const response = await axiosProvider({
      method: 'GET',
      endpoint: 'ManageCollection/byType',
      queryString: `?type=Flashsale&pageindex=0&PageSize=0&status=Active&isLive=true`
    })
    if (response?.data?.code === 200) {
      setDropDownData(response?.data?.data)
    }
  }

  useEffect(() => {
    fetchDropDownData()
  }, [])

  const handlePageClick = (event) => {
    fetchData(filterDetails?.collectionId, event.selected + 1)
    setFilterDetails((draft) => {
      draft.pageIndex = event.selected + 1
    })
  }

  const handleDelete = async (id, collectionId) => {
    try {
      setLoading(false)
      const response = await axiosProvider({
        method: 'DELETE',
        endpoint: 'ManageCollectionMapping',
        queryString: `?id=${id}`,
        userId,
        location: location.pathname
      })
      setLoading(false)

      if (response?.status === 200) {
        fetchData(collectionId)
        setFilterDetails((draft) => {
          draft.collectionId = collectionId
        })
      }

      showToast(toast, setToast, response)
    } catch {
      setLoading(false)
      showToast(toast, setToast, {
        data: {
          message: _exception?.message,
          code: 204
        }
      })
    }
  }

  useEffect(() => {
    if (flashSalePriceMaster?.isDataUpdated) {
      fetchData(flashSalePriceMaster?.collectionId)
      setFilterDetails((draft) => {
        draft.collectionId = flashSalePriceMaster?.collectionId
      })
    }
  }, [flashSalePriceMaster?.isDataUpdated])

  return (
    <>
      <div className='d-flex align-items-center mb-3 gap-3'>
        <div className='input-select-wrapper flex-fill'>
          <label className='form-label'>Flash Sale List</label>
          <Select
            styles={customStyles}
            id='collectionList'
            menuPortalTarget={document.body}
            menuPosition={'fixed'}
            options={dropDownData?.map(({ id, name }) => ({
              value: id,
              label: name
            }))}
            onChange={(e) => {
              fetchData(e?.value, 1)
              setFilterDetails((draft) => {
                draft.collectionId = e?.value
                draft.pageIndex = 1
              })
            }}
          />
        </div>
      </div>

      {toast?.show && (
        <CustomToast text={toast?.text} variation={toast?.variation} />
      )}

      {flashSalePriceMaster?.show && (
        <FlashSalePriceUpdate
          flashSalePriceMaster={flashSalePriceMaster}
          setFlashSalePriceMaster={setFlashSalePriceMaster}
          loading={loading}
          setLoading={setLoading}
          setToast={setToast}
          toast={toast}
        />
      )}

      {loading && <Loader />}
      {data?.data?.data?.length > 0 ? (
        <Table responsive className='align-middle table-list'>
          <thead>
            <tr>
              <th>Product Details</th>
              <th>Brand</th>
              <th>Pricing Details</th>
              <th>Sale Pricing</th>
              <th>Quantity</th>
              <th>Sale Status</th>
              <th>Product Status</th>
              <th>Live</th>
              {checkPageAccess(
                pageAccess,
                allPages?.flashSaleCollectionMapping,
                [allCrudNames?.update, allCrudNames?.delete]
              ) && <th className='text-center'>Action</th>}
            </tr>
          </thead>
          <tbody>
            {data?.data?.data?.length > 0 ? (
              data?.data?.data?.map((data) => (
                <tr
                  className='position-relative'
                  key={Math.floor(Math.random() * 10000000)}
                >
                  <td>
                    <div className='d-flex gap-2'>
                      <img
                        style={{ width: '60px', height: 'auto' }}
                        className='img-thumbnail'
                        src={`${process.env.REACT_APP_IMG_URL}${_productImg_}${data?.image1}`}
                        alt='...'
                      />
                      <p className='pv-font-hard mb-1'>{data?.productName}</p>
                    </div>
                  </td>
                  <td>{data?.brandName}</td>
                  <td>
                    <div className='d-flex flex-column gap-1 align-items-start'>
                      <div className='badge text-bg-light'>
                        <span className='pv-font-hard'>Selling Price : </span>
                        <span>
                          {currencyIcon} {data?.sellingPrice}
                        </span>
                      </div>
                      <div className='badge text-bg-light'>
                        <span className='pv-font-hard'>MRP : </span>
                        <span>
                          {currencyIcon} {data?.mrp}
                        </span>
                      </div>
                      <div className='badge text-bg-light'>
                        <span className='pv-font-hard'>Discount : </span>
                        <span>{data?.discount}%</span>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div className='d-flex flex-column gap-1 align-items-start'>
                      <div className='badge text-bg-light'>
                        <span className='pv-font-hard'>Selling Price : </span>
                        <span>
                          {currencyIcon}
                          {data?.saleSellingPrice
                            ? data?.saleSellingPrice
                            : data?.sellingPrice}
                        </span>
                      </div>
                      <div className='badge text-bg-light'>
                        <span className='pv-font-hard'>MRP : </span>
                        <span>
                          {currencyIcon}{' '}
                          {data?.saleMRP ? data?.saleMRP : data?.mrp}
                        </span>
                      </div>
                      <div className='badge text-bg-light'>
                        <span className='pv-font-hard'>Discount : </span>
                        <span>
                          {data?.saleDiscount
                            ? data?.saleDiscount
                            : data?.discount}
                          %
                        </span>
                      </div>
                    </div>
                  </td>
                  <td className='text-center'>{data?.quantity}</td>
                  <td className='text-center'>
                    <HKBadge
                      badgesbgname={
                        data?.saleStatus?.toLowerCase() === 'active' ? 'success' : 'danger'
                      }
                      badgesTxtname={data?.saleStatus ?? 'Inactive'}
                      badgeClassname={''}
                    />
                  </td>
                  <td>
                    <HKBadge
                      badgesbgname={
                        data?.status === 'Active' ? 'success' : 'danger'
                      }
                      badgesTxtname={data?.status}
                      badgeClassname={''}
                    />
                  </td>
                  <td>{data?.productLive ? 'Yes' : 'No'}</td>
                  {checkPageAccess(
                    pageAccess,
                    allPages?.flashSaleCollectionMapping,
                    [allCrudNames?.update, allCrudNames?.delete]
                  ) && (
                    <td className='text-center'>
                      <div className='d-flex gap-2 justify-content-center'>
                        {checkPageAccess(
                          pageAccess,
                          allPages?.flashSaleCollectionMapping,
                          allCrudNames?.update
                        ) && (
                          <span
                            onClick={() => {
                              setFlashSalePriceMaster({
                                show: !flashSalePriceMaster?.show,
                                productId: data?.productId,
                                sellerId: data?.sellerId,
                                collectionId: data?.collectionId,
                                collectionMappingId: data?.id
                              })
                            }}
                          >
                            <EditIcon bg='bg' />
                          </span>
                        )}
                        {checkPageAccess(
                          pageAccess,
                          allPages?.flashSaleCollectionMapping,
                          allCrudNames?.delete
                        ) && (
                          <span
                            onClick={() => {
                              Swal.fire({
                                title: _SwalDelete.title,
                                text: _SwalDelete.text,
                                icon: _SwalDelete.icon,
                                showCancelButton: _SwalDelete.showCancelButton,
                                confirmButtonColor:
                                  _SwalDelete.confirmButtonColor,
                                cancelButtonColor:
                                  _SwalDelete.cancelButtonColor,
                                confirmButtonText:
                                  _SwalDelete.confirmButtonText,
                                cancelButtonText: _SwalDelete.cancelButtonText
                              }).then((result) => {
                                if (result.isConfirmed) {
                                  handleDelete(data?.id, data?.collectionId)
                                } else if (result.isDenied) {
                                }
                              })
                            }}
                          >
                            <DeleteIcon bg='bg' />
                          </span>
                        )}
                      </div>
                    </td>
                  )}
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={9} className='text-center'>
                  {data?.data?.message}
                </td>
              </tr>
            )}
          </tbody>
        </Table>
      ) : (
        <h5 className='text-center'>{data?.data?.message}</h5>
      )}

      {data?.data?.pagination?.pageCount > 0 && (
        <ReactPaginate
          className='list-inline m-cst--pagination d-flex justify-content-end gap-1'
          breakLabel='...'
          nextLabel=''
          onPageChange={handlePageClick}
          pageRangeDisplayed={pageRangeDisplayed}
          pageCount={data?.data?.pagination?.pageCount}
          previousLabel=''
          renderOnZeroPageCount={null}
          forcePage={filterDetails?.pageIndex - 1}
        />
      )}
    </>
  )
}

export default FlashSaleCollectionMapping
