import { useState, useEffect, useCallback } from 'react';
import { useDispatch } from 'react-redux';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js';
import { PlusOutlined } from '@ant-design/icons';
import { Tables } from '../../Components/Tables/Table';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { useNavigate, useLocation } from 'react-router-dom';
import Search from '../../Components/Forms/Search.jsx';
import { getSession } from '../../Services/Others';
import { Messages } from '../../Components/Notifications/Messages';
import '../../Styles/Employee/EmpMaster.scss';
import { getstockAdjustmentDetails } from '../../Features/PurchaseOrder/PurchaseOrder.js';
import Buttons from '../../Components/Forms/Buttons.jsx';
import { HiAdjustmentsHorizontal } from 'react-icons/hi2';

const subDirectory = import.meta.env.BASE_URL;
const items = [
  {
    name: 'Home',
    link: `${subDirectory}app-page/home`,
  },

  {
    name: 'Stock Adjustment',
    link: `${subDirectory}setting/stock-adjustment-list`,
  },
];

const StockadjustmentList = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();

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

  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [TableData, setTableData] = useState([]);
  const [filteredInfo, setFilteredInfo] = useState({});
  const [sortedInfo, setSortedInfo] = useState({});
  const [searchedText, setSearchedText] = useState('');
  const [page, setpage] = useState(1);

  async function fetchData() {
    try {
      let Response = await dispatch(
        getstockAdjustmentDetails({ CompId, AppId, BranchId })
      ).unwrap();
      if (Response?.data?.statusCode == 1) {
        setTableData(Response?.data?.data);
      } else {
        setTableData([]);
      }
    } catch (error) {
      setTableData([]);
      console.error('Error fetching stock adjustment details:', error);
    }
  }

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    if (location?.state?.Notiffy) {
      setMessageType(location?.state?.Notiffy.messageType);
      setMessageData(location?.state?.Notiffy.messageData);
    }
    fetchData();
  }, []);

  const handleChange = (pagination, filters, sorter) => {
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };

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

  const onSearch = (value) => {
    setSearchedText(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };
  function formatDate(dateString, Time = true) {
    // Split date and time
    const [datePart, timePart] = dateString.split('T');

    // Extract year, month, day
    const [year, month, day] = datePart.split('-');

    // Extract hours, minutes
    const [hourStr, minStr] = timePart.split(':');
    let hour = Number(hourStr);
    const minute = minStr;

    // AM/PM logic
    const ampm = hour >= 12 ? 'PM' : 'AM';
    hour = hour % 12;
    if (hour === 0) hour = 12;

    const months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec',
    ];
    if (Time) {
      return `${day} ${months[month - 1]} ${year} ${hour}:${minute} ${ampm}`;
    }
    return `${day} ${months[month - 1]} ${year} `;
  }

  const columns = [
    {
      title: 'SL.NO',
      key: 'sno',
      align: 'center',
      width: '60px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Product Name',
      dataIndex: 'ProductName',
      key: 'ProductName',
      width: '180px',
      render: (text, row) => (
        <a style={{ color: 'black', width: '200px' }}>
          {row.ProductName} {row.ProVariantName}
        </a>
      ),
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return String(record.ProductName)
          ?.toLowerCase()
          ?.includes(value?.toLowerCase());
      },
    },

    {
      title: ' Received Date',
      dataIndex: 'InwardDate',
      key: 'InwardDate',
      width: '200px',
      render: (text) => (
        <a style={{ color: 'black' }}>{formatDate(text, false)}</a>
      ),
    },
    {
      title: 'Modified Date',
      dataIndex: 'CreatedDate',
      key: 'CreatedDate',
      width: '200px',
      render: (text) => <a style={{ color: 'black' }}>{formatDate(text)}</a>,
    },
    {
      title: 'Previous Balance Qty',
      dataIndex: 'OldBalQty',
      key: 'OldBalQty',
      width: '180px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      align: 'center',
    },

    {
      title: 'Current Balance Qty',
      dataIndex: 'NewBalQty',
      key: 'NewBalQty',
      width: '150px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      align: 'center',
    },
  ];

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);
  const handelAddButton = () => {
    navigate(`${subDirectory}setting/stock-adjustment`);
  };

  return (
    <div className="userPageTable stockAdjustListMaster">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="formAddNew">
          <div>
            <FormHeader title={'Stock Adjustment'} />
          </div>
          
            <div className="formSearch">
              <Search
                placeholder="Search"
                onSearch={onSearch}
                onSearchChange={onSearchChange}
              />
            </div>
        
          <Buttons
            buttonText={'Stock Adjustment'}
            handleSubmit={() => handelAddButton()}
            color="901D77"
            icon={<HiAdjustmentsHorizontal size={18} />}
          />
        </div>
        <div className="reportTable1 stockAdjustTable">
          <Tables
            columns={columns}
            data={TableData}
            dataSource={TableData}
            pagination={handlePageChange}
            onChange={handleChange}
          />{' '}
        </div>
      </div>
    </div>
  );
};

export default StockadjustmentList;
