import axios from "axios";
import moment from "moment";
import { useEffect, useState } from "react";
import { Button, Card, Col, Container, Form, InputGroup, Row } from "react-bootstrap";
import Link from "next/link";
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";
import BulkTDSCalc from "./BulkTDSCalc";
import SalaryBulkUpload from "./BulkUpload";
import FreezeSalary from "./FreezeSalary";

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 BulkPayroll = ({ setGenerated }: any) => {
  const [allpayroll, setPayroll] = useState<any>([]);
  const [leave, setLeaveCount] = useState<any>([]);
  const [attendance, setAttendanceCount] = useState<any>([]);
  const [payrolldata, setPayrollData] = useState<any>([]);
  const [days, setWorkDays] = useState<any>([ ]);
  const [salarydate, setMonthSalaryDate] = useState(new Date());


  const fetchEmp = async () => {
    try {
      console.log();
      const res = axios.all([
        axios.post(`/api/user/get_count`).then((res) => {
          setPayroll(res.data.results);
          console.log(res.data, "Payroll details");
        }),
        axios.get(`/api/user/work_days`).then((res) => {
          setWorkDays(res.data.results);
          console.log(res.data.results, "Month workdays details 2");
        }),
        axios.get(`/api/user/get_emp_leave`).then((res) => {
          setLeaveCount(res.data.results);
          console.log(res.data, "Leave count");
        }),
        axios.post(`/api/user/get_emp_leave`).then((res) => {
          setAttendanceCount(res.data.results);
          console.log(res.data, "Attendance count");
        }),
        axios.get(`/api/users/emp_payroll`).then((res) => {
          setPayrollData(res.data.results);
          console.log(res.data, "Attendance count");
        }),
      ]);
    } catch (error) {
      console.log(error, "Fetching user data error");
    }
  };

  const transformedPayroll =
    allpayroll &&
    allpayroll.map((emp: any) => {
      const {
        emp_id,
        prof_tax,
        monthly_pay,
        loan_amount,
        health_insurance,
        emp_pf,
        company_pf,
        uan_number,
        pf_number,
        esi_number,
        pan_number,
        bank_acc_number,
        bank_ifsc,
        ra,
        mp_card,
        ta,
        convey_allow,
        tds,
        adhoc_earning,
        adhoc_deduct,
      } = emp;
      const monthGross = parseInt(monthly_pay);
      console.log(salarydate,'llll');
      
      const work_days =
        (days &&
          days.filter((total_work_days: any) => {
            const date = new Date(total_work_days.att_date);
            return total_work_days.emp_id === emp_id && date.getMonth() + 1 === salarydate.getMonth() + 1 ;
          })[0]?.total_work_days) ||
        0;
        console.log(work_days, "days work");
        console.log(days, "days work");
      const day_salary = (monthGross / work_days) * work_days;
      const proftax = parseInt(prof_tax);
      const healthinsurance=parseInt(health_insurance);
      const pf = parseInt(emp_pf) + parseInt(company_pf);
      const emppf = parseInt(emp_pf);  
      const deduction = proftax + healthinsurance + emppf;
      const monthlypay = day_salary;
      const basic_pay = (monthlypay * 40) / 100;
      const hra = (basic_pay * 40) / 100;
      const lta = (basic_pay * 60) / 100;
      const mealplus = parseInt(mp_card);
      const amount = basic_pay + hra + lta + mealplus;
      const spec_allow = monthlypay - amount;
      const cmpf =parseInt(company_pf);
      const adhocdeduct = parseInt(adhoc_deduct);
      const adhoc_earn = parseInt(adhoc_earning);
      const mtds = parseInt(tds);
      const tallow = parseInt(ta);
      const rallow = parseInt(ra);
      const conveyallow=parseInt(convey_allow);
      const total_deduction = emppf + proftax + adhocdeduct + mealplus + mtds;
      console.log(emppf, proftax, adhocdeduct, mealplus, mtds, "td");
      
      const gratuity = Math.round(Math.abs(basic_pay * 0.57));
    
      const leaves =
        (leave &&
          leave.filter((emp_leave: any) => {
            return emp_leave.emp_id == emp_id;
          })[0]?.total_leave) ||
        0;
        // Get the year and month from the current date
        const currentDate = new Date();
         const year = currentDate.getFullYear(); 
         const month = currentDate.getMonth();
         const daysInMonth = new Date(year, month + 1, 0).getDate(); 
       const lop = daysInMonth - work_days; 
      const bonus = parseInt(payrolldata && payrolldata[0]?.yearly_bonus);

      const yrly_bonus = (bonus: number) => {
        if (payrolldata == "March") {
          return bonus;
        } else {
          return 0;
        }
      };
      const anualbonus = yrly_bonus(bonus);
      const gross_sal = basic_pay + hra + lta + spec_allow + tallow + rallow + mealplus + healthinsurance + conveyallow + anualbonus + adhoc_earn;
  //  console.log(basic_pay , hra , lta , pf , spec_allow , tallow , rallow , mealplus , healthinsurance , conveyallow , anualbonus , adhoc_earn, "kkktt");
      const net_pay = Math.round(gross_sal - total_deduction );
      const work_day_salary = net_pay;
      const curr_date = salarydate.toISOString().substring(0, 10);
      // const curr_date = moment(new Date()).format("YYYY-MM-DD");

      return {
        emp_id,
        work_days,
        lop,
        monthly_pay,
        basic_pay,
        prof_tax,
        hra,
        lta,
        health_insurance,
        loan_amount,
        spec_allow,
        pf,
        emp_pf,
        company_pf,
        yearly_bonus: yrly_bonus(bonus),
        uan_number,
        pf_number,
        esi_number,
        pan_number,
        bank_acc_number,
        bank_ifsc,
        ra,
        mp_card,
        ta,
        convey_allow,
        tds,
        net_pay,
        gratuity,
        gross_sal,
        work_day_salary,
        total_deduction,
        // total_salary,
        adhoc_earning,
        adhoc_deduct,
        curr_date,
      };
    });
  console.log({ transformedPayroll });
  const handleGenerateSalary = async (e: any) => {
    try {
      e.preventDefault();
      setGenerated(false);
      const response: any = await axios.post(`/api/users/bulksal`, {
        transformedPayroll,
      });
      console.log("response: ", response.data);
      setGenerated(true);
      toast.success("Bulk payslip genrated successfully");
    } catch (error: any) {
      setGenerated(false);
      toast.error(error.response.data.results);
      console.log(error, "fetch payroll error");
    }
  };
  useEffect(() => {
    fetchEmp();
  }, []);

  console.log({ allpayroll, leave, attendance });
  return (
    <>
      <Container className="my-3 text-end">
        <Row>
          <Col>
            <Card style={{ border: "0px" }}>
              <Card.Body className=" d-flex justify-content-end">
                
                <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}
                >
                  Generate All Salary Slip
                  <FontAwesomeIcon
                    icon={Icons.faFileInvoiceDollar}
                    className="ms-1"
                  />
                </Button>
      </InputGroup>
                
                </Form>
                <BulkTDSCalc/>

                <FreezeSalary/>

                <Link
                  className="btn btn-danger btn-sm"
                  style={{ float: "right" }}
                  href="/salarybulkupload_template.csv"
                >
                  Download Template
                  <FontAwesomeIcon
                    icon={Icons.faFileArrowDown}
                    className="ms-1"
                  />
                </Link>
              </Card.Body>
            </Card>
          </Col>
        </Row>
      </Container>

      <SalaryBulkUpload />
    </>
  );
};

export default BulkPayroll;
