import './pages-asset-management-asset-management-components-dc-form.css';
import React, { useEffect, useState } from 'react';
import { Button, Card, Form, Input, Select,Col,Row  } from 'antd';
import {Link, useHistory} from 'react-router-dom';
import { AssetCheckListDto } from '@gtpl/shared-models/asset-management';
import {AssetsLocationDto} from '../../../../../../shared-models/asset-management/src/lib/asset-location/asset-location.dto';
// import { AssetLocationService } from "../../../../../../shared-services/asset-management/src/lib/asset-location";
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { AssetCheckListService } from "../../../../../../shared-services/asset-management/src/lib/asset-check-list";

import {ItemSubCategoryService, UnitcodeService} from '@gtpl/shared-services/masters';


const {Option} = Select;

/* eslint-disable-next-line */
export interface checkListFormProps {
  checkListData: any;
  updateCheckList: (checklistData: any) => void;
  isUpdate: boolean;
  closeForm: () => void;
  setDrawerVisible: any;
  getAllChecklist?: () => void;
}
export function CheckListForm(
  props: checkListFormProps
) {
  const [form] = Form.useForm();
  const [disable, setDisable] = useState<boolean>(false)
  const [itemCategory, setItemCategory] = useState([]);
  const itemSubCategoryService = new ItemSubCategoryService();
  // const service = new AssetLocationService();
  const plantsService = new UnitcodeService();
  const [plantName,setPlantName]= useState<any>([]);
  const service=new AssetCheckListService()
const history=useHistory()

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

  const [initialValues, setInitialValues] = useState();

  useEffect(() => {
      if (props.checkListData) {
        const valuesToSet = { ...props.checkListData };
  
        if (props.checkListData) {
          form.setFieldsValue({
            checkListId: props.checkListData.checkListId,
            checkListName: props.checkListData.checkListName,
            assetCategory: props.checkListData.assetCategory,
                  });
        } else {
          form.setFieldsValue({
            checkListId: props.checkListData.checkListId,
            checkListName: props.checkListData.checkListName,
            assetCategory: props.checkListData.assetCategory,
          });
        }
  
        setInitialValues(valuesToSet);
      }
  
    }, [props.checkListData]);

//   const getAllPlants = () => {
//     plantsService.getAllPlants().then(res => {
//       if(res.status){
//         setPlantName(res.data)
//       } else {
//         AlertMessages.getErrorMessage(res.internalMessage)
//       }
//     })
//   }

const getItemCategory = () => {
  itemSubCategoryService.getAll().then(res => {
    if (res.status) {
      setItemCategory(res.data)
    } else {
      AlertMessages.getErrorMessage(res.internalMessage)
    }
  })
}
  // const onFinish = (values) => {
  //   service.create(values).then(res => {
  //     if(res.status) {
  //       AlertMessages.getSuccessMessage('Created Successfully')
  //       form.resetFields()
  //     } else {
  //       AlertMessages.getErrorMessage(res.internalMessage)
  //     }
  //   }).catch(error => {
  //     AlertMessages.getErrorMessage(error.message)
  //   })
  // }

  const createAssetChecklist=(productData:AssetCheckListDto)=>{
    setDisable(true)
    service.createAssetChecklist(productData).then(res => {
      setDisable(false)
      if (res.status) {
        AlertMessages.getSuccessMessage('Checklist Created Successfully');
        history.push("/asset-checklist-grid");
        onReset();
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setDisable(false)
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const onReset = () => {
    form.resetFields(); 
  }
  
  
  const saveData = (values: AssetCheckListDto) => {
    console.log(values.checkListName)
    console.log(form.getFieldValue('checkListName'))
    setDisable(false)
    if(props.isUpdate){
      props.updateCheckList(values);
    }else{
      setDisable(false)
      createAssetChecklist(values);
    }
  };

  const clearData = () => {
    form.resetFields()
  }

  let createdUser = "";

  if (!props.isUpdate) {
    createdUser = localStorage.getItem("createdUser");
  }


  return (
    <Card
      title={<span style={{ color: "white" }}>Check List</span>}
      style={{ textAlign: "center" }}
      headStyle={{ backgroundColor: "#69c0ff", border: 0 }}
      extra={
        props.isUpdate == true ? (
          ""
        ) : (
           <Link to="/asset-checklist-grid">
          <span style={{ color: "white" }}>
            <Button>View </Button>{" "}
          </span>
           </Link>
        )
      }
    >
      <Form form={form} onFinish={saveData} initialValues={initialValues}>
        <Row gutter={20}>
        <Col >
            <Form.Item name="checkListId" >
              <Input hidden />
            </Form.Item>
            <Form.Item name="created_user" initialValue={createdUser}>
              <Input hidden />
            </Form.Item>
            </Col>
 <Col xs={{span:24}} sm={{span:24}} md={{span:6}} lg={{span:6}} xl={{span:6}} style={{margin:'1%'}}>
            <Form.Item label='Asset Category' name='assetCategory' >
              <Select
                defaultValue={'All'}
                showSearch
                //onChange={getItems}
                optionFilterProp="children"
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                allowClear>
                <Option key={'all'} value={''}>All</Option>
                {itemCategory.map((items) => {
                  return <Option key={items.itemSubCategoryId} value={items.itemSubCategory}>{items.itemSubCategory}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>
            <Col xs={{span:24}} sm={{span:24}} md={{span:6}} lg={{span:6}} xl={{span:6}} style={{margin:'1%'}}>
            <Form.Item
              name="checkListName"
              label="CheckList Name"
              rules={[
                {
                  required: true
                }
              ]}
            >
              <Input />
            </Form.Item>
          </Col>
          
        </Row>

        <Row>
        <Col span={24} style={{ textAlign: 'right' }}>
              
              <Button type="primary" disabled={disable} htmlType="submit" >
                Submit
              </Button>
              {(props.isUpdate===false) &&
       <Button htmlType="button" style={{ margin: '0 14px' }} onClick={onReset}>
          Reset
        </Button>
        }
              </Col>
        </Row>
      </Form>
    </Card>
  );
}


export default CheckListForm;