import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Input, Button, Tag, Divider, Popconfirm, Switch, Card, Row, Table, Drawer, Col, Descriptions } from 'antd';
import { ColumnProps } from 'antd/lib/table';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import {CheckCircleOutlined,CloseCircleOutlined,RightSquareOutlined,EyeOutlined,EditOutlined,SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { EnquiriesService } from "libs/shared-services/enquiry-management/src/lib/enquiries-service"
import { RmCountPriceListService } from "libs/shared-services/raw-material-procurement/src/lib/rm-count-pricelist"
import { CompanyCategoryEnum } from '@gtpl/shared-models/raw-material-procurement';
import moment from 'moment';

/* eslint-disable-next-line */
export interface RmRatesReportProps {}

export function RmRatesReport(
  props: RmRatesReportProps
) {
 
 
  const searchInput = useRef(null);
  const [page, setPage] = React.useState(1);
  const [searchText, setSearchText] = useState(''); 
  const [searchedColumn, setSearchedColumn] = useState('');
  const [data, setData]=useState([])
  const [countPriceInfo,setCountPriceInfo] = useState<any[]>([])
  const enquiryService = new EnquiriesService()
  const rmRateService = new RmCountPriceListService()
  const [aquaData, setAquaData]=useState([])
  const [deviationData, setDeviationData]=useState([])
  const [dates, setDates]=useState([])
  const [companies, setCompanies]=useState([])

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

  /**
   * 
   */
 
  const getAll= () => {
    console.log(localStorage.getItem('createdUser'))
    rmRateService.getRmRatesBmr().then(res => {
      if(res.status){
          setCountPriceInfo(res.data)
      }
  })
  rmRateService.getCompanies().then(res => {
    if (res.status) {
      setCompanies(res.data);
    } else {
    setCompanies([]);
    AlertMessages.getErrorMessage(res.internalMessage);
  }
})
    rmRateService.getRmRatesData().then(res => {
      if (res.status) {
        setData(res.data.filter((res)=>res.category !== CompanyCategoryEnum.OWN));
      } else {
            setData([]);
            AlertMessages.getErrorMessage(res.internalMessage);
      }
    // }).catch(err => {
    //   setData([]);
    //   AlertMessages.getErrorMessage(err.message);
    })
    rmRateService.getRmRatesAqua().then(res => {
      if (res.status) {
        setAquaData(res.data);
      } else {
        // if (res.intlCode) {
          setAquaData([]);
            AlertMessages.getErrorMessage(res.internalMessage);
        // }
      }
    // }).catch(err => {
    //   setAquaData([]);
    //   AlertMessages.getErrorMessage(err.message);
    })
    rmRateService.getRmPriceDeviation().then(res => {
      if (res.status) {
        setDeviationData(res.data);
      } else {
        // if (res.intlCode) {
          setDeviationData([]);
            AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //  AlertMessages.getErrorMessage(res.internalMessage);
        // }
      }
    // }).catch(err => {
    //   setDeviationData([]);
    //   AlertMessages.getErrorMessage(err.message);
    })
    rmRateService.getRmReportDates().then(res => {
      if (res.status) {
        setDates(res.data);
      } else {
        // if (res.intlCode) {
          setDates([]);
            AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //  AlertMessages.getErrorMessage(res.internalMessage);
        // }
      }
    // }).catch(err => {
    //   setDates([]);
    //   AlertMessages.getErrorMessage(err.message);
    })
  }


  const getColumnSearchProps = (dataIndex:string) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={ searchInput }
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
          icon={<SearchOutlined />}
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          Search
        </Button>
        <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <SearchOutlined type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
    record[dataIndex]
    ? record[dataIndex]
       .toString()
        .toLowerCase()
        .includes(value.toLowerCase())
        : false,
    onFilterDropdownVisibleChange: visible => {
      if (visible) {    setTimeout(() => searchInput.current.select());   }
    },
    render: text =>
      text ?(
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text.toString()}
        />
      ) :text
      )
      : null
     
  });

  /**
   * 
   * @param selectedKeys 
   * @param confirm 
   * @param dataIndex 
   */
  function handleSearch(selectedKeys, confirm, dataIndex) {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  function handleReset(clearFilters) {
    clearFilters();
    setSearchText('');
  };

   
    //TO open the form for updation
 

  const columnsSkelton: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      // hideInSearch: true,
      // hideInForm: true,
      responsive: ['sm'],
      render: (text, object, index) => (page-1) * 10 +(index+1)
    },

    {
      title: 'Bank Name',
      dataIndex: 'bankName',
 
      sorter: (a, b) => a.bankName.localeCompare(b.bankName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('bankName')
    },
    {
      title: 'Branch Name',
      dataIndex: 'branchName',
 
      sorter: (a, b) => a.branchName.localeCompare(b.branchName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('branchName')
    },
    {
      title: 'Account No',
      dataIndex: 'bankAcc',
      sorter: (a, b) => a.bankAcc.localeCompare(b.bankAcc),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('bankAcc')
    },
    {
      title: 'IFSC Code',
      dataIndex: 'ifscCode',
      sorter: (a, b) => a.ifscCode.localeCompare(b.ifscCode),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('ifscCode')
    },
    {
      title: 'Swift Code',
      dataIndex: 'swiftCode',
 
      sorter: (a, b) => a.swiftCode.localeCompare(b.swiftCode),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('swiftCode')
    },
    {
      title: 'Bank Address',
      dataIndex: 'bankAddress',
 
      sorter: (a, b) => a.bankAddress.localeCompare(b.bankAddress),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('bankAddress')
    },
    
  ];

  const onChange=(pagination, filters, sorter, extra)=> {
    console.log('params', pagination, filters, sorter, extra);
  }
const currentDate = new Date()
  
  return (
    <>
    <Card title={<span style={{color:'white'}}>Average RM Rates Report</span>}
    style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }}>
  
          <br></br><br/>
          <Card>
            <div style={{justifySelf:'flex-end'}}>
              <Descriptions contentStyle={{justifyContent:'end'}}>
              <h2>Date:{moment(currentDate).format('DD-MM-YYYY')}</h2>
              </Descriptions>
            </div>
            <Row>
              <Descriptions>
                <Descriptions.Item>Booking Date:{dates?.[0]?.latest? moment(dates?.[0]?.latest).format('DD-MM-YYYY'):'-'}</Descriptions.Item>
                <Descriptions.Item>Harvest Date:{dates?.[0]?.harvestDate? moment(dates?.[0]?.harvestDate).format('DD-MM-YYYY'):'-'}</Descriptions.Item>
              </Descriptions>
            </Row>
            {/* <table className={'ta-b'} style={{ width: '100%', tableLayout: 'fixed' }}>
  <tr style={{backgroundColor:'#ffba08'}}>
    <th className={'ta-b'}>Count</th>
    {data.map((company, index) => (
      <th key={index} className={'ta-b'}>{company.company}</th>
    ))}
  </tr>
  {data?.[0]?.data.map((entry, index) => ( // Assuming all companies have the same number of entries
    <tr key={index}>
      <td className={'ta-b'}>{entry?.count}</td>
      {data.map((company) => (
        <td className={'ta-b'} key={company?.company}>{company?.data[index]?.price}</td>
      ))}
    </tr>
  ))}
</table> */}
<table className={'ta-b'} style={{ width: '100%', tableLayout: 'fixed' }}>
  <tr style={{backgroundColor:'#ffba08'}}>
    <th className={'ta-b'}>Count</th>
    {data.map((company, index) => (
      <th key={index} className={'ta-b'}>{company.company}</th>
    ))}
  </tr>
 
   {Array.from(new Set(data.reduce((acc, val) => acc.concat(val.data.map(e => e.count)), []))).map((count, countIndex) => (
    <tr key={countIndex}>
      <td className={'ta-b'}>{count}</td>
      {/* Iterate over companies to fill in the corresponding price for each count */}
      {data.map((company, companyIndex) => (
        <td key={companyIndex} className={'ta-b'}>
          {company.data.find(item => item.count === count)?.price || '-'}
        </td>
      ))}
    </tr>
  ))}
