import {
  ProdlogService,
  ProductionInventoryService,
} from '@gtpl/shared-services/production';
import { Button, Card, Col, DatePicker, Form, Select, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { TransportChargesReq } from '@gtpl/shared-models/production-management';
import moment from 'moment';

const WagesPayableVillageWiseReport = () => {
  const service = new ProdlogService();
  const [tableData, setTableData] = useState<any>([]);
  const serviceFilter = new ProductionInventoryService();
  const [contractors, setContractors] = useState<any>([]);
  const [villages, setVillages] = useState<any>([]);
  const { Option } = Select;
  const [form] = Form.useForm();
  const [dateRange, setDateRange] = useState<
    [moment.Moment, moment.Moment] | null
  >(null);

  useEffect(() => {
    const today = new Date();
    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    setDateRange([moment(firstDayOfMonth), moment(today)]);
    // wagesPayableVillageWise(undefined, undefined, firstDayOfMonth, today);
    getAllContractors();
    getAllVillages();
  }, []);

  const getAllContractors = () => {
    serviceFilter
      .getAllContractors()
      .then((res) => {
        if (res.status) {
          setContractors(res.data);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
          setContractors([]);
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setContractors([]);
      });
  };

  const getAllVillages = () => {
    serviceFilter
      .GetAllVillages()
      .then((res) => {
        if (res.status) {
          setVillages(res.data);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
          setVillages([]);
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setVillages([]);
      });
  };

  const wagesPayableVillageWise = (value) => {
    const [ fromDate, toDate ] = value?.dateRange?.map(date => date.format('YYYY-MM-DD'));
    const req = new TransportChargesReq(form.getFieldValue('contractorId'),form.getFieldValue('villageId'),fromDate,toDate);
    service
      .wagesPayableVillageWise(req)
      .then((res) => {
        if (res.status) {
          setTableData(res.data);
        } else {
          setTableData([]);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const columns: any = [
    {
      title: 'Contractor',
      dataIndex: 'contractorName',
      key: 'contractorName',
    },
    { title: 'SL No', dataIndex: 'slNo', key: 'slNo', align: 'right' },
    { title: 'Village', dataIndex: 'villageName', key: 'villageName',
      render: (text: string) => (
        text?.toLowerCase().includes('total') ? 
        <strong style={{ fontWeight: 600 }}>{text}</strong> : 
        text
      )
     },
    { title: 'No of Workers', dataIndex: 'noOfWorkers', key: 'noOfWorkers', align: 'right' },
    { title: 'Man Days', dataIndex: 'manDays', key: 'manDays', align: 'right' },
    { 
      title: 'Total Wages', 
      dataIndex: 'totalWages', 
      key: 'totalWages', 
      align: 'right', 
      render: text => Number(text).toLocaleString() 
    },
  ];
  

  const exportExcel = async () => {
    const workbook = new ExcelJS.Workbook();
    const formattedFromDate = form.getFieldValue("dateRange")[0].format('DD-MMM-YYYY');
    const formattedToDate = form.getFieldValue("dateRange")[1].format('DD-MMM-YYYY');
    const worksheet = workbook.addWorksheet(`Peeling Summary Details From ${formattedFromDate}`);
  
    const headerTitles = [
      'BMR Industries Pvt. Ltd.',
      'DAMAVARAM, NELLORE.',
      `Wages Payable Village Wise From ${formattedFromDate} To ${formattedToDate}`,
    ];
  
    headerTitles.forEach((title, index) => {
      const rowNumber = index + 1;
      worksheet.mergeCells(`A${rowNumber}:F${rowNumber}`);
      const cell = worksheet.getCell(`A${rowNumber}`);
      cell.value = title;
      cell.alignment = { horizontal: 'center', vertical: 'middle' };
      cell.font = { bold: true, size: 14 };
    });
  
    const columnHeaders = ['Contractor Name', 'SL No', 'Village Name', 'No of Workers', 'Man days', 'Total Wages'];
    const headerRow = worksheet.getRow(4);
  
    columnHeaders.forEach((header, index) => {
      const cell = worksheet.getCell(4, index + 1);
      cell.value = header;
      cell.font = { bold: true, size: 12 };
      cell.alignment = { horizontal: 'center', vertical: 'middle' };
      cell.border = {
        top: { style: 'thin' }, left: { style: 'thin' },
        bottom: { style: 'thin' }, right: { style: 'thin' }
      };
    });
  
    worksheet.columns = [
      { key: 'contractorName', width: 25 },
      { key: 'slNo', width: 10, alignment: { horizontal: 'right' } },
      { key: 'villageName', width: 20 },
      { key: 'noOfWorkers', width: 15, alignment: { horizontal: 'right' } },
      { key: 'manDays', width: 15, alignment: { horizontal: 'right' } },
      { key: 'totalWages', width: 20, alignment: { horizontal: 'right' } },
    ];
  
    let currentContractor = null;
    let startRow = null;
    let rowIndex = 5;
  
    tableData.forEach((row, index) => {
      const newRow = worksheet.addRow({
        contractorName: row.contractorName,
        slNo: row.slNo,
        villageName: row.villageName,
        noOfWorkers: row.noOfWorkers,
        manDays: row.manDays,
        totalWages: Number(row.totalWages).toLocaleString(),
      });
  
      newRow.eachCell((cell, colNumber) => {
        cell.border = {
          top: { style: 'thin' }, left: { style: 'thin' },
          bottom: { style: 'thin' }, right: { style: 'thin' }
        };
  
        if ([2, 4, 5, 6].includes(colNumber)) {
          cell.alignment = { horizontal: 'right' };
        }
  
        if (colNumber === 3 && row.villageName?.toLowerCase().includes('total')) {
          if (row.villageName.toLowerCase().includes('grand total')) {
            newRow.eachCell(cell => {
              cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFC000' } };
              cell.font = { bold: true };
            });
          } else {
            newRow.eachCell(cell => {
              cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'D9EAD3' } };
              cell.font = { bold: true };
            });
          }
        }
      });
  
      if (row.contractorName !== currentContractor) {
        if (startRow !== null && rowIndex - startRow > 1) {
          worksheet.mergeCells(`A${startRow}:A${rowIndex - 1}`);
          worksheet.getCell(`A${startRow}`).alignment = { horizontal: 'center', vertical: 'middle' };
        }
        currentContractor = row.contractorName;
        startRow = rowIndex;
      }
  
      rowIndex++;
    });
  
    if (startRow !== null && rowIndex - startRow > 1) {
      worksheet.mergeCells(`A${startRow}:A${rowIndex - 1}`);
      worksheet.getCell(`A${startRow}`).alignment = { horizontal: 'center', vertical: 'middle' };
    }
  
    const buffer = await workbook.xlsx.writeBuffer();
    const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    saveAs(blob, 'Contractor Wise & Village Wise - Wages Payable.xlsx');
  };
  
  

  const resetFilters = () => {
    form.resetFields();
    setTableData([]);
  };

  return (
    <>
      <Card
        size="small"
        title={
          <span style={{ color: 'white' }}>
            Wages Payable Village Wise Report
          </span>
        }
        style={{ textAlign: 'center' }}
        headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
        extra={
          <Button
            className="panel_button"
            onClick={() => exportExcel()}
            disabled={tableData.length === 0}
          >
            Get Excel
          </Button>
        }
      >
        <Form form={form} layout="inline" onFinish={wagesPayableVillageWise}>
          <Col
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 6 }}
            lg={{ span: 6 }}
            xl={{ span: 6 }}
          >
            <Form.Item
              name="dateRange"
              label="Date"
              rules={[
                {
                  required: true,
                  message: 'select date range',
                },
              ]}
            >
              <DatePicker.RangePicker
                value={dateRange}
                onChange={setDateRange}
              />
            </Form.Item>
          </Col>
          <Col
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 5 }}
            lg={{ span: 6 }}
            xl={{ span: 5 }}
          >
            <Form.Item
              name="contractorId"
              label="Contractor"
              style={{ width: 200 }}
            >
              <Select
                allowClear
                showSearch
                placeholder="Select Contractor"
                style={{ width: '100%' }}
                optionFilterProp="children"
              >
                {contractors.map((data) => (
                  <Option
                    key={data.contractorId}
                    value={data.contractorId}
                    name={data.contractor}
                  >
                    {' '}
                    {data.contractor}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: 5 }}
            lg={{ span: 6 }}
            xl={{ span: 5 }}
          >
            <Form.Item name="villageId" label="Village" style={{ width: 200 }}>
              <Select
                allowClear
                showSearch
                placeholder="Select Village"
                style={{ width: '100%' }}
                optionFilterProp="children"
              >
                {villages.map((data) => (
                  <Option
                    key={data.villageId}
                    value={data.villageId}
                    name={data.villageName}
                  >
                    {' '}
                    {data.villageName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Form.Item>
            <Button type="primary" htmlType='submit'>
              Search
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={resetFilters}>
              Reset
            </Button>
          </Form.Item>
        </Form>
        <br />
          <Table
            columns={columns}
            dataSource={tableData}
            pagination={false}
            bordered
            style={{
              width: "100%",
              fontSize: "14px",
              backgroundColor: "white",
              borderRadius: "5px",
              borderCollapse: "collapse",
            }}
          />
      </Card>
    </>
  );
};

export default WagesPayableVillageWiseReport;
