import axios from "axios";
import { useEffect, useState } from "react";
import { Button, Form, InputGroup } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as Icons from "@fortawesome/free-solid-svg-icons";
import { toast } from "react-toastify";
import DatePicker from "react-datepicker";
import styled from "@emotion/styled";

const DateInputWrapper = styled.div`
  .react-datepicker__navigation--years-upcoming {
    background-image: url(https://img.icons8.com/plumpy/24/null/collapse-arrow.png);
    background-repeat: no-repeat;
    background-position: center;
    background-size: inherit;
  }
  .react-datepicker__navigation--years-previous {
    background-image: url(https://img.icons8.com/plumpy/24/null/chevron-down.png);
    background-repeat: no-repeat;
    background-position: center;
    background-size: inherit;
  }
`;
const BulkTDSCalc = () => {
  const [allsalary, setSalary] = useState<any>([]);
  const [leave, setLeaveCount] = useState<any>([]);
  const [attendance, setAttendanceCount] = useState<any>([]);
  const [salarydata, setSalaryData] = useState<any>([]);
  const [days, setWorkDays] = useState<any>([ ]);
  const [salarydate, setMonthSalaryDate] = useState(new Date());
  const [itd, setITD]=useState<any>([]);
  const [genrated, setGenerated]= useState(false);
  const [filterData, setFilter]= useState<any>([]);

  useEffect(() => {
    const  fetchPayroll = async () =>{
      try {
        const response = await axios.get(`/api/user/itd_old_regime_all`);
        setITD(response.data.results[0]);
        setFilter(response.data.results[0]);
        console.log(response.data.results[0], "ITD");
  
      } catch (error) {
        console.log(error, "Error Fetching Salary Data");
      }
    };
    fetchPayroll();
  }, []);
  const fetchEmp = async () => {
    try {
      console.log();
      const res = axios.all([
        axios.get(`/api/users/bulktdscalc`).then((res) => {
          setSalary(res.data.results);
          setFilter(res.data.results);
          console.log(res.data, "Payroll details");
        }),
      
        axios.post(`/api/users/bulktdscalc`).then((res) => {
          setSalaryData(res.data.results);
          console.log(res.data, "Attendance count");
        }),
      ]);
    } catch (error) {
      console.log(error, "Fetching user data error");
    }
  };

  const transformedPayroll =
    allsalary &&
    allsalary.map((emp: any) => {
      const {
        emp_id,
        monthly_pay,
        basic_pay,
        hra,
        lta,
        pf,
        spec_allow,
        ta,
        ra,
        health_insurance,
        convey_allow,
        yearly_bonus,
        adhoc_earning,
        adhoc_deduct,
        mp_card,
        emp_pf,
        tds,
        prof_tax,
        company_pf,
        house_rent,
          medic_insur_prem_80d,
          handicap_depend_80dd,
          high_edu_loan_80e,
          paid_rent_80gg,
          handicap_80u,
          raj_gandhi_scheme_80ccg,
          int_on_saving_80tta,
          other_deduct,
          pf_jeevan_suraksha,
          lic,
          deferred_annuity,
          public_pf,
          ulip_uti_lic,
          housing_loan_repay,
          pf_uti_mutual_fund,
          invest_elss,
          child_tution_fee,
          deposit_home_looan_sch,
          five_yrs_bank_deposit,
          other,
          others,
          annuity_pension_plan,
          emp_contri,
          notif_pens_sch,
          int_house_loaan,
          int_loan_const_acco,
      } = emp;
      console.log(allsalary, "Emp DAta");
   
      const monthlydeductpay = parseInt(monthly_pay);
  
  const total_itd = parseInt(house_rent + 
    medic_insur_prem_80d +
    handicap_depend_80dd +
    high_edu_loan_80e +
    paid_rent_80gg +
    handicap_80u +
    raj_gandhi_scheme_80ccg +
    int_on_saving_80tta +
    other_deduct +
    pf_jeevan_suraksha +
    lic +
    deferred_annuity +
    public_pf +
    ulip_uti_lic +
    housing_loan_repay +
    pf_uti_mutual_fund +
    invest_elss +
    child_tution_fee +
    deposit_home_looan_sch +
    five_yrs_bank_deposit +
    other +
    others +
    annuity_pension_plan +
    emp_contri +
    notif_pens_sch +
    int_house_loaan +
    int_loan_const_acco) || 0;
    console.log({total_itd}, "ITD");
    
  const totalExemp10 = parseInt(emp?.hra)+parseInt(emp?.lta)+parseInt(emp?.mp_card);

  const basicpay =parseInt(basic_pay || 0);
  const mhra =parseInt(hra|| 0);
  const mlta =parseInt(lta|| 0);
  const mpf =parseInt(pf|| 0);
  const spAllow =parseInt(spec_allow|| 0);
  const tallow =parseInt(ta|| 0);
  const rallow =parseInt(ra|| 0);
  const healthinsurance =parseInt(health_insurance|| 0);
  const conveyallow =parseInt(convey_allow|| 0);
  const anualbonus = parseInt(yearly_bonus|| 0);
  const adhocEarn = parseInt(adhoc_earning|| 0);
  const mealplus = parseInt(mp_card|| 0);
  const adhoc_dedt = parseInt(adhoc_deduct|| 0);
  const emppf = parseInt(emp_pf|| 0);
  const proftax = parseInt(prof_tax || 0);
  const mtds = parseInt(tds || 0);
  const cpf = parseInt(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 netSalary = grossSal - monthlyDeduct;
        console.log(grossSal, "grossSal");

        const calculateMonthsDifference = ({ startDate, endDate }:any) => {
          let months = (endDate.getFullYear() - startDate.getFullYear()) * 12;
          months -= startDate.getMonth();
          months += endDate.getMonth() + 1;
          return months;
      };
      const empp = { join_date: '2023-01-15' }; // Replace with your employee data
      const joinDateComponents = emp.join_date.split('-');
      const joinYear = parseInt(joinDateComponents[0]);
      const joinMonth = parseInt(joinDateComponents[1]);
      const joinDay = parseInt(joinDateComponents[2]);
      const currentYear = new Date().getFullYear();
      const currentMonth = new Date().getMonth() + 1; // Adding 1 because getMonth() returns 0-based index
      const currentFinancialYearStartDate = new Date(`${currentYear}-04-01`);
      const currentFinancialYearEndDate = new Date(`${currentYear + 1}-03-31`);
      let endDate;
      if (joinYear === currentYear && joinMonth >= 4) {
          endDate = currentFinancialYearEndDate;
      } else {
          endDate = new Date(joinYear + 1, joinMonth - 1, joinDay); // End of next financial year
      }
      const startDate = new Date(joinYear, joinMonth - 1, joinDay); // Month is 0-based
      
      const month = calculateMonthsDifference({ startDate, endDate });
      console.log('Months Difference:', month);
      
        const mpay = grossSal;
        const grossSalary = mpay * month;
        console.log(grossSalary, "Total grossSalary");
        // const totalExempU10 = totalExemp10 * month;
        // console.log(totalExempU10, "Total totalExempU10");
        const grossAfterExemp = grossSalary;
        console.log(grossAfterExemp, "Total grossAfterExemp");
        const standardDeduct = 50000;
        const ptax = parseInt(emp.prof_tax) * month;
        console.log(ptax, "Total ptax");
        const totalDeduct16 = ptax  + standardDeduct;
        console.log(totalDeduct16, "Total totaldeduct16");
        const incomeFromSalary = Math.abs(grossAfterExemp) - totalDeduct16;
        const grossTotalIncome =    Math.abs(incomeFromSalary);
        console.log(grossTotalIncome, "Total grossTotalIncome");
        // let empTotalItd=0;
        // data.forEach((item:any) => {
        //   const empTotalItd = item.total_itd;
        //   console.log(empTotalItd, "Done");
        // });
        const TaxAmount =    grossTotalIncome - total_itd;

        
const netTaxAmount= Math.abs(TaxAmount);
console.log(netTaxAmount, "Total netTaxAmount");
        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 taxAfterRebate = 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 = taxAfterRebate + surchargeTaxRate;
  const cessTax = TaxPlusSurcharge*0.04
  const taxpay = cessTax+taxAfterRebate
  const monthTDS = taxpay/month;

      const ctcAll = mpay * 12;
      console.log('ddd',ctcAll);
      return {
        emp_id,
        tds:monthTDS,
      };
    });
  console.log({ transformedPayroll }, "all tds data");
  const handleGenerateSalary = async (e: any) => {
    try {
      e.preventDefault();
      setGenerated(false);
      const response: any = await axios.put(`/api/users/bulktdscalc`, {
        transformedPayroll,
      });
      console.log("response: ", response.data);
      setGenerated(true);
      toast.success("TDS genrated successfully");
    } catch (error: any) {
      setGenerated(false);
      toast.error(error.response.data.results);
      console.log(error, "fetch payroll error");
    }
  };
  useEffect(() => {
    fetchEmp();
  }, []);

  console.log({ allsalary, leave, attendance });
  return (
    <>
   
                <Form>
                <InputGroup>
                {/* <DateInputWrapper>
                    <DatePicker
                      className="form-control form-control-sm rounded-0"
                      name="attendance_date"
                      dateFormat="yyyy-MM-dd"
                      selected={salarydate}
                      onChange={(salarydate: any) => setMonthSalaryDate(salarydate)}
                      filterDate={(date) =>
                        date.getDay() != 6 && date.getDay() != 0
                      }
                    />
                  </DateInputWrapper> */}
        <Button
                  variant="danger"
                  size="sm"
                  className="me-2"
                  type="submit"
                  id="button-addon2"
                  onClick={handleGenerateSalary}
                >
                  Salary TDS Generate
                  <FontAwesomeIcon
                    icon={Icons.faFileInvoiceDollar}
                    className="ms-1"
                  />
                </Button>
      </InputGroup>
                
                </Form>
          
    </>
  );
};

export default BulkTDSCalc;
