import { useState, useEffect, useCallback } from 'react';
import { useDispatch } from 'react-redux';
import { Space } from 'antd';
import {
  EditFilled,
  DeleteFilled,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../Features/AppPage/CenterPage.js';
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 Buttons from '../../Components/Forms/Buttons';
import {
  getCustBasedOnCmpIdBrIdAppId,
  delCust,
} from '../../Features/CustMaster/CustMaster.js';
import { getSession, roundToDecimal } from '../../Services/Others.js';
import { Messages } from '../../Components/Notifications/Messages';
import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx';
import { useAuth } from '../../AuthContext.jsx';
import { getPreferenceData } from '../../Features/BookingScreen/BookingData/BookingData.js';

const subDirectory = import.meta.env.BASE_URL;

const items = [
  {
    name: 'Home',
    link: `${subDirectory}app-page/home`,
  },

  {
    name: 'Customer',
    link: `${subDirectory}setting/customer-master`,
  },
];

const CustomerMaster = () => {
  const { SadminuserAccess } = useAuth();

  console.log(SadminuserAccess, 'SadminuserAccess');

  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Customer'
  );
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();

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

  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);
  const [CostomerDeActivate, seCostomerDeActivate] = useState(false);
  const [rowData, serowData] = useState([]);
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);
  const [allowDecimal, setAllowDecimal] = useState(false);


  async function fetchData() {
    if (location?.state?.Notiffy) {
      setMessageType(location?.state?.Notiffy.messageType);
      setMessageData(location?.state?.Notiffy.messageData);
    }

    if (BranchId) {
      const gettingTableData = await dispatch(
        getCustBasedOnCmpIdBrIdAppId({ CompId, BranchId, AppId })
      ).unwrap();
      if (gettingTableData?.data?.statusCode === 1) {
        setTableData(gettingTableData?.data?.data);
      }
    }
  }

  useEffect(() => {
    try {
      fetchData();
    } catch (err) {
      console.log(err, 'err');
    }
    // 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 === 'Customer'
    );
    setEmpData(datas?.[0]);
  };

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

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

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

  const actionsFormatter = async (row, rowIndex) => {
    if (row.ActiveStatus !== 'D') {
      navigate(
        `${subDirectory}setting/customer-master/update`,
        { state: { editstate: row } },
        { key: rowIndex }
      );
    }
  };
  const getPreference = async () => {
    const data = { AppId: AppId, CompId: CompId, BranchId: BranchId };
    const { data: res } = await dispatch(getPreferenceData(data)).unwrap()
    const decimalSetting = res?.data?.[0]?.SettingDtlDetails?.find((setting) => setting?.SettingIdName?.toLowerCase() === "decimal" && setting?.SettingValue === 'Y');
    if (decimalSetting) {
      setAllowDecimal(true)
    }
  }

  //Delete
  const statusFormatter = async (row) => {
    if (row?.creditBal > 0 && row.ActiveStatus == 'A') {
      // setMessageType("warning");
      // setMessageData("Customer Has a Credit Balance");
      seCostomerDeActivate(true);
      serowData(row);
    } else {
      let deleteData = {
        CustId: row.CustId,
        ActiveStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
        UpdatedBy: UserId,
      };
      let response = await dispatch(delCust(deleteData)).unwrap();
      if (response?.data?.statusCode == 1) {
        fetchData();
        setMessageType('success');
        setMessageData(
          row.ActiveStatus == 'A'
            ? 'In-Activated Successfully'
            : 'Activated Successfully'
        );
      }
    }
  };

  const Deactivateuser = async (row) => {
    let deleteData = {
      CustId: row.CustId,
      ActiveStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
      UpdatedBy: UserId,
    };
    let response = await dispatch(delCust(deleteData)).unwrap();
    if (response?.data?.statusCode == 1) {
      fetchData();
      seCostomerDeActivate(false);
      serowData([]);
      setMessageType('success');
      setMessageData(
        row.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );
    }
  };
  // const statusFormatter = async (row) => {

  //   let deleteData = {
  //     CustId: row.CustId,
  //     ActiveStatus: row.ActiveStatus == "A" ? "D" : "A",
  //     UpdatedBy: UserId,
  //   };
  //   let response = await dispatch(delCust(deleteData)).unwrap();
  //   if (response?.data?.statusCode == 1) {
  //     fetchData();
  //     setMessageType("success");
  //     setMessageData(
  //       row.ActiveStatus == "A"
  //         ? "In-Activated Successfully"
  //         : "Activated Successfully"
  //     );
  //   }
  // };

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

  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '50px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Name',
      dataIndex: 'CustName',
      key: 'CustName',
      width: '100px',
      render: (text, row) => (
        <a style={{ color: 'black', width: '200px' }}>
          {(row?.CustName ? (row?.CustName + ' ') : '') + (row?.CustShortName || "") || row?.CustMobile}
        </a>
      ),
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return (
          String(record.CustShortName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.CustName)?.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',
      dataIndex: 'CustMobile',
      key: 'CustMobile',
      width: '100px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
    },

    {
      title: 'GSTIN',
      dataIndex: 'CustGSTIN',
      key: 'CustGSTIN',
      width: '50px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
    },
    {
      title: 'Discount',
      dataIndex: 'Discount',
      key: 'Discount',
      width: '100px',
      align: 'right',
      render: (_, record, index) => (
        <a style={{ color: 'black' }}>
          {record?.OfferType == 'F'
            ? '₹' + roundToDecimal(record?.OfferValue, allowDecimal)
            : record?.OfferValue + '%'}
        </a>
      ),
    },

    {
      title: 'Discount Status',
      dataIndex: 'OfferActiveStatus',
      key: 'OfferActiveStatus',
      width: '100px',
      render: (_, record, index) => (
        <a style={{ color: 'black' }}>
          {record?.OfferActiveStatus == 'A' ? 'Active' : 'Deactivate'}
        </a>
      ),
    },
    // {
    //   title: "Address",
    //   key: "sno",
    //   align: "center",
    //   width: "200px",
    //   render: (text, row) => {
    //     const { Address1, City, Dist, State, Zip } = row;

    //     // Check if all fields are not null or undefined
    //     if (Address1 && City && Dist && State && Zip) {
    //       return (
    //         <a style={{ color: "black" }}>
    //           {`${Address1}, ${City}, ${Dist}, ${State}, ${Zip}`}
    //         </a>
    //       );
    //     }

    //     return null; // Return null if any field is null or undefined
    //   },
    //   ellipsis: true,
    // },
    {
      title: 'Credit Balance',
      key: 'creditBal',
      align: 'center',
      dataIndex: 'creditBal',
      width: '100px',
      render: (text, row) => {
        return <a style={{ color: 'black' }}>{safeRound(text)}</a>;
      },
      // ellipsis: true,
    },
    // creditBal
    {
      title: 'Action',
      key: 'Action',
      dataIndex: 'Action',
      width: '100px',
      render: (_, record, index) =>
        TableData.length >= 1 ? (
          <Space size="middle">
            {/* edit cmd */}
            {record.ActiveStatus === 'A' ? (
              <a>
                <EditFilled
                  style={{ color: '#1292EE' }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                    (UserType === 'Super Admin User' &&
                      SAAccessCommonMaster?.UpdateAccess === 'Y') ||
                    (UserType === 'Employee' &&
                      empData?.UpdateAccess === 'Y') ||
                    UserType === 'Admin'
                      ? actionsFormatter(record, index)
                      : null
                  }
                />
              </a>
            ) : (
              ''
            )}
            <a>
              {record.ActiveStatus === 'A' ? (
                <DeleteFilled
                  style={{
                    color: '#FF4D4F',
                  }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                    (UserType === 'Super Admin User' &&
                      SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                    (UserType === 'Employee' &&
                      empData?.DeleteAccess === 'Y') ||
                    UserType === 'Admin'
                      ? statusFormatter(record)
                      : null
                  }
                />
              ) : (
                <ReloadOutlined
                  style={{
                    color: '#52C41A',
                  }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                    (UserType === 'Super Admin User' &&
                      SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                    (UserType === 'Employee' &&
                      empData?.DeleteAccess === 'Y') ||
                    UserType === 'Admin'
                      ? statusFormatter(record)
                      : null
                  }
                />
              )}
            </a>
          </Space>
        ) : null,
    },
  ];

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

  const handelAddButton = () => {
    navigate(`${subDirectory}setting/customer-master/new`);
  };

  function safeRound(amountStr) {
    if (amountStr == null) return allowDecimal ? '0.00' : '0';

    const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
    const num = Number(cleaned);

    if (isNaN(num)) return allowDecimal ? '0.00' : '0';

    return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
  }
  return (
    <div className="userPageTable">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="formAddNew">
          <div>
            <FormHeader title={'Customer'} />
          </div>
          <div className="searchAddDiv">
            <div className="formSearch">
              <Search
                placeholder="Search"
                onSearch={onSearch}
                onSearchChange={onSearchChange}
              />
            </div>
            <Buttons
              buttonText={'Add New'}
              disabled={addnewAccess}
              handleSubmit={() => handelAddButton()}
              color="901D77"
              icon={<PlusOutlined />}
            >
              OPEN
            </Buttons>
          </div>
        </div>
        <div className="reportTable">
          <Tables
            columns={columns}
            data={TableData}
            dataSource={TableData}
            pagination={handlePageChange}
            onChange={handleChange}
          />{' '}
        </div>
      </div>
      {console.log(rowData, 'checkrowData4')}
      <DefaultModal
        open={CostomerDeActivate}
        title="Deactivate Customer"
        handleCancel={() => {
          seCostomerDeActivate(false);
        }}
        footer={false}
        width={450}
        children={
          <div
            style={{
              display: 'flex',
              padding: '20px',
              gap: '1rem 2rem',
              flexWrap: 'wrap',
              alignItems: 'end',
              flexDirection: 'column',
            }}
          >
            <h3>
              The customer has &#8377;{rowData?.creditBal} Credit balance. Are
              you sure you want to deactivate?
            </h3>
            <button
              onClick={() => Deactivateuser(rowData)}
              style={{
                padding: '10px 15px',
                backgroundColor: '#ff4d4f',
                border: 'none',
                borderRadius: '5px',
                color: '#fff',
                cursor: 'pointer',
                width: 'max-content',
              }}
              className=""
            >
              Deactivate
            </button>
          </div>
        }
      />
    </div>
  );
};

export default CustomerMaster;
