import axios from "axios";
import { useEffect, useState } from "react";
import { Button, Card, Col, Form, Row } from "react-bootstrap";
import { toast } from "react-toastify";

const SalarySlipUpdate = ({ setSalaryUpdated, emp }: any) => {
    
      const[empid, setEmpID] = useState("");	
      const[salid, setSalaryID] = useState("");	
      const[workdays,setWorkDaysPresent] = useState("");	
      const[mlop, setLop] = useState("");	
      const[monthlypay, setMonthlyPay] = useState("");	
      const[basicpay, setBasicPay] = useState("");	
      const[proftax, setProfTax] = useState("");	
      const[mhra, setHRA] = useState("");	
      const[mlta, setLTA] = useState("");	
      const[healthinsurance, setHealthInsur] = useState("");	
      const[loanamount, setLoanAmount] = useState("");	
      const[specallow, setSpecAllow] = useState("");	
      const[mpf, setPF] = useState("");	
      const[emppf, setEmpPF] = useState("");	
      const[companypf, setCompPF] = useState("");	
      const[yearlybonus,setYrlyBonus] = useState("");	
      const[uannumber, setUAN] = useState("");	
      const[pfnumber, setPFNum] = useState("");	
      const[esinumber, setESI] = useState("");	
      const[pannumber, setPanNum] = useState("");	
      const[bankaccnumber, setBankAC] = useState("");	
      const[bankifsc,setBankIFSC] = useState("");	
      const[mra, setRA] = useState("");	
      const[mpcard, setMP] = useState("");	
      const[mta, setTA] = useState("");	
      const[conveyallow, setCA] = useState("");	
      const[mtds, setTDS] = useState("");	
      const[netpay, setNetPay] = useState("");	
      const[mgratuity, setGratuity] = useState("");	
      const[grosssal, setGrossSalary] = useState("");	
      const[workdaysalary, setWorkDaySalary] = useState("");	
      const[totaldeduction, setTotalDeduct] = useState("");	
      const[adhocearning, setAdhocEarn] = useState("");	
      const[adhocdeduct, setAdhocDeduct] = useState("");
      const [itd, setITD]=useState<any>([]);

  useEffect(() => {
    const fetchEmp = () => {
        setEmpID(emp.emp_id)
        setSalaryID(emp.salary_id);	
        setWorkDaysPresent(emp.work_days);
        setLop(emp.lop);	
        setMonthlyPay(emp.monthly_pay);	
        setBasicPay(emp.basic_pay);	
        setProfTax(emp.prof_tax);	
        setHRA(emp.hra);	
        setLTA(emp.lta);
        setHealthInsur(emp.health_insurance);	
        setLoanAmount(emp.loan_amount);	
        setSpecAllow(emp.spec_allow);	
        setPF(emp.pf);	
        setEmpPF(emp.emp_pf);	
        setCompPF(emp.company_pf);	
        setYrlyBonus(emp.yearly_bonus);	
        setUAN(emp.uan_number);	
        setPFNum(emp.pf_number);	
        setESI(emp.esi_number);	
        setPanNum(emp.pan_number);	
        setBankAC(emp.bank_acc_number);	
        setBankIFSC(emp.bank_ifsc);	
        setRA(emp.ra);	
        setMP(emp.mp_card);	
        setTA(emp.ta);	
        setCA(emp.convey_allow);	
        setTDS(emp.tds)
        setNetPay(emp.net_pay)	
        setGratuity(emp.gratuity)	
        setGrossSalary(emp.gross_sal)	
        setWorkDaySalary(emp.work_day_salary)	
        setTotalDeduct(emp.total_deduction)
        setAdhocEarn(emp.adhoc_earning)	
        setAdhocDeduct(emp.adhoc_deduct)
    };
    fetchEmp();
  },[]);

  const handleUpdatePayroll = async (
    event: React.FormEvent<HTMLFormElement>
  ) => {
    try {
      event.preventDefault();
      const data = new FormData(event.currentTarget);
      let salary_id = salid;
      let work_days = workdays;
      let monthly_pay = monthlypay;
      let basic_pay = basicpay;
      let hra = mhra;
      let lop = mlop;
      let lta = mlta;
      let prof_tax = proftax;
      let loan_amount = loanamount;
      let health_insurance = healthinsurance;
      let company_pf = companypf;
      let emp_pf = emppf;
      let pf = mpf;
      let yearly_bonus = yearlybonus;
      let uan_number = uannumber;
      let pf_number = pfnumber;
      let esi_number = esinumber;
      let pan_number = pannumber;
      let bank_acc_number = bankaccnumber;
      let bank_ifsc = bankifsc;
      let ra = mra;
      let mp_card = mpcard;
      let ta = mta;
      let convey_allow = conveyallow;
      let tds = mtds;
      let gross_sal= grosssal;
      let gratuity = mgratuity;
      let net_pay = netpay;
      let adhoc_earning = adhocearning;
      let adhoc_deduct = adhocdeduct;
      let total_deduction = totaldeduction;
      let spec_allow = specallow;
      let work_day_salary = workdaysalary;


      setSalaryUpdated(false);
      const response: any = await axios.put(
        `/api/user/salary_edit?&salary_id=${salary_id}&work_days=${work_days}&basic_pay=${basic_pay}&hra=${hra}&lop=${lop}&lta=${lta}&monthly_pay=${monthly_pay}&prof_tax=${prof_tax}&loan_amount=${loan_amount}&health_insurance=${health_insurance}&company_pf=${company_pf}&emp_pf=${emp_pf}&pf=${pf}&yearly_bonus=${yearly_bonus}&uan_number=${uan_number}&pf_number=${pf_number}&esi_number=${esi_number}&pan_number=${pan_number}&bank_acc_number=${bank_acc_number}&bank_ifsc=${bank_ifsc}&ra=${ra}&mp_card=${mp_card}&ta=${ta}&convey_allow=${convey_allow}&tds=${tds}&gross_sal=${gross_sal}&gratuity=${gratuity}&net_pay=${net_pay}&total_deduction=${total_deduction}&spec_allow=${spec_allow}&adhoc_earning=${adhoc_earning}&adhoc_deduct=${adhoc_deduct}&work_day_salary=${work_day_salary}`
      );
      console.log("response: ", response.data);
      setSalaryUpdated(true);
      toast.success("Salary updated successfully")
    } catch (error:any) {
      setSalaryUpdated(false);
      console.log(error);
      toast.error(error.response.data.results);
    }
  };

  useEffect(() => {
    const  fetchPayroll = async () =>{
      try {
        let emp_id = emp?.emp_id;
        console.log(emp_id, "emp");
        const response = await axios.get(`/api/user/itd_old_regime_fetch?&emp_id=${emp_id}`);
        setITD(response.data.results[0]);
        console.log(response.data.results[0], "ITD");
  
      } catch (error) {
        console.log(error, "Error Fetching Salary Data");
      }
    };
    fetchPayroll();
  }, []);

  // let total_inctax= parseInt(
  //   itd[0]?.house_rent + 
  //   itd[0]?.medic_insur_prem_80d +
  //   itd[0]?.handicap_depend_80dd +
  //   itd[0]?.high_edu_loan_80e +
  //   itd[0]?.paid_rent_80gg +
  //   itd[0]?.handicap_80u +
  //   itd[0]?.raj_gandhi_scheme_80ccg +
  //   itd[0]?.int_on_saving_80tta +
  //   itd[0]?.other_deduct +
  //   itd[0]?.pf_jeevan_suraksha +
  //   itd[0]?.lic +
  //   itd[0]?.deferred_annuity +
  //   itd[0]?.public_pf +
  //   itd[0]?.ulip_uti_lic +
  //   itd[0]?.housing_loan_repay +
  //   itd[0]?.pf_uti_mutual_fund +
  //   itd[0]?.invest_elss +
  //   itd[0]?.child_tution_fee +
  //   itd[0]?.deposit_home_looan_sch +
  //   itd[0]?.five_yrs_bank_deposit +
  //   itd[0]?.other +
  //   itd[0]?.others +
  //   itd[0]?.annuity_pension_plan +
  //   itd[0]?.emp_contri +
  //   itd[0]?.notif_pens_sch +
  //   itd[0]?.int_house_loaan +
  //   itd[0]?.int_loan_const_acco);
  // console.log({total_inctax}, "ITax");

  // const mpay =parseFloat(monthlypay);
  // const tds = (mpay:any = 0) => {
  //   console.log(typeof mpay,'Month Salary');
    
  //   const grossSalary = mpay * 12;
  //   const standDeduct = grossSalary - 50000;
  //   const annualSalary = standDeduct - total_inctax;
  //   let mtds = 0;
           
  //   if (annualSalary <= 250000) {
  //     mtds = (annualSalary * 0) / 100;
  //   } else if (annualSalary > 250000 && annualSalary <= 500000) {
  //     mtds = (annualSalary * 5) / 100;
  //   } else if (annualSalary > 500000 && annualSalary <= 1000000) {
  //     mtds = (annualSalary * 20) / 100;
  //   } else {
  //     mtds = (annualSalary * 30) / 100;
  //   }
  
  //   return mtds / 12;
  // };
  // const vtds = tds(mpay);
// console.log( Math.abs(vtds), "jjcjgcjc");
  const ctc = parseInt(monthlypay) * 12;
  
  return (
    <>
      <Card className="rounded-0">
        <Card.Body>
          <Form onSubmit={handleUpdatePayroll}>
            <Row className="mb-3">
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridEmpID"
            >
                <Form.Label>Employee ID</Form.Label>
                <Form.Control
                  type="text"
                  placeholder=""
                  name="emp_id"
                  defaultValue={empid}
                />
              </Form.Group>

             
              <Form.Group 
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridUANNum"
              >
                <Form.Label>UAN Number</Form.Label>
                <Form.Control
                  type="text"
                  placeholder=""
                  name="uan_number"
                  onChange={(e) => setUAN(e.target.value)}
                  defaultValue={uannumber}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridPF"
              >
                <Form.Label>PF Number</Form.Label>
                <Form.Control
                  type="text"
                  placeholder=""
                  name="pf_number"
                  onChange={(e) => setPF(e.target.value)}
                  defaultValue={pfnumber}
                />
              </Form.Group>

           
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridESINum"
              >
                <Form.Label>ESI Number</Form.Label>
                <Form.Control
                  type="text"
                  placeholder=""
                  name="esi_number"
                  onChange={(e) => setESI(e.target.value)}
                  defaultValue={esinumber}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridPANNum"
              >
                <Form.Label>PAN Number</Form.Label>
                <Form.Control
                  type="text"
                  placeholder=""
                  name="pan_number"
                  onChange={(e) => setPanNum(e.target.value)}
                  defaultValue={pannumber}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridBankACNum"
              >
                <Form.Label>Bank A/C Number</Form.Label>
                <Form.Control
                  type="text"
                  placeholder=""
                  name="bank_acc_number"
                  onChange={(e) => setBankAC(e.target.value)}
                  defaultValue={bankaccnumber}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridBankIFSC"
              >
                <Form.Label>IFSC</Form.Label>
                <Form.Control
                  type="text"
                  placeholder=""
                  name="bank_ifsc"
                  onChange={(e) => setBankIFSC(e.target.value)}
                  defaultValue={bankifsc}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridWD"
              >
                <Form.Label> Work Days</Form.Label>
                <Form.Control
                  type="text"
                  name="work_days"
                  placeholder="Enter Work Days"
                  onChange={(e) => setWorkDaysPresent(e.target.value)}
                  defaultValue={workdays}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridLOP"
              >
                <Form.Label> LOP</Form.Label>
                <Form.Control
                  type="text"
                  name="lop"
                  placeholder="Enter LOP"
                  onChange={(e) => setLop(e.target.value)}
                  defaultValue={mlop}
                />
              </Form.Group>
           
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridMS"
              >
                <Form.Label>Monthly Salary</Form.Label>
                <Form.Control
                  type="text"
                  name="monthly_pay"
                  placeholder="Enter Monthly Salary"
                  onChange={(e) => setMonthlyPay(e.target.value)}
                  defaultValue={monthlypay}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridBasicPay"
              >
                <Form.Label>Basic Pay</Form.Label>
                <Form.Control
                  type="text"
                  name="basic_pay"
                  placeholder="Enter Basic Salary"
                  onChange={(e) => setBasicPay(e.target.value)}
                  defaultValue={basicpay}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridHRA"
              >
                <Form.Label> HRA</Form.Label>
                <Form.Control
                  type="text"
                  name="hra"
                  placeholder="Enter HRA"
                  onChange={(e) => setHRA(e.target.value)}
                  defaultValue={mhra}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridLTA"
              >
                <Form.Label> LTA</Form.Label>
                <Form.Control
                  type="text"
                  name="lta"
                  placeholder="Enter LTA"
                  onChange={(e) => setLTA(e.target.value)}
                  defaultValue={mlta}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridECPF"
              >
                <Form.Label>Provident Fund(Employee)</Form.Label>
                <Form.Control
                  type="text"
                  name="emp_pf"
                  placeholder=""
                  onChange={(e) => setEmpPF(e.target.value)}
                  defaultValue={emppf}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridCCPF"
              >
                <Form.Label>Provident Fund(Employer)</Form.Label>
                <Form.Control
                  type="text"
                  name="company_pf"
                  placeholder=""
                  onChange={(e) => setCompPF(e.target.value)}
                  defaultValue={companypf}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridPF"
              >
                <Form.Label>Provident Fund</Form.Label>
                <Form.Control
                  type="text"
                  name="pf"
                  placeholder=""
                  onChange={(e) => setPF(e.target.value)}
                  defaultValue={mpf}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridPT"
              >
                <Form.Label>Professional Tax</Form.Label>
                <Form.Control
                  type="text"
                  name="prof_tax"
                  placeholder=""
                  onChange={(e) => setProfTax(e.target.value)}
                  defaultValue={proftax}
                />
              </Form.Group>
          
            <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridNetPay"
              >
                <Form.Label>Net Pay</Form.Label>
                <Form.Control
                  type="text"
                  name="net_pay"
                  placeholder=""
                  onChange={(e) => setNetPay(e.target.value)}
                  defaultValue={netpay}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridEID"
              >
                <Form.Label>Health Insurance</Form.Label>
                <Form.Control
                  type="text"
                  name="health_insurance"
                  placeholder=""
                  onChange={(e) => setHealthInsur(e.target.value)}
                  defaultValue={healthinsurance}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridAR"
              >
                <Form.Label>Loan Amount Deduction</Form.Label>
                <Form.Control
                  type="text"
                  name="loan_amount"
                  placeholder=""
                  onChange={(e) => setLoanAmount(e.target.value)}
                  defaultValue={loanamount}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridAdvFestBonus"
              >
                <Form.Label> Variable Pay/Bonus(Q/H/A)</Form.Label>
                <Form.Control
                  type="text"
                  name="yearly_bonus"
                  placeholder=""
                  onChange={(e) => setYrlyBonus(e.target.value)}
                  defaultValue={yearlybonus}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridRA"
              >
                <Form.Label>Relocation Allowances</Form.Label>
                <Form.Control
                  type="text"
                  name="ra"
                  placeholder=""
                  onChange={(e) => setRA(e.target.value)}
                  defaultValue={mra}
                />
              </Form.Group>
           
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formMPCard"
              >
                <Form.Label>MealPlus Card</Form.Label>
                <Form.Control
                  type="text"
                  name="mp_card"
                  placeholder=""
                  onChange={(e) => setMP(e.target.value)}
                  defaultValue={mpcard}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridTA"
              >
                <Form.Label>Telephone Allowances</Form.Label>
                <Form.Control
                  type="text"
                  name="ta"
                  placeholder=""
                  onChange={(e) => setTA(e.target.value)}
                  defaultValue={mta}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridSA"
              >
                <Form.Label>Special Allowance</Form.Label>
                <Form.Control
                  type="text"
                  name="spec_allow"
                  placeholder=""
                  onChange={(e) => setSpecAllow(e.target.value)}
                  defaultValue={specallow}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridCA"
              >
                <Form.Label>Conveyance Allowance</Form.Label>
                <Form.Control
                  type="text"
                  name="convey_allow"
                  placeholder=""
                  onChange={(e) => setCA(e.target.value)}
                  defaultValue={conveyallow}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridTDS"
              >
                <Form.Label>TDS</Form.Label>
                <Form.Control
                  type="text"
                  name="tds"
                  placeholder=""
                  value={mtds}
                  onChange={(e) => setTDS(e.target.value)}
                />
              </Form.Group> 
          
            <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridGratuity"
              >
                <Form.Label>Gratuity</Form.Label>
                <Form.Control
                  type="text"
                  name="gratuity"
                  placeholder=""
                  onChange={(e) => setGratuity(e.target.value)}
                  defaultValue={mgratuity}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridGross"
              >
                <Form.Label>Gross Salary</Form.Label>
                <Form.Control
                  type="text"
                  name="gross_sal"
                  placeholder=""
                  onChange={(e) => setGrossSalary(e.target.value)}
                  defaultValue={grosssal}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridAdhoc"
              >
                <Form.Label>Adhoc Earning</Form.Label>
                <Form.Control
                  type="text"
                  name="adhoc_earning"
                  placeholder=""
                  onChange={(e) => setAdhocEarn(e.target.value)}
                  defaultValue={adhocearning}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridAdhoc"
              >
                <Form.Label>Adhoc Deduction</Form.Label>
                <Form.Control
                  type="text"
                  name="adhoc_deduct"
                  placeholder=""
                  onChange={(e) => setAdhocDeduct(e.target.value)}
                  defaultValue={adhocdeduct}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridTD"
              >
                <Form.Label>Total Deduction</Form.Label>
                <Form.Control
                  type="text"
                  name="total_deduction"
                  placeholder=""
                  onChange={(e) => setTotalDeduct(e.target.value)}
                  defaultValue={totaldeduction}
                />
              </Form.Group>
              <Form.Group
                as={Col}
                sm={12}
                md={12}
                lg={3}
                controlId="formGridWDS"
                style={{display:"none"}}
              >
                <Form.Label> Per Days Earning</Form.Label>
                <Form.Control
                  type="text"
                  name="work_day_salary"
                  placeholder="Enter Work Days"
                  onChange={(e) => setWorkDaySalary(e.target.value)}
                  defaultValue={workdaysalary}
                />
              </Form.Group>
            </Row>
            <Button variant="primary" type="submit">
              Submit
            </Button>
          </Form>
        </Card.Body>
      </Card>
    </>
  );
};

export default SalarySlipUpdate;
