import { TransportChargesReq } from '@gtpl/shared-models/production-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card, Col, DatePicker, Form, Select } from 'antd';
import { ProductionInventoryService } from 'libs/shared-services/production/src/lib/production-inventory.service';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import * as XLSX from 'xlsx';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import form from 'antd/lib/form';


const WorkerWiseWagesReport = () => {
  const service = new ProductionInventoryService();
  const [transportData, setTransportData] = useState<any>([]);
  const [contractors, setContractors] = useState<any>([]);
  const [villages, setVillages] = useState<any>([]);
  const [page, setPage] = useState(1);
  const [columns, setColumns] = useState<any[]>([]);
  const [selectedContractorName, setSelectedContractorName] = useState<string>('');
  const [selectedVillageName, setSelectedVillageName] = useState<string>('');

  const [dateRange, setDateRange] = useState<[moment.Moment, moment.Moment] | null>(null);
  const [showTable, setShowTable] = useState(false); 
  const {Option} = Select
  const [form] = Form.useForm();


  // useEffect(() => {
  //   const today = new Date();
  //   const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    
  //   // Set the date range to the current month (1st to today)
  //   setDateRange([moment(firstDayOfMonth), moment(today)]);
  //   getAllTransportCharges(undefined, undefined,firstDayOfMonth, today);
  //   getAllContractors();
  //   GetAllVillages()
  // }, []);
  useEffect(() => {
    const today = new Date();
    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1); // Local time
  
    // Set the date range to the current month (1st to today).
    setDateRange([moment(firstDayOfMonth), moment(today)]);
    getAllTransportCharges(undefined, undefined, firstDayOfMonth, today);
    getAllContractors();
    GetAllVillages();
  }, []);
  

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

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

  // const getAllTransportCharges = (contractorId?: number, fromDate?: Date, toDate?: Date) => {
  //   const req = new TransportChargesReq(contractorId, fromDate, toDate);
  //   service.getTransportationChargesForReport(req).then((res) => {
  //     if (res.status) {
  //       setTransportData(res.data);
  //       const dynamicColumns = generateDynamicColumns(res.data, fromDate, toDate);
  //       setColumns(dynamicColumns);
  //     } else {
  //       AlertMessages.getErrorMessage(res.internalMessage);
  //       setTransportData([]);
  //     }
  //   }).catch((err) => {
  //     AlertMessages.getErrorMessage(err.message);
  //     setTransportData([]);
  //   });
  // };


  const getAllTransportCharges = (contractorId?: number, villageId?: number, fromDate?: Date, toDate?: Date) => {
    // Convert dates to UTC ISO format
    const fromDateUTC = fromDate ? new Date(fromDate.getTime() - fromDate.getTimezoneOffset() * 60000).toISOString() : undefined;
    const toDateUTC = toDate ? new Date(toDate.getTime() - toDate.getTimezoneOffset() * 60000).toISOString() : undefined;

    const req = new TransportChargesReq(Number(contractorId), villageId, fromDateUTC, toDateUTC);
    console.log(req, "reqqqqqqqqqqqqqqqqq");

    service.getWorkerWaseReport(req)
      .then((res) => {
        if (res.status) {
          setTransportData(res.data);
          const dynamicColumns = generateDynamicColumns(res.data, fromDate, toDate);
          setColumns(dynamicColumns);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
          setTransportData([]);
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setTransportData([]);
      });
};



  // const getAllTransportCharges = (contractorId?: number, villageId?: number, fromDate?: Date, toDate?: Date) => {
  //   // Format the dates to ISO 8601 strings (e.g., "2025-01-01T00:00:00.000Z").
  //   const formattedFromDate = fromDate ? fromDate.toISOString() : undefined;
  //   const formattedToDate = toDate ? toDate.toISOString() : undefined;
  
  //   // Create the payload with properly formatted dates.
  //   const req = new TransportChargesReq(Number(contractorId), villageId, formattedFromDate, formattedToDate);
  
  //   console.log(req, "Payload being sent");
  
  //   service
  //     .getWorkerWaseReport(req)
  //     .then((res) => {
  //       if (res.status) {
  //         setTransportData(res.data);
  //         const dynamicColumns = generateDynamicColumns(res.data, fromDate, toDate);
  //         setColumns(dynamicColumns);
  //       } else {
  //         AlertMessages.getErrorMessage(res.internalMessage);
  //         setTransportData([]);
  //       }
  //     })
  //     .catch((err) => {
  //       AlertMessages.getErrorMessage(err.message);
  //       setTransportData([]);
  //     });
  // };
  const generateDynamicColumns = (data, fromDate, toDate) => {
    const baseColumns = [
      { title: 'S No', key: 'id', align: 'center', width: '70px' },
      { title: 'ID No', dataIndex: 'idNo', key: 'idNo', align: 'right', width: '140px' },
      { title: 'Name', dataIndex: 'name', key: 'name', align: 'right', width: '140px' }
    ];
  
    const dayColumns = [];
    if (fromDate && toDate) {
      const start = new Date(fromDate);
      const end = new Date(toDate);
  
      for (let d = start; d <= end; d.setDate(d.getDate() + 1)) {
        const day = d.getDate();
        const dayKey = day < 10 ? `0${day}` : day.toString();
  
        dayColumns.push({
          title: dayKey,
          dataIndex: `days.${dayKey}`,
          key: `day-${dayKey}`,
          align: 'center',
          width: '80px',
        });
      }
    }
  
    const totalColumn = {
      title: 'Total',
      key: 'total',
      align: 'center',
      width: '130px',
    };
  
    const totalDaysColumn = {
      title: 'Total Days',
      key: 'totalDays',
      align: 'center',
      width: '120px',
      render: (_, record) => {
        // Calculate the total number of days the worker came based on non-zero days
        const totalDays = dayColumns.reduce((count, col) => {
          console.log(totalDays,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
          const dayValue = record.days?.[col.title] || 0;
          return count + (dayValue > 0 ? 1 : 0);
        }, 0);
        return totalDays;
      },
    };

    const signatureColumn = {
      title: 'Signature',
      key: 'signature',
      align: 'center',
      width: '120px',
    };
  
  
  
    return [...baseColumns, ...dayColumns, totalDaysColumn, totalColumn,signatureColumn];
  };



  
  

  const handleFilter = () => {
    const contractorId = form.getFieldValue('contractorId');
    const villageId = form.getFieldValue('villageId');

    // Find the selected village based on the village ID
    const selectedVillage = villages.find((v) => v.villageId === villageId);
    const selectedContractor = contractors.find((c) => c.contractorId === Number(contractorId));

    const startDate = dateRange ? dateRange[0].startOf('day').toDate() : undefined;
    const endDate = dateRange ? dateRange[1].endOf('day').toDate() : undefined;

    setSelectedContractorName(selectedContractor ? selectedContractor.contractor : '');
    setSelectedVillageName(selectedVillage ? selectedVillage.villageName : '');
    
    getAllTransportCharges(contractorId ? Number(contractorId) : undefined, villageId, startDate, endDate);
    setShowTable(true);
};

  const formatDateRangee = () => {
    if (dateRange) {
      const startMonth = dateRange[0].format('MMMM YYYY');
      return startMonth;
    }
    return '';
  };

  const resetFilters = ( ) => {
    const today = new Date();
    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    form.resetFields(); 
    setDateRange([moment(firstDayOfMonth), moment(today)]);
    document.getElementById('contractorId') ;
    setSelectedContractorName('');
    setSelectedVillageName('')
    getAllTransportCharges(undefined,undefined, firstDayOfMonth, today);
    
  };

  const formatDateRange = () => {
    if (dateRange) {
        const startDate = dateRange[0].format('MMMM DD');
        const endDate = dateRange[1].format('MMMM DD, YYYY');
        return `${startDate} to ${endDate}`;
    }
    return '';
};

  

  return (
    <>
    <style>
      {
        `
         .ta-b {
    border: 1px solid black;
    border-collapse: collapse;
    padding: 5px;
    text-align: left;
      }
    `
      }
    </style>
    <html>
      <body>
    <div>
   
      <div style={{ textAlign: 'center', paddingBottom: '20px' }}>
      <Card 
        size="small" 
        title={<span style={{ color: 'white' }}>Worker Wise  Charges Report</span>}
        style={{ textAlign: 'center' }} 
        headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
        extra={
          <>
          {transportData.length > 0 && (
          <ReactHTMLTableToExcel
          id="export-excel-button"
          // className="download-table-xls-button"
          table="my-table"
          filename="worker-wise-wages-report"
          sheet="worker-wise-wages-report"
           buttonText="Get Excel"
          
      />
  ) }
          </>
        }
       // Add the Excel button here
      >
        <Form form={form} layout="inline">
        <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 name="dateRange"
          label="Date"
             rules={[
              {
                required: true,
                message: "select date range"
              },
            ]}>
            <DatePicker.RangePicker value={dateRange} onChange={setDateRange} />
            
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleFilter}>search</Button>
            <Button style={{ marginLeft: 8 }} onClick={resetFilters}>Reset</Button>       
            {/* <Button onClick={exportToExcel} style={{ marginLeft: '10px' }}>Export to Excel</Button> */}


          </Form.Item>
        </Form>
      </Card>
        </div>
      </div>

      { showTable && (   
<table id="my-table">


      <table style={{ width: '100%', tableLayout: 'fixed' }}>
      <div style={{  textAlign: 'center', padding: '5px', fontWeight: 'bold' }}>
  {transportData.unitName}
    </div>

    <div style={{  textAlign: 'center', padding: '5px', fontWeight: 'bold' }}>
   Peeling Details From {formatDateRange()}
    </div>
  
  
  <tr>
        <div>contractor : <b>{selectedContractorName || ''} </b></div>
        <div>village: <b>{selectedVillageName} </b></div>
        <div>Month:  <b>{formatDateRangee()}</b></div>
    </tr>
    <br></br>

 
</table>



<table width="100%" style={{ textAlign: 'center',border:'1px solid black' }} >
  <thead className='ta-b'>
    <tr className='ta-b'>
      {columns.map((col) => (
        <th key={col.key}>{col.title}</th>
      ))}
    </tr>
  </thead>
  <tbody className='ta-b'>
  {transportData
    .filter((data) => {
      const hasNonZeroDay = columns
        .filter((col) => col.key.startsWith('day-'))
        .some((col) => Number(data.days?.[col.title] || 0) !== 0);
      return hasNonZeroDay;
    })
    .map((data, index) => {
      const totalDays = columns
        .filter((col) => col.key.startsWith('day-'))
        .reduce((count, col) => count + (data.days?.[col.title] > 0 ? 1 : 0), 0);

      return (
        <tr className='ta-b' key={data.id}>
          <td className='ta-b'>{(page - 1) * 10 + (index + 1)}</td>
          <td className='ta-b'>{data.idNo}</td>
          <td className='ta-b'>{data.name}</td>

          {columns
            .filter((col) => col.key.startsWith('day-'))
            .map((col) => (
              <td className='ta-b' key={col.key}>{Math.round(data.days?.[col.title] || 0)}</td>
            ))}

          <td className='ta-b'>

            {totalDays}


          </td>

          <td className='ta-b'><b>
                     {Math.round(
  columns.reduce((sum, col) => {
    if (col.key.startsWith('day-')) {
      return sum + Number(data.days?.[col.title] || 0);
    }
    return sum;
  }, 0)
)}
            </b></td>  {/* Display total days here */}
        </tr>
      );
    })}
</tbody>



  {/* Summary Row */}
  <tfoot className='ta-b'>
    <tr className='ta-b'>
      <td className='ta-b' colSpan={2}><strong>Total</strong></td>

      {/* Calculate the total cost column */}
      <td className='ta-b'>
        {/* {transportData.reduce((total, data) => total + (data.cost || 0), 0)} */}
      </td>

      {/* Calculate the sum for each day */}
      {columns
  .filter((col) => col.key.startsWith('day-'))
  .map((col) => (
    <td className='ta-b' key={`sum-${col.key}`}>
       {Math.round(
        transportData.reduce((sum, data) => sum + Number(data.days?.[col.title] || 0), 0)
      )}
    </td>
  ))}

        {/* Total for the amount column */}
        <td className='ta-b'>
  {transportData.reduce(
    (sum, data) =>
      sum +
      columns
        .filter((col) => col?.key?.startsWith('day-'))
        .reduce((subtotal, col) => subtotal + (data?.days?.[col?.title] > 0 ? 1 : 0), 0),
    0
  )}
</td>
      {/* Total for the total column */}
      <td className='ta-b'>
        {Math.round(transportData.reduce(
          (sum, data) =>
            sum +
            columns
              .filter((col) => col.key.startsWith('day-'))
              .reduce((subtotal, col) => subtotal + (Number(data.days?.[col.title] || 0)), 0),
          0
        ))}
      </td>


    </tr>
    <tr className='ta-b'>
      <td className='ta-b' colSpan={3}><b>Total Days</b></td>
      
      {columns
        .filter((col) => col.key.startsWith('day-'))
        .map((col) => {
          const totalDayCount = transportData.reduce((sum, data) => {
            return sum + (data.days?.[col.title] > 0 ? 1 : 0);
          }, 0);
          return (
            <td className='ta-b' key={`total-${col.key}`}><b>{totalDayCount}</b></td>
          );
        })
      }

      {/* Empty cell for the Total column */}
      <td className='ta-b'>
        <b>
      {transportData.reduce(
    (sum, data) =>
      sum +
      columns
        .filter((col) => col?.key?.startsWith('day-'))
        .reduce((subtotal, col) => subtotal + (data?.days?.[col?.title] > 0 ? 1 : 0), 0),
    0
  )}</b>
      </td>
      
      {/* Empty cell for the Total Days column */}
      <td className='ta-b'></td>
    </tr>
  </tfoot>
</table>
</table>
)}

    </body>
    </html>
    </>
  );
};

export default WorkerWiseWagesReport;
