import { useState, useEffect, useCallback } from 'react';
import { Form, Checkbox, Switch } from 'antd';
import Buttons from '../../Components/Forms/Buttons';
import { InputField } from '../../Components/Forms/InputField';
import { DropDowns } from '../../Components/Forms/DropDown';
import './OtherServices.scss';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage';
import { useDispatch, useSelector } from 'react-redux';
import FormHeader from '../PageComponents/FormHeader';
import { getConfigTypeData } from '../../Features/ConfigMasterPage/ConfigMasterPage';
import { getSession } from '../../Services/Others';
import { ArrowRightOutlined } from '@ant-design/icons';
import { getAdmin, onlineimages, taxSelector } from '../../Features/ProductPage/ProductPage';
import {
  GetOtherServices,
  PostOtherServicesMaster,
  PutOtherServices,
} from '../../Features/OtherServices/OtherServices';
import { useLocation, useNavigate } from 'react-router-dom';
import { Messages } from '../../Components/Notifications/Messages';
import { uploadImage } from '../../Features/upload/upload';
import CropUpload from '../../Components/Forms/CropUpload';
import { DefaultModal } from '../../Components/Modal/DefaultModal';

const subDirectory = import.meta.env.BASE_URL;
const OtherServices = ({ formType }) => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();
  const state = location?.state;
  const editstate = state?.editstate;
  const [OtherServicesData, setOtherServices] = useState([]);
  const TaxData = useSelector(taxSelector);
  const [SelectedTaxId, setSelectedTaxId] = useState(null);
  const [serviceTotal, setServiceTotal] = useState(null);
  const [SelectedCategory, setSelectedCategory] = useState(null);
  const [ServiceName, setServiceName] = useState(null);
  const [serviceType, setServiceType] = useState(true);
  const [imageUrl, setImageUrl] = useState('');
  const [imageopen, setimageOpen] = useState(false);
  const [imagedata, setimagedata] = useState();
  const [selectedImage, setSelectedImage] = useState(null);
  const [onlineImage, setOnlineImage] = useState(null);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');

  console.log(SelectedCategory, 'SelectedCategory');
  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },

    {
      name: 'Other Services',
      link: `${subDirectory}setting/other-services`,
    },
  ];

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    FetchData();
    GetTaxName();
    formType === "add" && form.setFieldsValue({ ServiceType: "I" })
  }, [formType]);
  const FetchData = async () => {
    let response = await dispatch(
      getConfigTypeData({ TypeName: 'Other Services' })
    ).unwrap();
    // let data={
    //     AppId: AppId,
    //     CompId: CompId,
    //     BranchId: BranchId,

    // }
    // let responseGET = await dispatch(GetOtherServices(data)).unwrap();

    if (response?.data?.statusCode == 1) {
      // if (formType == 'add') {
      //   setOtherServices(
      //     response?.data?.data?.filter?.(
      //       (item) =>
      //         !responseGET?.data?.data?.some(
      //           (i) => i.ServiceCategory === item.ConfigId
      //         )
      //     )
      //   );
      // } else {
      setOtherServices(response?.data?.data);
      // }
    }
  };

  useEffect(() => {
    try {
      if (formType === 'edit') {
        if (editstate && OtherServicesData) {
          form.setFieldsValue({
            tax: editstate?.TaxId || null,
            category: editstate?.ServiceCategory || null,
            serviceName: editstate?.ServiceName || '',
            shortName: editstate?.ServiceShortName || '',
            serviceTax: editstate?.TaxAmt || '',
            serviceTotal: editstate?.TotalAmt || '',
            vehiclenumber: editstate?.VehicleNumberAllowed === 'Y',
            ServiceType: editstate?.ServiceType || 'I',
          });
          setServiceTotal(editstate?.TotalAmt);
          setSelectedTaxId(editstate?.TaxId);
          setServiceType(editstate?.ServiceType === 'I' ? true : false);
          setImageUrl(editstate?.ImageUrl || '');
          setServiceName(editstate?.ServiceName || '');
          setSelectedCategory(
            OtherServicesData?.find(
              (option) => option.ConfigId === editstate?.ServiceCategory
            )?.ConfigName
          );
        }
      }
    } catch (err) {
      console.log(err, 'err');
    }
  }, [OtherServicesData]);

  useEffect(() => {
    const total = Number(serviceTotal);
    if (total > 0 && SelectedTaxId) {
      const selectedTax = TaxData.find((t) => t.TaxId === SelectedTaxId);
      const taxPercent = selectedTax ? Number(selectedTax.TaxPercentage) : 0;
      if (taxPercent >= 0) {
        const serviceTax = (total * taxPercent) / (100 + taxPercent);
        const chargePerItem = total - serviceTax;
        form.setFieldsValue({
          serviceTax: serviceTax.toFixed(2),
          chargePerItem: chargePerItem.toFixed(2),
        });
      } else {
        form.setFieldsValue({
          serviceTax: '',
          chargePerItem: '',
        });
      }
    } else {
      form.setFieldsValue({
        serviceTax: '',
        chargePerItem: '',
      });
    }
  }, [serviceTotal, SelectedTaxId]);
  useEffect(() => {
    const total = Number(serviceTotal);
    if (total > 0 && SelectedTaxId) {
      const selectedTax = TaxData.find((t) => t.TaxId === SelectedTaxId);
      const taxPercent = selectedTax ? Number(selectedTax.TaxPercentage) : 0;
      if (taxPercent >= 0) {
        const serviceTax = (total * taxPercent) / (100 + taxPercent);
        const chargePerItem = total - serviceTax;
        form.setFieldsValue({
          serviceTax: serviceTax.toFixed(2),
          chargePerItem: chargePerItem.toFixed(2),
        });
      } else {
        form.setFieldsValue({
          serviceTax: '',
          chargePerItem: '',
        });
      }
    } else {
      form.setFieldsValue({
        serviceTax: '',
        chargePerItem: '',
      });
    }
  }, [serviceTotal, SelectedTaxId]);
  useEffect(() => {
    imagecall();
  }, [imageopen]);
  const imagecall = async () => {
    if (ServiceName !== null) {
      let response = await dispatch(onlineimages(ServiceName)).unwrap();
      setimagedata(response?.data?.data);
    }
  };
  const GetTaxName = async () => {
    await dispatch(getAdmin({ CompId: CompId, AppId: AppId })).unwrap();
  };
  const handleServiceTypeChange = (checked) => {
    setServiceType(checked);
    form.setFieldsValue({ ServiceType: checked ? 'I' : 'G' }); // Capital S
  };
  const updateImageUrl = (url) => {
    setImageUrl(url);
  };
  const addimages = () => {
    const data = form.getFieldValue('serviceName')
    console.log(data, 'servicename data');
    if (data !== undefined) {
      setimageOpen(true);
    } else {
      setMessageType('error');
      setMessageData('Enter your service name');
    }
  };
  const submitimage = async () => {
    let response = await fetch(selectedImage.image);

    let data = await response?.blob();
    let metadata = {
      type: 'image/jpeg',
    };

    let file = new File([data], 'image.jpg', metadata);
    let uploadImgData = await dispatch(uploadImage(file)).unwrap();
    if (uploadImgData?.data?.status) {
      setOnlineImage(uploadImgData?.data?.image);
      setImageUrl(uploadImgData?.data?.image);
    }
    form?.setFieldsValue({ OnlineImage: file });

    setimageOpen(false);
  };
  const handleimage = () => {
    setimageOpen(false);
    setOnlineImage('');
  };
  const onFinish = async (values) => {
    let TypeId = OtherServicesData?.find(
      (option) => option.ConfigId === values.category
    )?.TypeId;
    let Data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      TypeId: TypeId,
      ServiceCategory: values.category,
      ServiceName: values.serviceName,
      ServiceShortName: values.shortName,
      ServiceType: serviceType ? 'I' : 'G',
      TaxId: values.tax,
      TaxAmt: Number(values.serviceTax),
      Rate: values.chargePerItem,
      TotalAmt: values.serviceTotal,
      VehicleNumberAllowed: values.vehiclenumber ? 'Y' : 'N',
      ImageUrl: imageUrl,
    };

    if (formType === 'add') {
      Data['CreatedBy'] = UserId;
      let response = await dispatch(PostOtherServicesMaster(Data)).unwrap();
      if (response?.data?.statusCode === 1) {
        form.resetFields();
        setServiceTotal(null);
        setSelectedTaxId(null);
        FetchData();
        navigate(`${subDirectory}setting/other-services`, {
          state: {
            Notiffy: {
              messageType: 'success',
              messageData: response?.data?.response,
            },
          },
        });
      } else {
        setMessageType("error")
        setMessageData(response?.data?.response)
      }
    } else {
      Data['UpdatedBy'] = UserId;
      Data['ServiceId'] = editstate?.ServiceId;
      Data['ConfigTypeId'] = editstate?.ConfigTypeId;
      let Response = await dispatch(PutOtherServices(Data)).unwrap();

      if (Response?.data?.statusCode === 1) {
        form.resetFields();
        setServiceTotal(null);
        setSelectedTaxId(null);
        FetchData();
        navigate(`${subDirectory}setting/other-services`, {
          state: {
            Notiffy: {
              messageType: 'success',
              messageData: Response?.data?.response,
            },
          },
        });
      } else {
        setMessageType("error")
        setMessageData(Response?.data?.response)
      }
    }
  };
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);
  return (
    <div className="pageOverAll">
      <div className="other-services-container">
        <div style={{ marginBottom: '20px' }}>
          <div className="formName">
            <FormHeader title={'Other Services'} />
          </div>
        </div>
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{ onlineApplicable: false }}
        >
          <div className="other-service-row">
            <div className="other-service-group">
              <Form.Item
                name="category"
                rules={[{ required: true, message: 'Required' }]}
              >
                <DropDowns
                  options={[
                    ...OtherServicesData.map((option) => ({
                      value: option.ConfigId,
                      label: option.ConfigName,
                    })),
                  ]}
                  label="Category"
                  onChangeFunction={(val) => {
                    form.setFieldsValue({ category: val });
                    setSelectedCategory(
                      OtherServicesData?.find(
                        (option) => option.ConfigId === val
                      )?.ConfigName
                    );
                  }}
                  valueData={form.getFieldValue('category')}
                  disabled={formType == 'edit' ? true : false}
                />
              </Form.Item>
            </div>
            {SelectedCategory?.toLowerCase() == 'parking' && (
              <div
                className="other-service-group other-service-checkbox-group"
                style={{ display: 'flex', alignItems: 'flex-start', justifyContent: "center" }}
              >
                <Form.Item
                  name="vehiclenumber"
                  valuePropName="checked"
                  style={{ marginBottom: 0 }}
                >
                  <Checkbox
                    onChange={(e) =>
                      form.setFieldsValue({ vehiclenumber: e.target.checked })
                    }
                  >
                    vehicle number
                  </Checkbox>
                </Form.Item>
              </div>
            )}
          </div>
          <div className="other-service-row">
            <div className="other-service-group">
              <Form.Item
                name="serviceName"
                rules={[{ required: true, message: 'Required' }]}
              >
                <InputField
                  label="Service Name"
                  onChange={(e) => {
                    const value = e.target.value;
                    form.setFieldsValue({ serviceName: value });
                    setServiceName(value);
                    // if (!isShortNameManuallySet) {
                    // Get initials
                    const initials = value
                      .split(' ')
                      .filter(Boolean)
                      .map((word) => word[0]?.toUpperCase() || '')
                      .join('');
                    form.setFieldsValue({ shortName: initials });
                    // }
                  }}
                  isOnChange={!!form.getFieldValue('serviceName')}
                // isOnChange={ form.getFieldsValue('serviceName') ? true :false}
                />
              </Form.Item>
              <Form.Item
                shouldUpdate={(prev, curr) => prev.shortName !== curr.shortName}
              >
                {() => (
                  <Form.Item
                    name="shortName"
                    rules={[{ required: true, message: 'Required' }]}
                  >
                    <InputField
                      label="Short Name"
                      onChange={(e) => {
                        form.setFieldsValue({ shortName: e.target.value });
                      }}
                      isOnChange={!!form.getFieldValue('shortName')}
                    />
                  </Form.Item>
                )}
              </Form.Item>
              <Form.Item
                name="ServiceType"
                rules={[
                  {
                    message: "Please Select Service Type"
                  },
                ]}
              >
                <div className="switch-order-type">
                  <div className="switch-header required">Service Type</div>
                  <Switch
                    checked={serviceType}
                    onChange={handleServiceTypeChange}
                    checkedChildren="Individual"
                    unCheckedChildren="Group"
                  />
                </div>
              </Form.Item>

              <Form.Item
                name="tax"
                rules={[{ required: true, message: 'Required' }]}
              >
                <DropDowns
                  options={[
                    ...TaxData?.map((option) => ({
                      value: option.TaxId,
                      label: option.TaxIdName,
                    })),
                  ]}
                  label="Tax"
                  onChangeFunction={(val) => {
                    form.setFieldsValue({ tax: val });
                    setSelectedTaxId(val);
                  }}
                  valueData={form.getFieldValue('tax')}
                />
              </Form.Item>
              <Form.Item
                name="serviceTotal"
                rules={[{ required: true, message: 'Required' }]}
              >
                <InputField
                  label="Service Total (Inclusive of Tax) (₹)"
                  type="number"
                  onChange={(val) => setServiceTotal(val.target.value)}
                  isOnChange={!!form.getFieldValue('serviceTotal')}
                />
              </Form.Item>
              <Form.Item name="chargePerItem">
                <InputField
                  label="Charge Per Item (₹)"
                  type="number"
                  disabled={true}
                  isOnChange={serviceTotal ? true : false}
                />
              </Form.Item>
              <Form.Item name="serviceTax">
                <InputField
                  label="Service Tax (₹)"
                  type="number"
                  disabled={true}
                  isOnChange={serviceTotal ? true : false}
                />
              </Form.Item>
            </div>
            {/* <div className="other-service-group">
              
            </div> */}
            <div className="other-service-row-ServiceImage">
              <div className='ServiceImage'>
                <label>Service Image</label>
              </div>

              <div className="bothbtn">
                <CropUpload
                  onlineImage={onlineImage}
                  ImageLink={imageUrl}
                  updateImageUrl={updateImageUrl}
                />
                <div className="onlineimgplus">
                  <button
                    type="button"
                    className="onlinebtnProduct"
                    onClick={addimages}
                  >
                    Browse Image
                  </button>
                </div>
              </div>

              <DefaultModal
                title="ONLINE IMAGE UPLOADER"
                width={800}
                open={imageopen}
                footer={true}
                buttonText="Submit"
                children={
                  <Form className="">
                    <div className="productonlineImg">
                      {imagedata?.map((item, index) => (
                        <div
                          className={`singleimg ${selectedImage === item ? 'selected' : ''
                            }`}
                          key={index}
                          onClick={() => setSelectedImage(item)}
                        >
                          <img
                            src={item.image}
                            style={{ height: '100%', width: '100%' }}
                            alt="no image"
                          />
                        </div>
                      ))}
                    </div>
                  </Form>
                }
                handleSubmit={submitimage}
                handleCancel={handleimage}
              ></DefaultModal></div>
          </div>



          <div className="submitButton">
            <Buttons buttonText="SUBMIT" htmlType={true} icon={<ArrowRightOutlined />} />
          </div>
        </Form>
      </div>
    </div>
  );
};

export default OtherServices;
