import axios from "axios";
import { useState } from "react";
import { Button, Card, Col, Container, Form, Row } from "react-bootstrap";
import PayrollGenerateCard from "./PayrollGenerateCard";
import EmpIDFetch from "./EmpIDFetch";

const EmpPayrollFetch = ({ setGenerated }: any) => {
  const [emp_id, setEmpId] = useState("");
  const [daycount, setDayCount] = useState({});
  const [payroll, setPayroll] = useState({});
  const [empfetch, setEmpFetch] = useState(false);
  const [mdays, setWorkDays] = useState<any>([]);

  const handleSubmit = async (event: { preventDefault: () => void }) => {
    try {
      event.preventDefault();
      setEmpFetch(false);
      const res = axios.all([
        axios.post(`/api/user/get_days?&emp_id=${emp_id}`).then((res) => {
          setDayCount(res.data);
          setEmpId(emp_id);
          console.log(res.data, "Days count");
        }),
        axios.get(`/api/user/work_days`).then((res) => {
          setWorkDays(res.data.results);
          console.log(res.data.reults, "Month workdays details");
        }),
        axios.get(`/api/users/emp_payroll?&emp_id=${emp_id}`).then((res) => {
          setPayroll(res.data);
          console.log(res.data, "Payroll details");
        }),
      ]);
      setEmpFetch(true);
      const clean = () => setEmpId("");
      clean();
    } catch (err) {
      setEmpFetch(false);
      console.log(empfetch);
    }
  };
  console.log({ payroll });

  return (
    <>
      <Container>
        <Row>
          <Col sm={12} md={12} lg={12}>
            <Card className="mb-3">
              <Card.Body>
                <Form onSubmit={handleSubmit}>
                  <Row className="mb-3">
                    <Form.Group
                      as={Col}
                      sm={12}
                      md={12}
                      lg={4}
                      controlId="formGridEID"
                    >
                      <Form.Label>Emp.ID</Form.Label>
                      <Form.Select
                        name="emp_id"
                        placeholder="Enter Employee ID"
                        onChange={(e) => setEmpId(e.target.value)}
                      >
                        <option>Select Employee</option>
                        <EmpIDFetch/>
                      </Form.Select>
                    </Form.Group>
                  </Row>
                  <Button variant="primary" size="sm" type="submit">
                    Fetch Details
                  </Button>
                </Form>
              </Card.Body>
            </Card>
          </Col>
        </Row>
      </Container>
      <PayrollGenerateCard
        setGenerated={setGenerated}
        payroll={payroll}
        daycount={daycount}
        emp_id={emp_id}
        empfetch={empfetch}
        mdays={mdays}
      />
    </>
  );
};

export default EmpPayrollFetch;
