import { useCallback, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { getSession } from "../../Services/Others";
import { changeBreadCrumb, getEmpAccess } from "../../Features/AppPage/CenterPage";
import { Messages } from "../../Components/Notifications/Messages";
import { Tables } from "../../Components/Tables/Table";
import FormHeader from "../PageComponents/FormHeader";
import Search from "../../Components/Forms/Search";
import Buttons from "../../Components/Forms/Buttons";
import {
    EditFilled,
    DeleteFilled,
    PlusOutlined,
    ReloadOutlined,
} from '@ant-design/icons';
import { useLocation, useNavigate } from "react-router-dom";
import { Space, Tooltip } from "antd";
import { deleteAutomatedReorder, getAutomatedReorderList } from "../../Features/PurchaseOrder/PurchaseOrder";
import { DefaultModal } from "../../Components/Modal/DefaultModal";
import { FaRegEye } from "react-icons/fa";
import { render } from "react-dom";
import { useAuth } from "../../AuthContext";
import "./AutomatedReorder.scss";

const subDirectory = import.meta.env.BASE_URL;

const items = [
    {
        name: 'Home',
        link: `${subDirectory}app-page/home`,
    },
    {
        name: 'Automated Reorder',
        link: `${subDirectory}setting/automated-reorder`,
    },
];



const AutomatedReorderList = () => {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const location = useLocation();
    const state = location?.state;
    const { SadminuserAccess } = useAuth();
    let SAAccessCommonMaster = SadminuserAccess?.find(
        (e) => e?.MenuName === 'Product Receipt'
    );

    const AppId = getSession('AppId');
    const CompId = getSession('CompId');
    const BranchId = getSession('BranchId');
    const UserId = getSession('UserId');
    const UserType = getSession('UserType');
    const [empData, setEmpData] = useState();
    const [addnewAccess, setaddnewAccess] = useState(true);

    const [messageType, setMessageType] = useState(null);
    const [messageData, setMessageData] = useState(null);
    const [supplierModalOpen, setSupplierModalOpen] = useState(false);
    const [supplierRecords, setSupplierRecords] = useState([]);
    const [supplierRecordIndex, setSupplierRecordIndex] = useState(null);
    const [page, setPage] = useState(1);


    const [searchedText, setSearchedText] = useState('');
    const [tableData, setTableData] = useState([]);

    const columns = [
        {
            title: 'SL.NO',
            dataIndex: 'SLNO',
            key: 'SLNO',
            width: '10%',
            render: (_, record, index) => index + 1,
            align: 'center',
        },
        {
            title: 'Product Name',
            dataIndex: 'ProdName',
            key: 'ProdName',
        },
        {
            title: 'Supplier',
            dataIndex: 'Supplier',
            key: 'Supplier',
            align: 'center',
            render: (_, record, index) => (
                // <div className="productMasterImageUpload">
                <Tooltip title={record.SupplierDetails ? 'View Image' : 'Upload Image'}>
                    <div>
                        <FaRegEye
                            style={{ background: 'none', cursor: 'pointer' }}
                            size={22}
                            color={record.SupplierDetails && '#1F9B3A'}
                            onClick={() => {
                                setSupplierModalOpen(true);
                                setSupplierRecords(record.SupplierDetails);
                                setSupplierRecordIndex(index);
                            }}
                        />
                    </div>
                </Tooltip>
            ),
        },
        {
            title: 'Order Type',
            dataIndex: 'OrderType',
            key: 'OrderType',
            render: (_, record, index) => (
                record.OrderType === 'E' ? 'End of Day (EOD)' : 'Immediate'
            )
        },
        {
            title: 'Confirmation Type',
            dataIndex: 'OrderProcessing',
            key: 'OrderProcessing',
            render: (_, record, index) => (
                record.OrderProcessing === 'Y' ? 'Need Confirmation' : 'Auto'
            )
        },
        {
            title: 'Reorder Quantity',
            dataIndex: 'OrderQty',
            key: 'OrderQty',
            align: 'center',
        },
        {
            title: 'Action',
            dataIndex: 'Action',
            key: 'Action',
            width: '100px',
            align: 'center',
            render: (_, record, index) => (

                record.ActiveStatus === 'A' ? (
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100%', gap: '10px' }}>
                        <EditFilled
                            style={{ color: '#1292EE' }}
                            onClick={() => handleEdit(record)}
                        />
                        <DeleteFilled
                            style={{ color: '#FF4D4F' }}
                            onClick={() => handleActiveAndDeactive(record)}
                        />
                    </div>
                ) : (
                    <ReloadOutlined
                        style={{ color: '#52C41A' }}
                        onClick={() => handleActiveAndDeactive(record)}
                    />
                )
            ),
        },
    ];

    const supplierColumns = [
        {
            title: 'SL.NO',
            dataIndex: 'SLNO',
            key: 'SLNO',
            width: '10%',
            render: (_, record, index) => index + 1
        },
        {
            title: 'Supplier Name',
            dataIndex: 'SuppName',
            key: 'SuppName',
            width: '20%',
        }
    ];

    useEffect(() => {
        try {
            if (AppId && CompId && BranchId) {
                dispatch(changeBreadCrumb({ items: items }));
                fetchData()
                if (state?.Notify) {
                    setMessageType(state?.Notify.messageType);
                    setMessageData(state?.Notify.messageData);
                }
            }
        } catch (error) {
            console.error(error, 'error: changeBreadCrumb');
        }
    }, [AppId, CompId, BranchId]);

    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 === 'Automated Reorder'
        );
        setEmpData(datas?.[0]);
    };

    const fetchData = async () => {
        try {
            const res = await dispatch(getAutomatedReorderList({ AppId, CompId, BranchId }))?.unwrap();
            if (res?.data?.statusCode === 1 && res?.data?.data?.length > 0) {
                setTableData(res?.data?.data)
            } else {
                setTableData([])
            }
        } catch (error) {
            console.error(error, 'error: getAutomatedReorderList');
        }
    }

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

    const handleAdd = () => {
        navigate(`${subDirectory}setting/automated-reorder/new`);
    }

    const handleEdit = (record) => {
        navigate(`${subDirectory}setting/automated-reorder/update`, {
            state: {
                editstate: record,
            }
        });
    }
    const handleActiveAndDeactive = async (record) => {
        const res = await dispatch(deleteAutomatedReorder({ UniqueId: record?.UniqueId, UpdatedBy: UserId, ActiveStatus: record?.ActiveStatus === 'A' ? 'D' : 'A' }))?.unwrap();
        if (res?.data?.statusCode === 1) {
            setMessageType('success');
            setMessageData(record?.ActiveStatus === 'A' ? 'Deactivated Successfully' : 'Activated Successfully');
            fetchData();
        } else {
            setMessageType('error');
            setMessageData(res?.data?.message);
        }
    }

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

    return (
        <section className="automated-reorder-list-container">
            <Messages
                messageType={messageType}
                messageData={messageData}
                onComplete={onComplete}
            />
            <div className="automated-reorder-list-wrapper">
                <div className="automated-reorder-list-header">
                    <div className="formAddNew">
                        <div>
                            <FormHeader title={'Automated Reorder'} />
                        </div>
                        <div className="searchAddDiv">
                            <div className="formSearch">
                                <Search
                                    placeholder="Search"
                                    onSearch={onSearch}
                                    onSearchChange={onSearchChange}
                                />
                            </div>
                            <Buttons
                                buttonText={'Add New'}
                                handleSubmit={handleAdd}
                                disabled={addnewAccess}
                                color="901D77"
                                icon={<PlusOutlined />}
                            />
                        </div>
                    </div>
                </div>
                <div className="automated-reorder-list-content">
                    <Tables
                        columns={columns}
                        data={tableData}
                        ownPagination={true}
                        pagination={{
                            current: page,
                            onChange: handlePageChange,
                            defaultPageSize: 10,
                            showSizeChanger: false,
                            hideOnSinglePage: true
                        }}
                    />
                </div>
            </div>
            <DefaultModal
                open={supplierModalOpen}
                title={'Suppliers'}
                width={500}
                footer={false}
                handleCancel={() => {
                    setSupplierModalOpen(false);
                    setSupplierRecords(null);
                    setSupplierRecordIndex(null);
                }}
                children={
                    <div className="automated-reorder-list-content">
                        <Tables
                            columns={supplierColumns}
                            data={supplierRecords}
                        />
                    </div>
                }
            />
        </section>
    )
}

export default AutomatedReorderList