import styled from "@emotion/styled";
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import { Button, Card, Col, Container, Form, InputGroup, Row, Table } from "react-bootstrap"
import Pagination from "./Pagination";
import YearSelect from "./YearSelect";
import { DownloadTableExcel } from "react-export-table-to-excel";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as Icons from "@fortawesome/free-solid-svg-icons";

const TDSCompWrapper = styled.div`
.table td,th{
    white-space:nowrap;
}
`
const MonthSumTax=()=>{
    const [empdata, setEmpData] = useState([]);
    const [empid, setEmpID] = useState("");
    const [fromyear, setFromYear] = useState("");
    const [payrolldata, setPayrollData] = useState([]);
    const [filterData,setFilterData]=useState<any>([]); 
    const [currentPage, setCurrentPage] = useState(0);
    const [postsPerPage] = useState(15);
    
    const taxTableRef = useRef<HTMLTableElement>(null);
console.log(filterData, "All Data");
  // const taxTableRef = useRef(null);

        const fetchEmp = async () => {
          try {
            let emp_id = empid;
            let from_year= fromyear;
            let to_year=parseInt(fromyear) + 1;
            const res = await
              axios.get(`/api/user/itd_old_regime?&emp_id=${emp_id}&from_year=${from_year}&to_year=${to_year}`);
                setEmpData(res.data.results[0]);
                setFilterData(res.data.results[0])
             
              
            console.log("Employee ITD Data", res.data.results[0]);
          } catch (error) {
            console.log(error, "Error Fetching Employee ITD Request Data");
          }
        };
        const itdData=async()=>{
           const res=await axios.post(`/api/user/get_emp_itd`)
           console.log(res.data.results[0],'jjjjjjjj');
           setFilterData(res.data.results[0]);
           setPayrollData(res.data.results[0]);
        }
        useEffect(()=>{
          itdData()
        },[])

        // Get current posts
  const paginateData=(arg:any)=>{
    const indexOfLastPost = arg * postsPerPage;
    const indexOfFirstPost = indexOfLastPost - postsPerPage;
    const currentPosts = empdata.slice(indexOfFirstPost, indexOfLastPost);
  
    setFilterData(currentPosts)
  }
  useEffect(()=>{
    paginateData(currentPage)
  },[empdata])
  // Change page
  const paginate = (pageNumber: any) => {
    setCurrentPage(pageNumber)
    paginateData(pageNumber)
  };
  
    return(
        <>
        <TDSCompWrapper>
        <Container>
            <Row>
            <Col lg="12" className="mb-3">
                <Card>
                    <Card.Body>
                <Form as={Row} className="d-flex justify-content-center">
                    <Col lg="6" sm="12">
                            <InputGroup>
                        
                        <Form.Select name="emp_id"  onChange={(e)=>setEmpID(e.target.value)}>
                          <option>Select Emp. ID</option>
                            {payrolldata.map((emp:any,i:any)=>{
                             return <option key={i} value={emp?.emp_id}>{emp?.emp_id}</option>
                            })
                            }
                        </Form.Select>
                      
                        <Form.Select  name="from_year" placeholder="Starting Year" onChange={(e)=>setFromYear(e.target.value)}>
                          <option>Select Year</option>
                  <YearSelect/>
                        </Form.Select>
                       
                       
                        <Button variant="outline-secondary"
                        onClick={fetchEmp}
                        id="button-addon2">
                        Search
                        </Button>
                    </InputGroup>
                </Col>
                </Form>
                </Card.Body>
                </Card>
            </Col>
                <Col sm={12} md={8}>
                <h4>TDS Calculation Summary(OLD)</h4>
                </Col>
                <Col sm={12} md={4} className="text-end">
                <DownloadTableExcel
                    filename="Tax Summary"
                    sheet="tax summary"
                    currentTableRef={taxTableRef.current}
                  >
                    <Button variant="primary" size="sm" id="button-addon2">
                      Download
                      <FontAwesomeIcon
                        icon={Icons.faFileArrowDown}
                        className="ms-1"
                      />
                    </Button>
                  </DownloadTableExcel>
                </Col>
                <Col>
               
                <Table responsive bordered ref={taxTableRef}>
                    <thead>
                        <tr>
                            <th>Emp. ID</th>
                            <th>Name</th>
                            <th>PAN Number</th>
                            <th>Adhoc</th>
                            <th>Basic</th>
                            <th>Bonus</th>
                            <th>House Rent Allowance</th>
                            <th>Conveyance Allowance</th>
                            <th>Medical Allowance</th>
                            <th>Telephone Allowance</th>
                            <th>Special Allowances</th>
                            <th>Relocation Allowences</th>
                            <th>Leave Travel Allowance</th>
                            <th>MealPlus Card</th>
                            <th>Gross Salary</th>
                            <th>House Rent</th>
                            <th>Total Exemption u/s 10</th>
                            <th>Gross Salaries after exemption u/s 10</th>
                            <th>Total deduction u/s 16</th>
                            <th>Income from Salary</th>
                            <th>Gross Total Income</th>
                            <th>Sec 80D - Medical Insurance Premium</th>
                            <th>Sec 80DD - Handicapped Dependent</th>
                            <th>Sec 80E - Repayment of Loan for higher education</th>
                            <th>Sec 80GG - Rent Paid</th>
                            <th>Sec 80U - Handicapped</th>
                            <th>Sec 80CCG - Rajeev Gandhi Equity Saving Scheme</th>
                            <th>Sec 80TTA / 80TTB - Interest on saving a/c</th>
                            <th>Other Deduction</th>
                            <th>Sec 80C - Contribution to Pension Fund-Jeevan Suraksha</th>
                            <th>Sec 80C - Life Insurance Premium</th>
                            <th>Sec 80C - Deferred Annuity</th>
                            <th>Sec 80C - Public Provident Fund</th>
                            <th>Sec 80C - ULIP of UTI/LIC</th>
                            <th>Sec 80C - Repayment of Housing Loan</th>
                            <th>Sec 80C - Contribution to Pension Fund or UTI or Notified Mutual Fund</th>
                            <th>Sec 80C - Investment in ELSS made in units of Notified Mutual Fund</th>
                            <th>Sec 80C - Children Tuition Fee: Restricted to a max of 2 Children</th>
                            <th>Sec 80C - Deposit in home loan account scheme of NHB/HDFC</th>
                            <th>Sec 80C - 5 yrs. Term deposit in a Sch.Bank</th>
                            <th>Sec 80C - Other</th>
                            <th>Sec 80CCC - Annuity/Pension Plan</th>
                            <th>Sec 80CC (1b)-	Employee Contribution</th>
                            <th>Sec 80CCD -	Notified Pension Scheme</th>
                            <th>Sec 24 - Interest on Housing Loan on fully constructed accomodation only</th>
                            <th>Sec 24 - Interest if the loan is taken before 01/04/99 on fully constructed accomodation only.</th>
                            <th>Standard Deduction</th>
                            <th>Total Exemption</th>
                            <th>Net Taxable Amount</th>
                            <th>Raw Tax</th>
                            <th>Rebate</th>
                            <th>Tax after rebate</th>
                            <th>Cess</th>
                            <th>Surcharge</th>
                            <th>Total tax payable</th>
                            <th>Tax Deducted</th>
                            <th>Difference Amount</th>
                        </tr>
                    </thead>
                    {filterData &&
                    filterData?.map((emp: any, index: any) => {
                      const totalExempAmount = emp.medic_insur_prem_80d+emp.handicap_80u+emp.invest_elss+emp.int_loan_const_acco+emp.int_house_loaan+emp.notif_pens_sch+emp.emp_contri+emp.annuity_pension_plan+emp.other+emp.five_yrs_bank_deposit+emp.deposit_home_looan_sch+emp.child_tution_fee+emp.pf_uti_mutual_fund+emp.housing_loan_repay+emp.ulip_uti_lic+emp.public_pf+emp.deferred_annuity+emp.lic+emp.pf_jeevan_suraksha+emp.other_deduct+emp.int_on_saving_80tta+emp.raj_gandhi_scheme_80ccg+emp.paid_rent_80gg+emp.high_edu_loan_80e+emp.handicap_depend_80dd+emp.house_rent;
                      const totalExemp10 = parseInt(emp?.hra)+parseInt(emp?.lta)+parseInt(emp?.mp_card);

                      const basicpay =parseInt(emp?.basic_pay || 0);
                      const mhra =parseInt(emp?.hra|| 0);
                      const mlta =parseInt(emp?.lta|| 0);
                      const mpf =parseInt(emp?.pf|| 0);
                      const spAllow =parseInt(emp?.spec_allow|| 0);
                      const tallow =parseInt(emp?.ta|| 0);
                      const rallow =parseInt(emp?.ra|| 0);
                      const healthinsurance =parseInt(emp?.health_insurance|| 0);
                      const conveyallow =parseInt(emp?.convey_allow|| 0);
                      const anualbonus = parseInt(emp?.yearly_bonus|| 0);
                      const adhocEarn = parseInt(emp?.adhoc_earning|| 0);
                      const mealplus = parseInt(emp?.mp_card|| 0);
                      const adhoc_dedt = parseInt(emp?.adhoc_deduct|| 0);
                      const emppf = parseInt(emp?.emp_pf|| 0);
                      const proftax = parseInt(emp?.prof_tax || 0);
                      const mtds = parseInt(emp?.tds || 0);
                      const cpf = parseInt(emp?.company_pf || 0);
                      const monthlyDeduct = emppf + proftax + mealplus + adhoc_dedt + mtds
                      const grossSal = basicpay + mhra + mlta + spAllow + tallow + rallow + mealplus + healthinsurance + conveyallow + anualbonus + adhocEarn;
                    
                      const grossAfterExemption = grossSal;
                      const grossAfterExemp = Math.abs(grossAfterExemption);
                      const standardDeduct = 50000
                      const totalDeduct16 = parseInt(emp.prof_tax) + standardDeduct;
                      const incomeFromSal = grossAfterExemp - totalDeduct16;
                      const incomeFromSalary = Math.abs(incomeFromSal);
                      // const incomeFromHouseProperty = 200000
                      const grossTotalIncome =    incomeFromSalary;
                      const totalExemp = Math.abs(totalExempAmount);
                      const TaxAmount =   grossTotalIncome - totalExemp;
                      const netTaxAmount= Math.abs(TaxAmount);
                      const rowTax = (netTaxAmount:number = 0)=>{
                            let tax = 0;
                          if(netTaxAmount <= 250000){
                              tax = 0;
                          }else if(netTaxAmount <= 500000){
                            tax = (netTaxAmount-250000)*0.05
                          }else if(netTaxAmount<=1000000){
                          tax =(netTaxAmount-500000)*0.2+12500
                          }
                          else if(netTaxAmount>1000000){
                            tax = (netTaxAmount-1000000)*0.3+112500
                        }
                        return parseFloat(tax.toFixed(2));
                      }
                      console.log(netTaxAmount);
                      
                      const rtax =rowTax(netTaxAmount);
                       console.log(rtax);
                       
                    const rebateTax = (rtax:number=0, netTaxAmount:number = 0)=>{
                      let rebate=0;
                      if(rtax === 0.00) {
                        rebate=  0;
                      } else if(netTaxAmount > 500000){
                          rebate = 0;
                      } else {
                        rebate =parseFloat( Math.min(rtax, 12500).toFixed(2));
                      }
                      return rebate;
                    }
                    const taxRebate = rebateTax(rtax, netTaxAmount);
                    const taxAfterReb = rtax - taxRebate;

                    const surchargeTax = (netTaxAmount:number = 0, taxAfterReb:number = 0)=>{
                      let surcharge = 0;
                    if (netTaxAmount > 10000000){
                      surcharge = taxAfterReb*0.15
                    }else if(netTaxAmount >= 5000000){
                      surcharge = taxAfterReb*0.1
                    }
                    return surcharge;
                    }
                    const surchargeTaxRate= surchargeTax(netTaxAmount);

                    const TaxPlusSurcharge = taxAfterReb + surchargeTaxRate;

                    const cessTax = TaxPlusSurcharge*0.04
                    const taxpay = cessTax+taxAfterReb
                    const diffAmount =   taxpay - parseInt(emp?.tds);

                      return(
                    <tbody key={index}>
                        <tr>
                            <td>{emp.emp_id}</td>
                            <td>{emp?.name}</td>
                            <td>{emp.pan_number || emp.emp_pan}</td>
                            <td>{emp.adhoc_earning || 0}</td>
                            <td>{Math.round(emp?.basic_pay) || 0}</td>
                            <td>{Math.round(emp?.yearly_bonus) || 0}</td>
                            <td>{Math.round(emp?.hra) || 0}</td>
                            <td>{Math.round(emp?.convey_allow) || 0}</td>
                            <td>{Math.round(emp?.health_insurance) || 0}</td>
                            <td>{Math.round(emp?.ta) || 0}</td>
                            <td>{Math.round(emp?.spec_allow) || 0}</td>
                            <td>{Math.round(emp?.ra) || 0}</td>
                            <td>{Math.round(emp?.lta) || 0}</td>
                            <td>{Math.round(emp?.mp_card) || 0}</td>
                            <td>{Math.round(grossSal) || 0}</td>
                            <td>{Math.round(emp.house_rent) || 0}</td>
                            <td>{Math.round(totalExemp10) || 0}</td>
                            <td>{Math.round(grossAfterExemp) || 0}</td>
                            <td>{Math.round(totalDeduct16) || 0}</td>
                            <td>{Math.round(incomeFromSalary) || 0}</td>
                            <td>{Math.round(grossTotalIncome) ||0}</td>
                            <td>{emp.medic_insur_prem_80d || 0}</td>
                            <td>{emp.handicap_depend_80dd || 0}</td>
                            <td>{emp.high_edu_loan_80e || 0}</td>
                            <td>{emp.paid_rent_80gg || 0}</td>
                            <td>{emp.handicap_80u || 0}</td>
                            <td>{emp.raj_gandhi_scheme_80ccg || 0}</td>
                            <td>{emp.int_on_saving_80tta || 0}</td>
                            <td>{emp.other_deduct || 0}</td>
                            <td>{emp.pf_jeevan_suraksha || 0}</td>
                            <td>{emp.lic || 0}</td>
                            <td>{emp.deferred_annuity || 0}</td>
                            <td>{emp.public_pf || 0}</td>
                            <td>{emp.ulip_uti_lic || 0}</td>
                            <td>{emp.housing_loan_repay || 0}</td>
                            <td>{emp.pf_uti_mutual_fund || 0}</td>
                            <td>{emp.invest_elss || 0}</td>
                            <td>{emp.child_tution_fee || 0}</td>
                            <td>{emp.deposit_home_looan_sch || 0}</td>
                            <td>{emp.five_yrs_bank_deposit || 0}</td>
                            <td>{emp.other || 0}</td>
                            <td>{emp.annuity_pension_plan || 0}</td>
                            <td>{emp.emp_contri || 0}</td>
                            <td>{emp.notif_pens_sch || 0}</td>
                            <td>{emp.int_house_loaan || 0}</td>
                            <td>{emp.int_loan_const_acco || 0}</td>
                            <td>{Math.round(standardDeduct) || 0}</td>
                            <td>{Math.round(totalExemp) || 0}</td>
                            <td>{Math.round(netTaxAmount) || 0}</td>
                            <td>{Math.round(rtax) || 0}</td>
                            <td>{Math.round(taxRebate) || 0}</td>
                            <td>{Math.round(taxAfterReb) || 0}</td>
                            <td>{Math.round(cessTax) || 0}</td>
                            <td>{Math.round(surchargeTaxRate) || 0}</td>
                            <td>{Math.round(taxpay) || 0}</td>
                            <td>{Math.round(emp?.tds) || 0}</td>
                            <td>{Math.round(Math.abs(diffAmount)) || 0}</td>
                        </tr>
                    </tbody>
                     )})}
                </Table>
              
                <Pagination
                postsPerPage={postsPerPage}
                totalPosts={empdata.length}
                paginate={paginate}
                currentPage={currentPage}
                />
                </Col>
            </Row>
        </Container>
        </TDSCompWrapper>
        </>
    )
}
export default MonthSumTax;