import React, { useCallback, useEffect, useState } from 'react';
import {
  EditFilled,
  DeleteFilled,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { Messages } from '../../Components/Notifications/Messages';
import FormHeader from '../PageComponents/FormHeader';
import Buttons from '../../Components/Forms/Buttons';
import { Tables } from '../../Components/Tables/Table';
import { Space, Table } from 'antd';
import { useDispatch } from 'react-redux';
import {
  getWholeSaleProductEntry,
  getwsPreorder,
} from '../../Features/WholeSale/ProductEntry';
import { getSession } from '../../Services/Others';
import { IoEye } from 'react-icons/io5';
import { DefaultModal } from '../../Components/Modal/DefaultModal';
import { useNavigate } from 'react-router-dom';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../Features/AppPage/CenterPage';
import Search from '../../Components/Forms/Search';
import { DatePicProd } from '../../Components/Forms/DatePickerProduct';
import moment from 'moment';
import { useAuth } from '../../AuthContext';

const subDirectory = import.meta.env.BASE_URL;
const WsPreOrderList = () => {
  const { SadminuserAccess } = useAuth();
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Preorder'
  );

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

  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserType = getSession('UserType');

  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [page, setpage] = useState(1);
  const [page2, setpage2] = useState(1);
  const [filteredInfo, setFilteredInfo] = useState({});
  const [sortedInfo, setSortedInfo] = useState({});
  const [CommonDataFilter, setCommonDataFilter] = useState([]);
  const [ProductDetailopen, setProductDetailopen] = useState(false);
  const [Productdata, setProductdata] = useState([]);
  const [searchedText, setSearchedText] = useState('');
  const [WsPreorderDate, setWsPreorderDate] = useState();
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);

  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
    {
      name: 'Preorder',
      link: `${subDirectory}setting/wholesale-preorder`,
    },
  ];

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    const todayDate = new Date()?.toISOString()?.split('T')[0];
    FetchFilterData(todayDate);
    // if (UserType === "Employee") {
    //     fetchApi()
    // }
  }, []);
  useEffect(() => {
    if (UserType === 'Employee') {
      fetchApi();
    }
  }, [UserType]);
  useEffect(() => {
    let hasAccess = false;

    if (UserType === 'Admin' || UserType === 'Super Admin') {
      hasAccess = true;
    } else if (UserType === 'Employee') {
      hasAccess = empData?.AddAccess === 'Y';
    } else if (UserType === 'Super Admin User') {
      hasAccess = SAAccessCommonMaster?.AddAccess === 'Y';
    }

    setaddnewAccess(!hasAccess);
  }, [empData, SAAccessCommonMaster, UserType]);

  const fetchApi = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      EmpId: UserId,
    };
    let response = await dispatch(getEmpAccess(data)).unwrap();
    let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
      (item) => item.ConfigName === 'Preorder'
    );
    setEmpData(datas?.[0]);
  };

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    const day = String(date.getDate()).padStart(2, '0'); // Ensure two digits
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
    const year = date.getFullYear();
    return `${day}-${month}-${year}`;
  };

  const ActionFormatter = (row, rowIndex) => {
    navigate(
      `${subDirectory}setting/wholesale-preorder/update`,
      { state: { editstate: row } },
      { key: rowIndex }
    );
  };
  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '100px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Customer Name',
      dataIndex: 'CustName',
      key: 'CustName',
      width: '100px',
      render: (text, record, row) => (
        <a style={{ color: 'black', width: '200px' }}>
          {record?.CustShortName || record?.CustName || record?.CustMobile}
        </a>
      ),
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return (
          String(record.CustShortName)
            ?.toLowerCase()
            .includes(value?.toLowerCase()) ||
          String(record.CustName)?.toLowerCase().includes(value?.toLowerCase()) ||
          String(record.DueDate)?.toLowerCase().includes(value?.toLowerCase()) ||
          String(record.CustMobile)?.toLowerCase().includes(value?.toLowerCase())
        );
      },
      sorter: (a, b) => a?.CustName?.length - b?.CustName?.length,
      sortOrder: sortedInfo.columnKey === 'CustName' ? sortedInfo.order : null,
      ellipsis: true,
    },

    {
      title: 'Mobile No',
      dataIndex: 'CustMobile',
      key: 'CustMobile',
      width: '100px',
      render: (text) => (
        <a style={{ color: 'black', width: '200px' }}>{text}</a>
      ),
    },
    {
      title: 'Date',
      dataIndex: 'DueDate',
      key: 'DueDate',
      width: '100px',
      render: (text) => (
        <a style={{ color: 'black', width: '200px' }}>{formatDate(text)}</a>
      ),
    },
    {
      title: 'Product_Details',
      key: 'ProductDetails',
      dataIndex: 'ProductDetails',
      align: 'center',
      width: '100px',
      render: (text, row) => (
        <Space size="middle">
          <a>
            <IoEye
              style={{ color: '#1292EE', fontSize: '25px', cursor: 'pointer' }}
              onClick={() => ViewProduct(row)}
            />
          </a>
        </Space>
      ),
    },
    // {
    //     title: "Action",
    //     key: "Action",
    //     dataIndex: "Action",
    //     width: "100px",
    //     render: (_, record, index) =>
    //       CommonDataFilter.length >= 1 ? (
    //         <Space size="middle">
    //             <a>
    //               <EditFilled
    //                 style={{ color: "#1292EE" }}
    //                 onClick ={()=>ActionFormatter(record, index)}

    //                 />
    //             </a>
    //         </Space>
    //       ) : null,
    //   },
  ];
  const ProductdataColumns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '50px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page2 - 1) * 10 + index + 1}</a>
      ),
    },

    {
      title: 'Product Name',
      dataIndex: 'ProdName',
      key: 'ProdName',
      width: '200px',
    },
    {
      title: 'Size',
      dataIndex: 'RequestedQty',
      key: 'RequestedQty',
      align: 'right',
    },
    {
      title: 'UOM',
      dataIndex: 'UomName',
      key: 'UomName',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
    },
    {
      title: 'Status',
      dataIndex: 'ActiveStatus',
      key: 'ActiveStatus',
      render: (text) => (
        <a style={{ color: text == 'A' ? 'green' : 'red' }}>
          {text == 'A' ? 'Active' : 'Deactive'}
        </a>
      ),
    },
  ];

  // const FetchData = async () => {
  //     let response = await dispatch(getwsPreorder({ "CompId": CompId, "AppId": AppId, "BranchId": BranchId })).unwrap()

  //     if (response?.data?.statusCode == 1) {
  //         setCommonDataFilter(response?.data?.data)
  //     }
  // }

  const ViewProduct = (record) => {
    setProductDetailopen(true);
    setProductdata(record?.ProductDetails);
  };

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const handlePageChange = (current) => {
    setpage(current);
  };
  const handlePageChange2 = (current) => {
    setpage2(current);
  };

  const handleChange = (pagination, filters, sorter) => {
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };
  const handleProductCancel = () => {
    setProductDetailopen(false);
  };
  const navigateToProductEntry = () => {
    navigate(`${subDirectory}setting/wholesale-preorder/new`);
  };

  const onSearch = (value) => {
    setSearchedText(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };
  const FetchFilterData = async (date) => {
    let response = await dispatch(
      getwsPreorder({
        CompId: CompId,
        AppId: AppId,
        BranchId: BranchId,
        Date: date,
      })
    ).unwrap();

    if (response?.data?.statusCode == 1) {
      setCommonDataFilter(response?.data?.data);
    } else {
      setCommonDataFilter([]);
    }
  };
  const wsPreOrderDate = async (date, dateString) => {
    if (dateString) {
      const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );
      console.log(Date1.split('T')[0], 'Date1Date1');
      setWsPreorderDate(Date1);
      FetchFilterData(Date1.split('T')[0]);
    } else {
      setWsPreorderDate(null);
    }
  };

  return (
    <div className="userPageTable2">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div>
          <div>
            <FormHeader title={'Preorder'} />
          </div>
          <div className="searchAddDiv">
            <div className="formSearch">
              <Search
                placeholder="Search"
                onSearch={onSearch}
                onSearchChange={onSearchChange}
              />
            </div>
            <DatePicProd
              canSelectPast={true}
              onChange={wsPreOrderDate}
              valueData={WsPreorderDate}
              dontallowfeature={true}
            />
            <Buttons
              buttonText={'Add New'}
              handleSubmit={() => navigateToProductEntry()}
              disabled={addnewAccess}
              color="901D77"
              icon={<PlusOutlined />}
            >
              OPEN
            </Buttons>
          </div>
        </div>

        <div className="reportTable">
          <Tables
            columns={columns}
            data={CommonDataFilter}
            pagination={handlePageChange}
            onChange={handleChange}
          />
        </div>
      </div>
      {console.log('Productdata', Productdata)}
      <DefaultModal
        open={ProductDetailopen}
        title="Product Details"
        handleCancel={handleProductCancel}
        footer={false}
        width={1000}
        children={
          <div style={{ height: '400px', overflowY: 'scroll' }}>
            <div className="reportTable important-style">
              <Tables
                dataSource={Productdata}
                data={Productdata}
                columns={ProductdataColumns}
                pagination={handlePageChange2}
              />
            </div>
          </div>
        }
      />
    </div>
  );
};

export default WsPreOrderList;
