import { useCallback, useEffect, useMemo, useState } from 'react';
import Buttons from '../../Components/Forms/Buttons';
import Search from '../../Components/Forms/Search';
import { Messages } from '../../Components/Notifications/Messages';
import { Tables } from '../../Components/Tables/Table';
import FormHeader from '../PageComponents/FormHeader';
import dayjs from 'dayjs';
import { PlusOutlined } from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import {
  dateTimeFormatChange,
  ExtractDateFormate,
  getSession,
} from '../../Services/Others';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage';
import { DatePicker, Modal, Table } from 'antd';
import { getRequestStock } from '../../Features/RequestStock/RequestStock';
import { EyeOutlined } from '@ant-design/icons';
const subDirectory = import.meta.env.BASE_URL;

const StockTransferList = () => {
  const AppId = getSession('AppId');
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const [selectedComponent, setselectedComponent] = useState('C');
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [TableData, setTableData] = useState([]);
  const [viewModalOpen, setViewModalOpen] = useState(false);
  const [selectedRequest, setSelectedRequest] = useState(null);
  const [searchedText, setSearchedText] = useState('');
  const [page, setpage] = useState(1);
  const [selectedDate, setSelectedDate] = useState(dayjs());

  const navigate = useNavigate();
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
  }, []);

  useEffect(() => {
    getRequestData();
  }, [selectedComponent]);

  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
    {
      name: 'Transfer List',
      link: `${subDirectory}setting/stock-transferlist`,
    },
  ];

  const getRequestData = async () => {
    const data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      RequestStatus: selectedComponent,
    };
    const response = await dispatch(getRequestStock(data)).unwrap();
    if (response?.data?.statusCode == 1) {
      setTableData(response?.data?.data);
    } else {
      setTableData([]);
    }
  };
  const handelCreate = () => {
    navigate(`${subDirectory}setting/stock-transfer`, {
      state: { transform: 'Create' },
    });
  };
  const handelRequest = () => {
    navigate(`${subDirectory}setting/stock-transfer`, {
      state: { transform: 'Request' },
    });
  };
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const onSearch = (value) => {
    setSearchedText(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };

  const handlePageChange = (current) => {
    setpage(current);
  };
  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '60px',
      render: (text, record, index) => (
        <span>{(page - 1) * 10 + index + 1}</span>
      ),
    },
    {
      title: selectedComponent === 'C' ? 'Create Date' : 'Request Date',
      dataIndex: 'CreatedDate',
      key: 'CreatedDate',
      width: '180px',
      render: (text) => <span>{dateTimeFormatChange(text)}</span>,
    },
    {
      title: 'Request  From',
      dataIndex: 'FromBranchName',
      key: 'FromBranchName',
      width: '150px',
      render: (text) => <span>{text}</span>,
    },
    {
      title: 'Request To',
      dataIndex: 'ToBranchName',
      key: 'ToBranchName',
      width: '150px',
      render: (text) => <span>{text}</span>,
    },
    {
      title: 'No Of Item',
      dataIndex: 'ProductDetail',
      key: 'ProductDetail',
      width: '100px',
      align: 'center',
      render: (_, record) => (
        <span
          style={{ cursor: 'pointer', color: '#1890ff' }}
          onClick={() => {
            setSelectedRequest(record?.ProductDetail);
            setViewModalOpen(true);
          }}
        >
          {record?.ProductDetail?.length}
        </span>
      ),
    },
    {
      title: 'OverAll Qty',
      key: 'ProductDetail',
      width: '50px',
      align: 'right',
      render: (_, record) => (
        <span>
          {record?.ProductDetail?.reduce(
            (sum, item) => sum + (item?.RequestQty || 0),
            0
          )}
        </span>
      ),
    },
  ];

  const ComponentSelect = (value) => {
    setselectedComponent(value);
  };

  const filteredTableData = useMemo(() => {
    let data = [...TableData];

    if (searchedText) {
      data = data.filter(
        (item) =>
          item?.FromLocationName?.toLowerCase().includes(
            searchedText.toLowerCase()
          ) ||
          item?.ToLocationName?.toLowerCase().includes(
            searchedText.toLowerCase()
          )
      );
    }

    if (selectedDate) {
      const selected = dayjs(selectedDate).format('YYYY-MM-DD');

      data = data.filter(
        (item) => dayjs(item.CreatedDate).format('YYYY-MM-DD') === selected
      );
    }

    return data;
  }, [TableData, searchedText, selectedDate]);

  return (
    <>
      <div className="userPageTable">
        <div className="userPageContent">
          <Messages
            messageType={messageType}
            messageData={messageData}
            onComplete={onComplete}
          />
          <div className="formAddNew">
            <div
              style={{
                width: 'auto',
                whiteSpace: 'nowrap',
              }}
              className="ProductMasterListSwitchBTN"
            >
              <div
                className={selectedComponent === 'C' ? 'selected' : ''}
                onClick={() => ComponentSelect('C')}
              >
                {' '}
                Create Transfer
              </div>
              <div
                className={selectedComponent === 'R' ? 'selected' : ''}
                onClick={() => ComponentSelect('R')}
              >
                {' '}
                Request Transfer
              </div>
            </div>

            <div className="searchAddDiv">
              <div className="formSearch">
                {/* <Search
                                    placeholder="Search"
                                    onSearch={onSearch}
                                    onSearchChange={onSearchChange}
                                /> */}
                <DatePicker
                  placeholder="search Date"
                  value={selectedDate}
                  onChange={(date) => setSelectedDate(date)}
                  allowClear
                  format="DD-MM-YYYY"
                  disabledDate={(current) =>
                    current && current > dayjs().endOf('day')
                  }
                />
              </div>
              <div style={{ display: 'flex', gap: '10px' }}>
                {selectedComponent === 'C' && (
                  <Buttons
                    buttonText={'Create Transfer'}
                    handleSubmit={() => handelCreate()}
                    color="901D77"
                    icon={<PlusOutlined />}
                  ></Buttons>
                )}
                {selectedComponent === 'R' && (
                  <Buttons
                    buttonText={'Request Transfer'}
                    handleSubmit={() => handelRequest()}
                    color="901D77"
                    icon={<PlusOutlined />}
                  ></Buttons>
                )}
              </div>
            </div>
          </div>
          <div className="reportTable">
            <Tables
              columns={columns}
              // data={TableData}
              // dataSource={TableData}
              data={filteredTableData}
              dataSource={filteredTableData}
              pagination={handlePageChange}
              onChange={''}
            />
          </div>
          <Modal
            title="Request Product Details"
            open={viewModalOpen}
            onCancel={() => {
              setViewModalOpen(false);
              setSelectedRequest([]);
            }}
            footer={null}
            width={800}
          >
            <Table
              columns={[
                {
                  title: 'Product Name',
                  dataIndex: 'ProdName',
                },
                // {
                //     title: 'Product ID',
                //     dataIndex: 'ProdId',
                // },
                {
                  title: 'Variant Name',
                  render: (_, record) =>
                    record?.ProdVariantDetails?.[0]?.ProdVariantName || '-',
                },
                {
                  title: 'Requested Qty',
                  dataIndex: 'RequestQty',
                },
              ]}
              dataSource={selectedRequest}
              pagination={false}
              rowKey={(record, index) => index}
            />
          </Modal>
        </div>
      </div>
    </>
  );
};
export default StockTransferList;
