import {ItemCategoryService,ItemSubCategoryService,ItemsService,} from '@gtpl/shared-services/masters';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import {Button,Card,Col,Divider,Form,Input,Popconfirm,Row,Select,Table,Tag,Tooltip, message,} from 'antd';
import React, { useEffect, useState } from 'react';
import { EditOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { ColumnProps } from 'antd/lib/table';
import { ItemCategoryRequest, ItemsReqForCategoryId } from '@gtpl/shared-models/masters';
import { EnquiriesService } from 'libs/shared-services/enquiry-management/src/lib/enquiries-service';

export interface EnquiryPackingProductProps {
  packBomDetails: any;
  // updateDetails: any;
  enquiryId:number
}
export function EnquiryProductPackingForm(props: EnquiryPackingProductProps) {
  const [itemsForm] = Form.useForm();
  const { Option } = Select;

  const [tableData, setTableData] = useState<any[]>([]);
  const [defaultFormData, setDefaultFormData] = useState<any>([]);
  const [isUpdate, setIsUpdate] = useState<boolean>(false);
  const [indexVal, setIndexVal] = useState(undefined);
  const itemCatService = new ItemCategoryService();
  const [itemCatData, setItemCatData] = useState<any[]>([]);
  const itemSubService = new ItemSubCategoryService();
  const [itemSubData, setItemSubData] = useState<any[]>([]);
  const itemsService = new ItemsService();
  const [itemsData, setItemsData] = useState<any[]>([]);
  const [enqUpdateData, setEnqUpdateData] = useState([])

  let itemData: any[] = [];
  const enquiryService = new EnquiriesService()

  // useEffect(() => {
  //   if(props?.updateDetails){
  //     setTableData(props?.updateDetails)
  //   }
  // },[props?.updateDetails]);

  useEffect(() => {
    getItemCats();
  }, []);

  useEffect(() =>{
    if(props.enquiryId != 0){
      getEnquiryDetailsById(props.enquiryId)
    }
    },[props.enquiryId])

    const getEnquiryDetailsById = (enquiryId) =>{
      enquiryService.getAllEnquiryDetailsById({enquiryid:enquiryId}).then(res =>{
        if(res.status){
          setEnqUpdateData(res.data)
          setTableData(res?.data[0]?.packBomDetails)
          // props.packBomDetails(res?.data[0]?.packBomDetails)
        }else{
          setEnqUpdateData([])
        }
      })
    }
  const getItemCats = () => {
    itemCatService.getActiveItemCategories().then((res) => {
            setItemCatData(res.data);
    });
  };

  const getItemSubCats = () => {
    const req = new ItemCategoryRequest(itemsForm.getFieldValue('itemCategoryId'))
    itemSubService.getItemSubCategoriesForCategoryDropDown(req).then((res) => {
        setItemSubData(res.data)
    });
  };

  const getItems = () => {
    const req = new ItemsReqForCategoryId(itemsForm.getFieldValue('itemCategoryId'),itemsForm.getFieldValue('itemSubCategoryId'))
    itemsService.getItemForCategoryAndSubCat(req).then((res) => {
      setItemsData(res.data);
    });
  };

  const setEditForm = (rowData: any, index) => {
    console.log(rowData);
    console.log(index);
    setDefaultFormData(rowData);
    setIsUpdate(true);
    setIndexVal(index);
  };

  const deleteData = (index: any) => {
    itemData = [...tableData];
    itemData.splice(index, 1);
    setTableData(itemData);
    props.packBomDetails(itemData)
  };

  useEffect(() => {
    console.log(defaultFormData,'==-qwe56789')
    if (defaultFormData) {
      itemsForm.setFieldsValue({itemCategoryId: defaultFormData.itemCategoryId,});
      // itemsForm.setFieldsValue({itemCategory: defaultFormData.itemCategory})
      itemsForm.setFieldsValue({itemSubCategoryId: defaultFormData.itemSubCategoryId})
      // itemsForm.setFieldsValue({itemSubCategory: defaultFormData.itemSubCategory})
      itemsForm.setFieldsValue({ itemId: defaultFormData.itemId });
      // itemsForm.setFieldsValue({ itemName: defaultFormData.itemName})
      itemsForm.setFieldsValue({ quantity: defaultFormData.quantity });
    }
  }, [defaultFormData]);

  const itemCatOnChange =(val,option)=>{
    itemsForm.setFieldsValue({itemCategory: option?.name})
    getItemSubCats()
  }

  const itemSubCatOnChange =(val,option)=>{
    itemsForm.setFieldsValue({itemSubCategory: option?.name})
    getItems()
  }

  const itemsOnChange =(val,option)=>{
    itemsForm.setFieldsValue({itemName: option?.name})
  }

  const updateColumns: ColumnProps<any>[] = [
    {
      title: 'Item Category',
      dataIndex: 'itemCategory',
    },
    {
      title: 'Item Sub Category',
      dataIndex: 'itemSubCategory',
    },
    {
      title: 'Item',
      dataIndex: 'itemName',
    },
    {
      title: 'Quantity',
      dataIndex: 'quantity',
    },
    {
      title: 'Action',
      dataIndex: 'action',
      render: (text, rowData: any, index) => (
        <span>
          <Tooltip placement="top" title="edit">
            <EditOutlined
            //   className={'editSamplTypeIcon'}
              type="edit"
              onClick={() => {
                if (rowData) {
                  setEditForm(rowData, index);
                }
              }}
              style={{ color: '#1890ff', fontSize: '14px' }}
            />
          </Tooltip>
          {
            <>
              <Divider type="vertical" />
              <Tooltip placement="top" title="delete">
                <Tag>
                  <Popconfirm
                    title="Sure to delete?"
                    onConfirm={(e) => {
                      deleteData(index);
                    }}
                  >
                    <MinusCircleOutlined
                      style={{ color: '#1890ff', fontSize: '14px' }}
                    />
                  </Popconfirm>
                </Tag>
              </Tooltip>
            </>
          }
        </span>
      ),
    },
  ];

  const onAdd = (values) => {
    console.log(values);
    itemsForm.validateFields().then((res) => {
      console.log(values);
      if (indexVal !== undefined) {
        tableData[indexVal] = values;
        itemData = [...tableData];
        setIndexVal(undefined);
        setIsUpdate(false);
        itemsForm.resetFields();
      } else {
        itemData = [...tableData, values];
        itemsForm.resetFields();
      }
      setTableData(itemData);
      props.packBomDetails(itemData)
      console.log(itemData,'6666666666666666666')
    });
  };

  const onReset = () => {
    itemsForm.resetFields();
  };

  return (
    <Card
      title={<span style={{ color: 'white' }}>Product Packing Details</span>}
      style={{ textAlign: 'center', width: '100%' }}
      headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    >
      <Form
        form={itemsForm}
        layout="vertical"
        autoComplete="off"
        onFinish={onAdd}
        initialValues={props?.packBomDetails}
      >
        <Form.Item name={'id'} hidden>
          <Input />
        </Form.Item>
        <Row gutter={16}>
          <Form.Item name={'enquiryId'} hidden></Form.Item>
          <Col xs={24} sm={12} md={6}>
            <Form.Item
              name="itemCategoryId"
              label="Item Category"
              rules={[{ required: true, message: 'Item Category is required' }]}
            >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >=
                  0
                }
                placeholder="Select Item Category"
                allowClear
                onChange={itemCatOnChange}
              >
                {itemCatData?.map((e) => {
                  return (
                    <Option
                      label={'category'}
                      key={e.itemCategoryId}
                      value={e.itemCategoryId}
                      name={e.itemCategory}
                    >
                      {e.itemCategory}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name={'itemCategory'} hidden><Input/></Form.Item >
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Form.Item
              label="Item Sub Category"
              name={'itemSubCategoryId'}
              rules={[
                { required: true, message: 'Item SubCategory is required' },
              ]}
            >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >=
                  0
                }
                placeholder="Select Item SubCategory"
                allowClear
                onChange={itemSubCatOnChange}
              >
                {itemSubData?.map((e) => {
                  return (
                    <Option
                      key={e.itemSubCategoryId}
                      value={e.itemSubCategoryId}
                      name={e.itemSubCategory}
                    >
                      {e.itemSubCategory}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name={'itemSubCategory'} hidden><Input/></Form.Item >
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Form.Item
              label="Items"
              name={'itemId'}
              rules={[{ required: true, message: 'Item is required' }]}
            >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >=
                  0
                }
                placeholder="Select Item"
                allowClear
                dropdownMatchSelectWidth={false}
                onChange={itemsOnChange}
              >
                {itemsData?.map((e) => {
                  return (
                    <Option key={e.itemId} value={e.itemId} name={e.itemName}>
                      {e.itemName}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name={'itemName'} hidden><Input/></Form.Item >
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Form.Item label="Quantity" required name={'quantity'}>
              <Input placeholder="Enter Quantity" />
            </Form.Item>
          </Col>
        </Row>
        <Row justify="end">
          <Col span={2}>
            <Button type="primary" htmlType="submit">
              {isUpdate ? 'Update' : 'Add'}
            </Button>
          </Col>
          <Col span={2}>
            <Button danger onClick={onReset}>
              {'Reset'}
            </Button>
          </Col>
        </Row>
      </Form>
      {tableData.length > 0 ? (
        <Row>
          <Col span={24}>
            <Table columns={updateColumns} dataSource={tableData}></Table>
          </Col>
        </Row>
      ) : (
        <></>
      )}
    </Card>
  );
}
export default EnquiryProductPackingForm;
