import { GrnDtos, GrnInspectionreq, grnIdreq } from "@gtpl/shared-models/procurement-management";
import { ReasonsService } from "@gtpl/shared-services/masters";
import { GrnService } from "@gtpl/shared-services/procurement";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import { Button, Card, Col, Descriptions, Form, Input, Row, Select, Space } from "antd";
import form from "antd/lib/form";
import React, { useEffect, useState } from "react";
const { Option } = Select;
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { GrnStatusEnum } from "apps/services/procurement-service/src/app/grn/dto/grn-status.enum";
import { useHistory } from "react-router-dom";
export interface GrnInspectionProps{
  isUpdate:boolean;
  closeForm: () => void;
  fgInspecData : any
}
export function GrnInspection(props:GrnInspectionProps) {
  const service= new ReasonsService
  const services= new GrnService
  const[reasons,setReasons]=useState<any[]>([]);
  // const[reqdata,setreqData]=useState<any[]>([]);
  const [passfields] = useState([{}]);
  const [form] = Form.useForm();
  let reqData = []
  let history = useHistory();

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

  const getReasons = () => {
    console.log('res');

    service.getAllReasonsgrn().then(res => {
      if (res.status) {
        console.log(res);
        
        setReasons(res.data)
      }
    })
  }
  let sum 
  const finish = (val: any) => {
  const passData = val.pass.filter((obj) => obj.quantity !== '') || [];
  const passWithConditionData = val.passwithcondition != undefined ? val.passwithcondition.filter((obj) => obj.quantity !== '') || [] : [];
  const failData = val.fail != undefined ?  val.fail.filter((obj) => obj.quantity !== '') || [] : []

  const newData = [...passData, ...passWithConditionData, ...failData];
  console.log(newData,'newdata')
  sum = newData.reduce((acc: number, item: any) => acc + (Number(item.quantity) || 0), 0);
    if (sum > props.fgInspecData?.receivedQuantity) {
      AlertMessages.getErrorMessage('Sum of quantities should not be greater than receivedQty.');
    } else {
      // Update the state with the new data
      reqData = newData;
      save();
    }
  }
  

const validateQuantity = (data: any[], receivedQty: number) => {
const sum = data.reduce((acc, item) => acc + (Number(item.quantity) || 0), 0);
console.log(data.reduce((acc, item) => acc +(Number(item.quantity) || 0), 0));

return sum === receivedQty;
};
  const save = () =>{  
  const req =new GrnInspectionreq ()
  req.grndata = reqData
  req.itemid= props.fgInspecData.grnItemId
  req.grnId = props.fgInspecData.grnId
  req.inspectedQty = sum
  services.saveGrnInspection(req).then((res)=>{
    if(res.status){
    AlertMessages.getSuccessMessage(res.internalMessage)
    // history.push("/pending-grn-info-grid");
    props.closeForm()

    }else{
      AlertMessages.getErrorMessage(res.internalMessage)
    }
  })
    
  }


  const [selectedReasons, setSelectedReasons] = useState([]);
  const [selectedReasonsTwo, setSelectedReasonsTwo] = useState([]);


return (
  <>
  <Card title={<span style={{color:'white'}}>Grn Inspection</span>} style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }}>
      <Row gutter={24}>
        <Col>
          <Descriptions>
            <Descriptions.Item label="Invoice Number">{props.fgInspecData?.invoiceNumber}</Descriptions.Item>
            <Descriptions.Item label="GRN Number" >{props.fgInspecData?.grnNo} </Descriptions.Item>
            <Descriptions.Item label="Received Quantity" >{props.fgInspecData?.receivedQuantity}</Descriptions.Item>
          </Descriptions>
        </Col>
      </Row>
    <Form layout="vertical" onFinish={finish}>
      <Row gutter={24}>
        <Col  xs={{ span: 24 }}
                    sm={{ span: 24 }}
                    md={{ span: 5 }}
                    lg={{ span: 5 }}
                    xl={{ span: 8 }}>
          <Card style={{ height: '70px', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: '#efd3d7' }}>PASS</Card>
          <br/>
          <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
                <Row>
                <Col>
                <Form.List name="pass" initialValue={passfields}>
                  {(fields) => (
                    <>
                      {fields.map(({ key, name, ...restField }) => (
                        <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                          <Form.Item
                            label='Quantity'

                            {...restField}
                            name={[name, 'status']}
                            initialValue={GrnStatusEnum.PASS}
                          >
                            <Input defaultValue="pass" hidden />
                          </Form.Item>
                          <Form.Item
                            {...restField}
                            name={[name, 'quantity']}
                            rules={[{ required: true, message: 'Please enter quantity' }]}
                          >
                            <Input placeholder="quantity" width={'100%'}/>
                          </Form.Item>
                        </Space>
                      ))}
                    </>
                  )}
                </Form.List>
          </Col>
          </Row>
          </div>
        </Col>
        <Col xs={{ span: 24 }}
                    sm={{ span: 24 }}
                    md={{ span: 5 }}
                    lg={{ span: 5 }}
                    xl={{ span: 8 }}>
        <Card style={{ height: '70px', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: '#dee2ff' }}>PASS WITH CONDITION</Card>
        <br/>
        <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
          <Row>
            <Col>
              <Form.List name="passwithcondition">
              {(fields, { add, remove }) => (
              <>
              {fields.map(({ key, name, ...restField }) => (
              <Space key={key} style={{ display: 'flex', marginBottom: 8 }}>
              <Form.Item
              {...restField}
              name={[name, 'status']}
              initialValue={GrnStatusEnum.PASSWITHCONDITION}              
              >
              <Input defaultValue="passwithcondition" hidden/>
              </Form.Item>
              <Form.Item
              {...restField}
              name={[name, 'quantity']} 
              label='Quantity'
                          
              >
              <Input placeholder="quantity" />
              </Form.Item>

              <Form.Item
              name={[name, 'reasonId']} 
              label="select Reason"
              style={{ width: "100%" }}
              >
             <Select
        showSearch
        placeholder="Select Reason"
        optionFilterProp="children"
        allowClear
        onChange={(value) => selectedReasons[name] = value}
      >
        {reasons.map((res) => (
          <Option
            key={res.reasonId}
            value={res.reasonId}
            disabled={selectedReasons.includes(res.reasonId)}
          >
            {res.reasonName}
          </Option>
        ))}
      </Select>
              </Form.Item>
              <MinusCircleOutlined onClick={() =>
                 {remove(name) 
                 selectedReasons.splice(name,1)}} />
              </Space>
              ))}

              <Form.Item>
              <Button  type="dashed" onClick={() => add()} block  icon={<PlusOutlined />}>
                Add
              </Button>
              </Form.Item>
              </>
              )}
              </Form.List>
            </Col>
          </Row>
        </div>
        </Col>
        <Col xs={{ span: 24 }}
                    sm={{ span: 24 }}
                    md={{ span: 5 }}
                    lg={{ span: 5 }}
                    xl={{ span: 8 }}>
        <Card style={{ height: '70px', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: '#dee2ff' }}>FAIL</Card>
        <br/>
          <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
          <Row>
            <Col>
              <Form.List name="fail">
              {(fields, { add, remove }) => (
              <>
              {fields.map(({ key, name, ...restField }) => (
              <Space key={key} style={{ display: 'flex', marginBottom: 8 }} >
              <Form.Item
              {...restField}
              name={[name, 'status']}   
              initialValue={GrnStatusEnum.FAIL}            
              >
              <Input defaultValue="fail" hidden/>
              </Form.Item>
              <Form.Item
              {...restField}
              name={[name, 'quantity']}  
              label='Quantity'

              >
              <Input placeholder="quantity" />
              </Form.Item>

              <Form.Item
              name={[name, 'reasonId']} 
              label="select Reason"
              style={{ width: "100%" }}
              >
             
                <Select
        showSearch
        placeholder="Select Reason"
        optionFilterProp="children"
        allowClear
        // onChange={(value) => setSelectedReasonsTwo((prev) => [...prev, value])}
        onChange={(value) => selectedReasonsTwo[name] = value}
      >
        {reasons.map((res) => (
          <Option
            key={res.reasonId}
            value={res.reasonId}
            disabled={selectedReasonsTwo.includes(res.reasonId)}
          >
            {res.reasonName}
          </Option>
        ))}
      </Select>
              </Form.Item>
              <MinusCircleOutlined onClick={() => 
                {remove(name)
                  selectedReasonsTwo.splice(name,1)
                }} />
              </Space>
              ))}

              <Form.Item>
              <Button  type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
              Add 
              </Button>
              </Form.Item>
              </>
              )}
              </Form.List>
          </Col>
          </Row>
          </div>
        </Col>             
      </Row>
      <Row>
        <Col span={24} style={{ textAlign: 'right' }}>
          <Button type="primary" htmlType="submit" >
              Submit
          </Button>
        </Col>
      </Row>
    </Form>
  </Card>
  </>
)
}

export default GrnInspection;
