import { ProductionProcessDashboardReq } from '@gtpl/shared-models/production-management';
import { Button, Card, Col, DatePicker, Form, Row, Select } from 'antd';
import { ProdlogService } from 'libs/shared-services/production/src/lib/prod-log.service';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import { PurchasesProductService } from '@gtpl/shared-services/finance';
import { GrnService } from '@gtpl/shared-services/procurement';

export const ProductionProcessDashboard = () => {
  const service = new ProdlogService();
  const [intakeData, setIntakeData] = useState<any>();
  const [form] = Form.useForm();
  const [soakingData, setSoakingData] = useState<any>();
  const [shiftWiseData, setShiftWisedata] = useState<any>();
  const [generalData, setGeneralData] = useState<any>();
  const [shiftAData, setShiftAData] = useState<any>();
  const [shiftBData, setShiftBData] = useState<any>();
  const [shiftCData, setShiftCData] = useState<any>();
  const [productionData, setProductionData] = useState<any>();
  const [valueAdditionQuantity, setValueAdditionQuantity] = useState<any>();
  const [valueAdditionFourQuantity, setValueAdditionFourQuantity] = useState<
    any
  >();
  const [isFiltered, setIsFiltered] = useState<boolean>(false);
  const [selectedDate, setSelectedDate] = useState(null);
  const loggedInUnitId = Number(localStorage.getItem('unit_id'));
  const [unitCodes, setUnitCodes] = useState([]);
  const purchaseService = new PurchasesProductService();
  const { Option } = Select;
  const role = JSON.parse(localStorage.getItem('role'));
  const grnService = new GrnService()

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

  const getAllUnits = () => {
    grnService.getUnitsForCeoDashboard().then((res) => {
      if (res.status) {
        setUnitCodes(res.data);
      }
    });
  };

  const getIntakeDetailsForProductionDashboard = () => {
    const req = new ProductionProcessDashboardReq(null);
    const selectedDate = form.getFieldValue('date');
    const loggedInRole = JSON.parse(localStorage.getItem('role'));
    if (selectedDate) {
      req.date = moment(selectedDate).format('YYYY-MM-DD');
    }
    if(loggedInUnitId === 5) {
    if (form.getFieldValue('unitId') !== undefined) {
      req.unitId = form.getFieldValue('unitId');
    }}else{
      req.unitId = loggedInUnitId; // Convert number to string
    }
    console.log('Request for soaking data:', req);
    service.getIntakeDetailsForProductionDashboard(req).then((res) => {
      if (res.status) {
        setIntakeData(res.data);
      } else {
        setIntakeData([]);
      }
    });
  };

  const getSoakingDataForProductionReport = () => {
    const req = new ProductionProcessDashboardReq(null);
    const selectedDate = form.getFieldValue('date');

    if (selectedDate) {
      req.date = moment(selectedDate).format('YYYY-MM-DD');
    }
    if(loggedInUnitId === 5) {
      if (form.getFieldValue('unitId') !== undefined) {
        req.unitId = form.getFieldValue('unitId');
      }}else{
        req.unitId = loggedInUnitId; // Convert number to string
      }
    console.log('Request for soaking data:', req);
    service.getSoakingDataForProductionReport(req).then((res) => {
      if (res.status) {
        setSoakingData(res.data);
      } else {
        setSoakingData([]);
      }
    });
  };

  const getShiftWiseDataForProductionReport = () => {
    const req = new ProductionProcessDashboardReq(null);
    const selectedDate = form.getFieldValue('date');
    if (selectedDate) {
      req.date = moment(selectedDate).format('YYYY-MM-DD');
    }
    if(loggedInUnitId === 5) {
      if (form.getFieldValue('unitId') !== undefined) {
        req.unitId = form.getFieldValue('unitId');
      }}else{
        req.unitId = loggedInUnitId; // Convert number to string
      }
    service.getShiftWiseDataForProductionReport(req).then((res) => {
      if (res.status) {
        setShiftWisedata(res.data);
        separateData(res.data);
      } else {
        setShiftWisedata([]);
        separateData([])
      }
    });
  };

  const getTotalProductionForDashboard = () => {
    const req = new ProductionProcessDashboardReq(null);
    const selectedDate = form.getFieldValue('date');

    if (selectedDate) {
      req.date = moment(selectedDate).format('YYYY-MM-DD');
    }
    if(loggedInUnitId === 5) {
      if (form.getFieldValue('unitId') !== undefined) {
        req.unitId = form.getFieldValue('unitId');
      }}else{
        req.unitId = loggedInUnitId; // Convert number to string
      }
    service.getTotalProductionForDashboard(req).then((res) => {
      if (res.status && res.data) {
        setProductionData(res.data); // Set the entire data object, not just the array
      } else {
        setProductionData({ data: [], totalSlabs: 0, totalKgs: 0 }); // Fallback structure
      }
    });
  };

  const getValueAdditionQuantitiesForProduction = () => {
    const req = new ProductionProcessDashboardReq(null);
    const selectedDate = form.getFieldValue('date');

    if (selectedDate) {
      req.date = moment(selectedDate).format('YYYY-MM-DD');
    }
    if(loggedInUnitId === 5) {
      if (form.getFieldValue('unitId') !== undefined) {
        req.unitId = form.getFieldValue('unitId');
      }}else{
        req.unitId = loggedInUnitId; // Convert number to string
      }
    service.getValueAdditionQuantitiesForProduction(req).then((res) => {
      if (res.status) {
        setValueAdditionQuantity(res.data);
      } else {
        setValueAdditionQuantity([]);
      }
    });
  };

  const getValueAdditionFourForProduction = () => {
    const req = new ProductionProcessDashboardReq(null);
    const selectedDate = form.getFieldValue('date');

    if (selectedDate) {
      req.date = moment(selectedDate).format('YYYY-MM-DD');
    }
    if(loggedInUnitId === 5) {
      if (form.getFieldValue('unitId') !== undefined) {
        req.unitId = form.getFieldValue('unitId');
      }}else{
        req.unitId = loggedInUnitId; // Convert number to string
      }
    service.getValueAdditionFourForProduction(req).then((res) => {
      if (res.status) {
        setValueAdditionFourQuantity(res.data);
      } else {
        setValueAdditionFourQuantity([]);
      }
    });
  };

  const getCalculatedValue = (code: string) => {
    const item = valueAdditionQuantity?.find(
      (d: any) => d.valueFiveCode === code
    );
    const value = item ? parseFloat(item.totalCalculatedFiveValue) : 0;
    return value.toFixed(2);
  };

  // const getCalculatedFourValue = (code: string) => {
  //   const item = valueAdditionFourQuantity?.find((d: any) => d.valueFourCode === code);
  //   const value = item ? parseFloat(item.totalCalculatedFourValue) : 0;
  //   return value.toFixed(2);
  // };

  const separateData = (data) => {
    const acc = {
      generalData: [],
      shiftAData: [],
      shiftBData: [],
      shiftCData: [],
    };

    data.forEach((item) => {
      if (item.shift === 'General') {
        acc.generalData.push(item);
      } else if (item.shift === 'Shift A') {
        acc.shiftAData.push(item);
      } else if (item.shift === 'Shift B') {
        acc.shiftBData.push(item);
      } else {
        acc.shiftCData.push(item);
      }
    });

    setGeneralData(acc.generalData);
    setShiftAData(acc.shiftAData);
    setShiftBData(acc.shiftBData);
    setShiftCData(acc.shiftCData);
  };

  const onSubmit = () => {
    getIntakeDetailsForProductionDashboard();
    getSoakingDataForProductionReport();
    getShiftWiseDataForProductionReport();
    getTotalProductionForDashboard();
    getValueAdditionQuantitiesForProduction();
    getValueAdditionFourForProduction();
    setIsFiltered(true);
  };

  const onReset = () => {
    setIntakeData(null);
    form.resetFields();
    setIsFiltered(false);
  };

  const date = form.getFieldValue('date');
  const formattedDate = date ? date.format('DD-MM-YYYY') : null;

  const calculateTotalQuantity = () => {
    const total = (intakeData || []).reduce((total, rec) => {
      const reweighmentQuantity = parseFloat(rec.reweighmentQuantity) || 0;
      const quantity = parseFloat(rec.quantity) || 0;
      return total + (reweighmentQuantity || quantity);
    }, 0);
    return parseFloat(total.toFixed(3)).toString();
  };

  const calculatePercentageChange = (
    inputQuantity: number,
    actualOutputQuantity: number
  ): string => {
    if (inputQuantity === 0 || actualOutputQuantity === 0) {
      return '-100%';
    }
    const percentage = (actualOutputQuantity / inputQuantity) * 100 - 100;
    return `${percentage.toFixed(2)}%`;
  };

  const calculateTotals = (data) => {
    let totals = {
      grnHonQuantity: 0,
      quantity: 0,
      yieldPer: 0, // This will store the sum of yield percentages as numbers
      actualOutputQuantity: 0,
      difference: 0,
      sampleYield: 0,
    };
    let count = 0;
    data?.forEach((rec) => {
      const grnHonQuantity =
        rec.grnHonQuantity !== null ? parseFloat(rec.grnHonQuantity) : 0;
      const quantity = rec.quantity !== null ? parseFloat(rec.quantity) : 0;
      const actualOutputQuantity =
        rec.actualOutputQuantity !== null
          ? parseFloat(rec.actualOutputQuantity)
          : 0;

      // Calculate yield percentage
      const yieldPer = rec.grnHonQuantity
        ? (rec.quantity / rec.grnHonQuantity) * 100
        : 0;
      const difference =
        quantity && actualOutputQuantity ? quantity - actualOutputQuantity : 0;
      const sampleYield =
        rec.sampleYield !== null ? parseFloat(rec.sampleYield) : 0;
      // Add to totals
      totals.grnHonQuantity += grnHonQuantity;
      totals.quantity += quantity;
      totals.yieldPer += yieldPer;
      totals.actualOutputQuantity += actualOutputQuantity;
      totals.difference += difference;
      // totals.sampleYield+=sampleYield
      if (sampleYield !== null) {
        totals.sampleYield += sampleYield;
        count++;
      }
    });
    if (count > 0) {
      totals.sampleYield = totals.sampleYield / count;
    }

    return totals;
  };

  const totalsData = calculateTotals(shiftWiseData);
  const validSampleYields = shiftWiseData
    ?.map((rec) => (rec.sampleYield ? parseFloat(rec.sampleYield) : null))
    ?.filter((val) => val !== null);
  console.log('valid sample yield:', validSampleYields);
  const averageSampleYield =
    validSampleYields?.length > 0
      ? (
          validSampleYields?.reduce((sum, val) => sum + val, 0) /
          validSampleYields?.length
        ).toFixed(2)
      : '-';

  console.log('Average Sample Yield:', averageSampleYield);

  return (
    <div>
      <Card
        size="small"
        title={
          <span style={{ color: 'white', textAlign: 'center' }}>
            Production Dashboard
          </span>
        }
        style={{ textAlign: 'center' }}
        headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
        extra={
          isFiltered && (
            <ReactHTMLTableToExcel
              id="excel-button"
              className="download-table-xls-button"
              table="report-table"
              filename="production-dashboard"
              sheet="production-dashboard"
              buttonText="Get Excel"
            />
          )
        }
      >
        <Form
          form={form}
          onFinish={onSubmit}
          layout="horizontal"
          style={{ padding: '0px', marginRight: 100 }}
        >
          <Row gutter={24}>
            <Col
              xs={{ span: 24 }}
              sm={{ span: 24 }}
              md={{ span: 4 }}
              lg={{ span: 6 }}
              xl={{ span: 6 }}
            >
              <Form.Item name="date" label="Date" rules={[{required:true,message:"Please Select Date"}]}>
                <DatePicker />
              </Form.Item>
            </Col>
            <Col
              xs={{ span: 24 }}
              sm={{ span: 24 }}
              md={{ span: 10 }}
              lg={{ span: 10 }}
              xl={{ span: 10 }}
            >
              <Form.Item name="unitId" label="Unit">
                <Select
                  placeholder="Select Unit"
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  allowClear
                  disabled={
                    Number(localStorage.getItem('unit_id')) != 5 ? true : false
                  }
                  defaultValue={
                    loggedInUnitId == 5
                      ? ''
                      : Number(localStorage.getItem('unit_id'))
                  }
                >
                  {unitCodes.map((dropData) => {
                    return (
                      <Option value={dropData.unitCodeId}>
                        {dropData.plantCode}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col
              xs={{ span: 18 }}
              sm={{ span: 18 }}
              md={{ span: 4 }}
              lg={{ span: 4 }}
              xl={{ span: 2 }}
            >
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  Search
                </Button>
              </Form.Item>
            </Col>
            <Col
              xs={{ span: 18 }}
              sm={{ span: 18 }}
              md={{ span: 4 }}
              lg={{ span: 4 }}
              xl={{ span: 2 }}
            >
              <Form.Item>
                <Button type="primary" onClick={onReset}>
                  Reset
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        {/* {isFiltered && (
        <ReactHTMLTableToExcel
        id='excel-button'
        className='download-table-xls-button'
        table='report-table'
        filename='productiondashboard'
        sheet="Sheet1"
        buttonText='Get Excel'

              />
            ) } */}
        {isFiltered && (
          <table
            id="report-table"
            style={{
              borderCollapse: 'collapse',
              borderBlockColor: 'black',
              width: '100%',
            }}
          >
            <tr>
              <th
                style={{
                  textAlign: 'center',
                  fontSize: '18px',
                  border: '1px solid black',
                  borderRight: 'none',
                }}
              >
                DAILY PRODUCTION STATEMENT
              </th>
              <th
                style={{
                  textAlign: 'center',
                  fontSize: '18px',
                  border: '1px solid black',
                  borderLeft: 'none',
                }}
              >
                DATE:{formattedDate}
              </th>
            </tr>
            <br />
            {isFiltered && (
              <table
                id="report-table"
                style={{
                  borderCollapse: 'collapse',
                  borderBlockColor: 'black',
                  width: '60%',
                }}
              >
                <thead>
                  <tr style={{ backgroundColor: 'lightblue' }}>
                    <th
                      colSpan={4}
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      INTAKE DETAILS
                    </th>
                  </tr>
                  <tr>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      S.CODE
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      FARMER NAME
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      HON COUNT
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      HON QNT
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {intakeData?.map((rec, index) => (
                    <tr key={index}>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        {rec.lotNumber ? rec.lotNumber : '-'}
                      </td>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        {rec.farmerName ? rec.farmerName : '-'}
                      </td>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        {rec.reweighmentCount
                          ? parseFloat(rec.reweighmentCount)
                          : parseFloat(rec.count)}
                      </td>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        {rec.reweighmentQuantity
                          ? parseFloat(rec.reweighmentQuantity)
                          : parseFloat(rec.quantity)}
                      </td>
                    </tr>
                  ))}
                </tbody>
                <tfoot>
                  <tr>
                    <td
                      colSpan={3}
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                        color: 'red',
                      }}
                    >
                      TOTAL
                    </td>
                    <td
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                        color: 'red',
                      }}
                    >
                      {' '}
                      {calculateTotalQuantity()}
                    </td>
                  </tr>
                </tfoot>
              </table>
            )}
            <br />
            <table
              id="report-table"
              style={{ borderCollapse: 'collapse', width: '100%' }}
            >
              <tr>
                <th style={{ textAlign: 'right' }}>{formattedDate}</th>
              </tr>
            </table>
            {isFiltered && (
              <table
                id="report-table"
                style={{ borderCollapse: 'collapse', width: '100%' }}
              >
                <thead>
                  <tr style={{ backgroundColor: 'lightblue' }}>
                    <th
                      colSpan={8}
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      HON TO HLSO YIELD
                    </th>
                  </tr>
                  <tr>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      S.CODE
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      HON COUNT
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      HON QNT
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      GRADEING HLSO QNT
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      YIELD %
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      SAMPLE YIELD %
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      DE HEADING HLSO QTY
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      DIFF +/- Loss
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {generalData?.length > 0 && (
                    <>
                      <tr>
                        <th
                          colSpan={8}
                          style={{
                            textAlign: 'center',
                            fontSize: '15px',
                            border: '1px solid black',
                          }}
                        >
                          General
                        </th>
                      </tr>
                      {generalData.map((rec, idx) => {
                        const yieldPer = rec.grnHonQuantity
                          ? ((rec.quantity / rec.grnHonQuantity) * 100).toFixed(
                              2
                            )
                          : '-';
                        const difference =
                          rec.quantity && rec.actualOutputQuantity
                            ? (rec.quantity - rec.actualOutputQuantity).toFixed(
                                2
                              )
                            : '-';
                        let percentageValue = '-';
                        if (yieldPer !== '-' && !isNaN(parseFloat(yieldPer))) {
                          const yieldPerNum = parseFloat(yieldPer);
                          if (yieldPerNum <= 25) percentageValue = '72%';
                          else if (yieldPerNum <= 30) percentageValue = '71%';
                          else if (yieldPerNum <= 50) percentageValue = '70%';
                          else if (yieldPerNum <= 60) percentageValue = '69%';
                          else if (yieldPerNum <= 80) percentageValue = '68%';
                          else if (yieldPerNum <= 100) percentageValue = '67%';
                          else if (yieldPerNum <= 120) percentageValue = '66%';
                          else if (yieldPerNum <= 150) percentageValue = '65%';
                          else if (yieldPerNum >= 151) percentageValue = '64%';
                        }
                        const sampleYield = rec.sampleYield
                          ? parseFloat(rec.sampleYield)
                          : '-';
                        return (
                          <tr key={idx}>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {rec.lotNumber ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.grnHonCount) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.grnHonQuantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.quantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {yieldPer !== '-' ? `${yieldPer}%` : '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {sampleYield !== '-' ? `${sampleYield}%` : '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.actualOutputQuantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(difference)}
                            </td>
                          </tr>
                        );
                      })}
                    </>
                  )}

                  {shiftAData?.length > 0 && (
                    <>
                      <tr>
                        <th
                          colSpan={8}
                          style={{
                            textAlign: 'center',
                            fontSize: '15px',
                            border: '1px solid black',
                          }}
                        >
                          Shift A
                        </th>
                      </tr>
                      {shiftAData.map((rec, idx) => {
                        const yieldPer = rec.grnHonQuantity
                          ? ((rec.quantity / rec.grnHonQuantity) * 100).toFixed(
                              2
                            )
                          : '-';
                        const difference =
                          rec.quantity && rec.actualOutputQuantity
                            ? (rec.quantity - rec.actualOutputQuantity).toFixed(
                                2
                              )
                            : '-';
                        let percentageValue = '-';
                        if (yieldPer !== '-' && !isNaN(parseFloat(yieldPer))) {
                          const yieldPerNum = parseFloat(yieldPer);
                          if (yieldPerNum <= 25) percentageValue = '72%';
                          else if (yieldPerNum <= 30) percentageValue = '71%';
                          else if (yieldPerNum <= 50) percentageValue = '70%';
                          else if (yieldPerNum <= 60) percentageValue = '69%';
                          else if (yieldPerNum <= 80) percentageValue = '68%';
                          else if (yieldPerNum <= 100) percentageValue = '67%';
                          else if (yieldPerNum <= 120) percentageValue = '66%';
                          else if (yieldPerNum <= 150) percentageValue = '65%';
                          else if (yieldPerNum >= 151) percentageValue = '64%';
                        }
                        const sampleYield = rec.sampleYield
                          ? parseFloat(rec.sampleYield)
                          : '-';

                        return (
                          <tr key={idx}>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {rec.lotNumber ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.grnHonCount) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.grnHonQuantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.quantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {yieldPer !== '-' ? `${yieldPer}%` : '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {sampleYield !== '-' ? `${sampleYield}%` : '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.actualOutputQuantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(difference)}
                            </td>
                          </tr>
                        );
                      })}
                    </>
                  )}

                  {shiftBData?.length > 0 && (
                    <>
                      <tr>
                        <th
                          colSpan={8}
                          style={{
                            textAlign: 'center',
                            fontSize: '15px',
                            border: '1px solid black',
                          }}
                        >
                          Shift B
                        </th>
                      </tr>
                      {shiftBData.map((rec, idx) => {
                        const yieldPer = rec.grnHonQuantity
                          ? ((rec.quantity / rec.grnHonQuantity) * 100).toFixed(
                              2
                            )
                          : '-';
                        const difference =
                          rec.quantity && rec.actualOutputQuantity
                            ? (rec.quantity - rec.actualOutputQuantity).toFixed(
                                2
                              )
                            : '-';
                        let percentageValue = '-';
                        if (yieldPer !== '-' && !isNaN(parseFloat(yieldPer))) {
                          const yieldPerNum = parseFloat(yieldPer);
                          if (yieldPerNum <= 25) percentageValue = '72%';
                          else if (yieldPerNum <= 30) percentageValue = '71%';
                          else if (yieldPerNum <= 50) percentageValue = '70%';
                          else if (yieldPerNum <= 60) percentageValue = '69%';
                          else if (yieldPerNum <= 80) percentageValue = '68%';
                          else if (yieldPerNum <= 100) percentageValue = '67%';
                          else if (yieldPerNum <= 120) percentageValue = '66%';
                          else if (yieldPerNum <= 150) percentageValue = '65%';
                          else if (yieldPerNum >= 151) percentageValue = '64%';
                        }
                        const sampleYield = rec.sampleYield
                          ? parseFloat(rec.sampleYield)
                          : '-';
                        return (
                          <tr key={idx}>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {rec.lotNumber ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.grnHonCount) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.grnHonQuantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.quantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {yieldPer !== '-' ? `${yieldPer}%` : '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {sampleYield !== '-' ? `${sampleYield}%` : '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.actualOutputQuantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(difference)}
                            </td>
                          </tr>
                        );
                      })}
                    </>
                  )}
                  {shiftCData?.length > 0 && (
                    <>
                      <tr>
                        <th
                          colSpan={8}
                          style={{
                            textAlign: 'center',
                            fontSize: '15px',
                            border: '1px solid black',
                          }}
                        >
                          Shift C
                        </th>
                      </tr>
                      {shiftCData.map((rec, idx) => {
                        const yieldPer = rec.grnHonQuantity
                          ? ((rec.quantity / rec.grnHonQuantity) * 100).toFixed(
                              2
                            )
                          : '-';
                        const difference =
                          rec.quantity && rec.actualOutputQuantity
                            ? (rec.quantity - rec.actualOutputQuantity).toFixed(
                                2
                              )
                            : '-';
                        let percentageValue = '-';
                        if (yieldPer !== '-' && !isNaN(parseFloat(yieldPer))) {
                          const yieldPerNum = parseFloat(yieldPer);
                          if (yieldPerNum <= 25) percentageValue = '72%';
                          else if (yieldPerNum <= 30) percentageValue = '71%';
                          else if (yieldPerNum <= 50) percentageValue = '70%';
                          else if (yieldPerNum <= 60) percentageValue = '69%';
                          else if (yieldPerNum <= 80) percentageValue = '68%';
                          else if (yieldPerNum <= 100) percentageValue = '67%';
                          else if (yieldPerNum <= 120) percentageValue = '66%';
                          else if (yieldPerNum <= 150) percentageValue = '65%';
                          else if (yieldPerNum >= 151) percentageValue = '64%';
                        }
                        const sampleYield = rec.sampleYield
                          ? parseFloat(rec.sampleYield)
                          : '-';
                        const validSampleYields = shiftCData
                          .map((rec) =>
                            rec.sampleYield ? parseFloat(rec.sampleYield) : null
                          )
                          .filter((val) => val !== null);
                        const averageSampleYield =
                          validSampleYields.length > 0
                            ? (
                                validSampleYields.reduce(
                                  (sum, val) => sum + val,
                                  0
                                ) / validSampleYields.length
                              ).toFixed(2)
                            : '-';

                        return (
                          <tr key={idx}>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {rec.lotNumber ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.grnHonCount) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.grnHonQuantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.quantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {yieldPer !== '-' ? `${yieldPer}%` : '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {sampleYield !== '-' ? `${sampleYield}%` : '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(rec.actualOutputQuantity) ?? '-'}
                            </td>
                            <td
                              style={{
                                textAlign: 'center',
                                border: '1px solid #000',
                              }}
                            >
                              {parseFloat(difference)}
                            </td>
                          </tr>
                        );
                      })}
                    </>
                  )}
                </tbody>
                <tfoot>
                  <tr>
                    <td
                      colSpan={2}
                      style={{
                        textAlign: 'center',
                        border: '1px solid #000',
                        color: 'red',
                      }}
                    >
                      TOTAL
                    </td>
                    <td
                      style={{
                        textAlign: 'center',
                        border: '1px solid #000',
                        color: 'red',
                      }}
                    >
                      {totalsData.grnHonQuantity.toFixed(2)}
                    </td>
                    <td
                      style={{
                        textAlign: 'center',
                        border: '1px solid #000',
                        color: 'red',
                      }}
                    >
                      {totalsData.quantity.toFixed(2)}
                    </td>
                    <td
                      style={{
                        textAlign: 'center',
                        border: '1px solid #000',
                        color: 'red',
                      }}
                    >
                      {(
                        (totalsData.quantity / totalsData.grnHonQuantity) *
                        100
                      ).toFixed(2)}
                      %
                    </td>{' '}
                    {/* Averaged Yield Percentage */}
                    <td
                      style={{
                        textAlign: 'center',
                        border: '1px solid #000',
                        color: 'red',
                      }}
                    >
                      {totalsData.sampleYield.toFixed(2)}%
                    </td>
                    <td
                      style={{
                        textAlign: 'center',
                        border: '1px solid #000',
                        color: 'red',
                      }}
                    >
                      {totalsData.actualOutputQuantity.toFixed(2)}
                    </td>
                    <td
                      style={{
                        textAlign: 'center',
                        border: '1px solid #000',
                        color: 'red',
                      }}
                    >
                      {totalsData.difference.toFixed(2)}
                    </td>
                  </tr>
                </tfoot>
              </table>
            )}

            <br />
            {isFiltered && (
              <table
                id="report-table"
                style={{
                  borderCollapse: 'collapse',
                  borderBlockColor: 'black',
                  width: '60%',
                }}
              >
                <thead>
                  <tr style={{ backgroundColor: 'lightblue' }}>
                    <th
                      colSpan={4}
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      SOAKING REPORT
                    </th>
                  </tr>
                  <tr>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      VARIETY
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      SOAK IN KGS
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      PRODUCTION IN KGS
                    </th>
                    <th
                      style={{
                        textAlign: 'center',
                        fontSize: '15px',
                        border: '1px solid black',
                      }}
                    >
                      YIELD %
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {soakingData?.map((rec, index) => (
                    <tr key={index}>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        {rec.product}
                      </td>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        {parseFloat(rec.inputQuantity)}
                      </td>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        {parseFloat(rec.actualOutputQuantity)}
                      </td>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        {calculatePercentageChange(
                          parseFloat(rec.inputQuantity),
                          parseFloat(rec.actualOutputQuantity)
                        )}
                      </td>{' '}
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
            <br />
            {isFiltered && (
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <table
                  id="report-table"
                  style={{
                    borderCollapse: 'collapse',
                    borderBlockColor: 'black',
                    width: '60%',
                  }}
                >
                  <thead>
                    <tr style={{ backgroundColor: 'lightblue' }}>
                      <th
                        colSpan={5}
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        TOTAL PRODUCTION
                      </th>
                    </tr>
                    <tr>
                      <th
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        VARIETY
                      </th>
                      <th
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        Slabs
                      </th>
                      <th
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        Net Weight In Kgs
                      </th>
                      <th
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        Gross weight Per Pouch
                      </th>
                      <th
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                        }}
                      >
                        Gross weight In Kg
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {Array.isArray(productionData?.data) &&
                    productionData.data.length > 0 ? (
                      productionData.data.map((rec, index) => (
                        <tr key={index}>
                          <td
                            style={{
                              textAlign: 'center',
                              fontSize: '15px',
                              border: '1px solid black',
                            }}
                          >
                            {rec.convertedShortCode}
                          </td>
                          <td
                            style={{
                              textAlign: 'center',
                              fontSize: '15px',
                              border: '1px solid black',
                            }}
                          >
                            {parseFloat(rec.slabs)}
                          </td>
                          <td
                            style={{
                              textAlign: 'center',
                              fontSize: '15px',
                              border: '1px solid black',
                            }}
                          >
                            {parseFloat(rec.noOfKgs)}
                          </td>
                          <td
                            style={{
                              textAlign: 'center',
                              fontSize: '15px',
                              border: '1px solid black',
                            }}
                          >
                            {parseFloat(rec.grossWeight)}
                          </td>
                          <td
                            style={{
                              textAlign: 'center',
                              fontSize: '15px',
                              border: '1px solid black',
                            }}
                          >
                            {parseFloat(rec.grossWeightPerKg)}
                          </td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td
                          colSpan={5}
                          style={{
                            textAlign: 'center',
                            fontSize: '15px',
                            border: '1px solid black',
                          }}
                        >
                          No production data available
                        </td>
                      </tr>
                    )}
                  </tbody>
                  <tfoot>
                    <tr>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                          color: 'red',
                        }}
                      >
                        TOTAL
                      </td>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                          color: 'red',
                        }}
                      >
                        {productionData?.totalSlabs || 0}
                      </td>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                          color: 'red',
                        }}
                      >
                        {productionData?.totalKgs || 0}
                      </td>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                          color: 'red',
                        }}
                      >
                        &nbsp;
                      </td>
                      <td
                        style={{
                          textAlign: 'center',
                          fontSize: '15px',
                          border: '1px solid black',
                          color: 'red',
                        }}
                      >
                        {productionData?.totalGrossWeight || 0}
                      </td>
                    </tr>
                  </tfoot>
                </table>

                <div style={{ marginRight: '60px' }}>
                  <div>
                    <b>DC Kgs:</b>{' '}
                    {valueAdditionQuantity?.totalDC
                      ? valueAdditionQuantity?.totalDC
                      : 0}
                  </div>
                  <div>
                    <b>GII Kgs:</b>{' '}
                    {valueAdditionQuantity?.totalGII
                      ? valueAdditionQuantity?.totalGII
                      : 0}
                  </div>
                  <div>
                    <b>BKN Kgs:</b>{' '}
                    {valueAdditionQuantity?.totalBKN
                      ? valueAdditionQuantity?.totalBKN
                      : 0}
                  </div>
                  <br />
                  <div>
                    <b>IQF:</b>{' '}
                    {valueAdditionFourQuantity?.totalIqf
                      ? valueAdditionFourQuantity?.totalIqf
                      : 0}
                  </div>
                  <div>
                    <b>BLK:</b>{' '}
                    {valueAdditionFourQuantity?.totalBlk
                      ? valueAdditionFourQuantity?.totalBlk
                      : 0}
                  </div>
                </div>
              </div>
            )}

            <br />
            {isFiltered && (
              <table
                id="report-table"
                style={{
                  borderCollapse: 'collapse',
                  borderBlockColor: 'black',
                  width: '80%',
                }}
              >
                <tr>
                  <th
                    style={{
                      textAlign: 'center',
                      fontSize: '15px',
                      border: '1px solid black',
                      width: '40%',
                    }}
                  >
                    Total Raw Materials Receiving In Kgs
                  </th>
                  <td
                    style={{
                      textAlign: 'center',
                      fontSize: '15px',
                      border: '1px solid black',
                      width: '20%',
                    }}
                  >
                    {' '}
                    {calculateTotalQuantity()}
                  </td>
                  <td
                    style={{
                      textAlign: 'center',
                      fontSize: '15px',
                      border: '1px solid black',
                      width: '20%',
                    }}
                  >
                    KGS
                  </td>
                </tr>
              </table>
            )}
            <br />
            {isFiltered && (
              <table
                id="report-table"
                style={{
                  borderCollapse: 'collapse',
                  borderBlockColor: 'black',
                  width: '80%',
                }}
              >
                <tr>
                  <th
                    style={{
                      textAlign: 'center',
                      fontSize: '15px',
                      border: '1px solid black',
                      width: '40%',
                    }}
                  >
                    Total Production In Kgs
                  </th>
                  <td
                    style={{
                      textAlign: 'center',
                      fontSize: '15px',
                      border: '1px solid black',
                      width: '20%',
                    }}
                  >
                    {productionData?.totalKgs || 0}
                  </td>
                  <td
                    style={{
                      textAlign: 'center',
                      fontSize: '15px',
                      border: '1px solid black',
                      width: '20%',
                    }}
                  >
                    KGS
                  </td>
                </tr>
              </table>
            )}
          </table>
        )}
      </Card>
    </div>
  );
};

export default ProductionProcessDashboard;