</table>
{/* <table className={'ta-b'} style={{ width: '100%', tableLayout: 'fixed' }}>
  <tr style={{ backgroundColor:'#ffba08' }}>
    <th className={'ta-b'}>Count</th>
    {data.map((company, index) => (
      <th key={index} className={'ta-b'}>{company.company}</th>
    ))}
  </tr>
  {data.reduce((maxEntries, company) => Math.max(maxEntries, company.data.length), 0).map(index => (
    <tr key={index}>
      <td className={'ta-b'}>{data[0]?.data[index]?.count || 'N/A'}</td> 
      {data.map((company) => (
        <td className={'ta-b'} key={company?.company}>{company?.data[index]?.price || 'N/A'}</td>
      ))}
    </tr>
  ))}
</table> */}
          <Row gutter={[50,50]}>
          {countPriceInfo.length>0?(<Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 8 }}>
                        <div style={{padding:'20px'}}>
                            <b>BMR Purchase Rates</b>
                            <br/><br/><br/><br/>
                            <table className={'ta-b'} style={{ width: '100%', tableLayout: 'fixed' }}>
                                <tr style={{backgroundColor:'#ffba08'}}>
                                    <th className={'ta-b'}>COUNT</th>
                                    <th className={'ta-b'} >RATE</th>
                                </tr>
                                    {
                                        countPriceInfo.map(rec => {

                                           
                                            return(
                                                <>
                                                <tr style={{backgroundColor: rec.colorVar ? 'lightblue' : ''}}>
                                                <td className={'ta-b'}>{rec.count ? rec.count : '-'}</td>
                                                <td className={'ta-b'}>{rec.price ? rec.price : '-'}</td>
                                                </tr>
                                                </>
                                            )
                                        })
                                    }
                            </table>
                        </div>
                        </Col>):''}
                        {aquaData.length>0?(<Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 8 }}>
                        <div style={{padding:'20px'}}>
                            <b>Aqua Brama Online RM Purchase Rates</b>
                            <br/><br/><br/><br/>
                            <table className={'ta-b'} style={{ width: '100%', tableLayout: 'fixed' }}>
                                <tr style={{backgroundColor:'#ffba08'}}>
                                    <th className={'ta-b'}>COUNT</th>
                                    <th className={'ta-b'} >RATE</th>
                                </tr>
                                    {
                                        aquaData.map(rec => {
                                               return(
                                                <>
                                                <tr style={{backgroundColor: rec.colorVar ? 'lightblue' : ''}}>
                                                <td className={'ta-b'}>{rec.count ? rec.count : '-'}</td>
                                                <td className={'ta-b'}>{rec.price ? rec.price : '-'}</td>
                                                </tr>
                                                </>
                                            )
                                        })
                                    }
                            </table>
                        </div>
                        </Col>):''}
          </Row>
          <div>
            <Descriptions contentStyle={{justifyContent:'initial'}}>
              <Descriptions.Item>Rs.5/- extra for Ice and Delivery</Descriptions.Item>
            </Descriptions>
           </div>
          {deviationData.length>0?(<Row>
          <div>
                            <b> RM Purchase PriceDeviation</b>
                            <br/><br/><br/><br/>
                            <table className={'ta-b'} style={{ width: '100%', tableLayout: 'fixed' }}>
                                <tr style={{backgroundColor:'#ffba08'}}>
                                    <th className={'ta-b'}>DATE</th>
                                    <th className={'ta-b'}>Farmer</th>
                                    <th className={'ta-b'}>COUNT</th>
                                    <th className={'ta-b'}>RATE</th>
                                    <th className={'ta-b'}>Remarks</th>

                                </tr>
                                    {
                                        deviationData.map(rec => {

                                            // const obj = rec.count.split('-')
                                            // const count = obj[0] == obj[1] ? obj[0] : rec.count
                                            return(
                                                <>
                                                <tr style={{backgroundColor: rec.colorVar ? 'lightblue' : ''}}>
                                                  <td className={'ta-b'}>{rec.date ? moment(rec.date).format('DD-MM-YYYY') :'-'}</td>
                                                  <td className={'ta-b'}>{rec.farmer ? rec.farmer:'-'}</td>
                                                <td className={'ta-b'}>{rec.count ? rec.count : '-'}</td>
                                                <td className={'ta-b'}>{rec.price ? rec.price : '-'}</td>
                                                <td className={'ta-b'}>Rs.{rec.deviation ? rec.deviation : '-'} /-excess approved by KSR for feed materials</td>

                                                </tr>
                                                </>
                                            )
                                        })
                                    }
                            </table>
                        </div>

          </Row>):''}
        </Card>
       
     </Card>
    </>
  );


}

export default RmRatesReport;
