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 TransportationChargesReport = () => {
  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 [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()
  }, []);

  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;
  
    // Create request object with UTC dates
    const req = new TransportChargesReq(
      Number(contractorId),
      villageId,
      fromDateUTC,
      toDateUTC
    );
  
    console.log(req, "Request Object //////////////////");
  
    // Call the service with the updated request object
    service
      .getTransportationChargesForReport(req)
      .then((res) => {
        if (res.status) {
          setTransportData(res.data);
  
          // Generate dynamic columns based on day-wise data
          const dynamicColumns = generateDynamicColumns(res.data, fromDateUTC, toDateUTC);
          setColumns(dynamicColumns);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
          setTransportData([]);
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setTransportData([]);
      });
  };
  
  const startOfMonth = moment().startOf('month');
  const today = moment();

  // const disabledDate = (current) => {
  //   if (!dateRange || !dateRange[0]) return false;
  //   const startDate = dateRange[0];
    
  //   // Disable dates before the start date or after 30 days from the start date
  //   return current && (current < startDate || current > startDate.clone().add(30, 'days'));
  // };

  const generateDynamicColumns = (data, fromDate, toDate) => {
    const baseColumns = [
      { title: 'S No', key: 'id', align: 'center', width: '70px' },
      { title: 'Village Name', dataIndex: 'village', key: 'village', align: 'right', width: '140px' },
      { title: 'Rs', dataIndex: 'cost', key: 'cost', 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: '120px',
    };

    const amountColumn = {
      title: 'Amount',
      key: 'amount',
      align: 'center',
      width: '120px',
    };
  
    return [...baseColumns, ...dayColumns, totalColumn, amountColumn];
  };

  const handleFilter = () => {
    const contractorId = form.getFieldValue('contractorId');
    const villageId = form.getFieldValue('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 : '');
    getAllTransportCharges(contractorId ? Number(contractorId) : undefined,villageId, startDate, endDate);
    setShowTable(true);
  };
  const formatDateRange = () => {
    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('');
    getAllTransportCharges(undefined, undefined,firstDayOfMonth, today);
    
  };

  

  const exportToExcel = () => {
    const exportData = transportData.map(record => {
      const formattedRecord = {
        'Village Name': record.village,
        'Cost': record.cost,
      };

      columns.forEach(column => {
        if (column.key.startsWith('day-')) {
          const dayKey = column.title;
          formattedRecord[dayKey] = record.days?.[dayKey] || 0;
        }
      });

      const total = columns.reduce((sum, col) => {
        if (col.key.startsWith('day-')) {
          const dayKey = col.title;
          return sum + (Number(record.days?.[dayKey] || 0));
        }
        return sum;
      }, 0);

      const amount = total * (record.cost || 0);
      formattedRecord['Total'] = total;
      formattedRecord['Amount'] = amount.toFixed(2);

      return formattedRecord;
    });

    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet(exportData);
    XLSX.utils.sheet_add_aoa(worksheet, [[`Transportation Charges Report for ${selectedContractorName || ''}`]], { origin: 'A1' });
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Transportation Charges');
    XLSX.writeFile(workbook, `Transportation_Charges_${selectedContractorName || 'Report'}.xlsx`);
  };

  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' }}>Transportation 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="transportation-charges-report "
                sheet="transportation-charges-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}    defaultValue={[startOfMonth, today]}/>
            
          </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' }}>
  <tr>
    <td style={{ border: '1px solid black', textAlign: 'center', padding: '5px', fontWeight: 'bold' }} colSpan={2}>
      Transportation Charges (AUTO) for the month of Transportation utilised by the Local Workers for the Contractor {selectedContractorName || ''}
    </td>
  </tr>

  <tr>
    <td style={{ border: '1px solid black', textAlign: 'center', padding: '5px', fontWeight: 'bold' }}>
      {selectedContractorName}
    </td>
    <td style={{ border: '1px solid black', textAlign: 'center', padding: '5px', fontWeight: 'bold' }}>
      {formatDateRange()}
    </td>
  </tr>
</table>


   {/* <tr style={{ border: '1px solid black', textAlign: 'center', padding: '10px', fontWeight: 'bold' }}>{selectedContractorName}</tr>
   <tr style={{ border: '1px solid black', textAlign: 'center', padding: '10px', fontWeight: 'bold' }}>{formatDateRange()}</tr> */}

<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.map((data, index) => (
      <tr className='ta-b' key={data.id}>
        <td className='ta-b'>{(page - 1) * 10 + (index + 1)}</td>
        <td className='ta-b'>{data.village}</td>
        <td className='ta-b'>{data.cost}</td>

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

        <td className='ta-b'>
          {columns
            .filter((col) => col.key.startsWith('day-'))
            .reduce((sum, col) => sum + (Number(data.days?.[col.title] || 0)), 0)}
        </td>

        <td className='ta-b'>
          {(columns
            .filter((col) => col.key.startsWith('day-'))
            .reduce((sum, col) => sum + (Number(data.days?.[col.title] || 0)), 0) * data.cost).toFixed(2)}
        </td>
      </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}`}>
            {transportData.reduce((sum, data) => sum + (Number(data.days?.[col.title] || 0)), 0)}
          </td>
        ))}

      {/* Total for the total column */}
      <td className='ta-b'>
        {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>

      {/* Total for the amount column */}
      <td className='ta-b'>
        {transportData
          .reduce((sum, data) => {
            const totalDays = columns
              .filter((col) => col.key.startsWith('day-'))
              .reduce((subtotal, col) => subtotal + (Number(data.days?.[col.title] || 0)), 0);
            return sum + totalDays * (data.cost || 0);
          }, 0)
          .toFixed(2)}
      </td>
    </tr>
  </tfoot>
</table>
</table>
)}

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

export default TransportationChargesReport;
