import axios from "axios";
import { useEffect, useState } from "react";
import { Button, Card, Col, Container, Form, Row } from "react-bootstrap";
import DatePicker from "react-datepicker";
import styled from "@emotion/styled";
import { toast } from "react-toastify";
import GetAssets from "./GetAssets";
import CityComp from "./CityComp";
import AssignManagerComponent from "./AssignManagerComponent";

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 AssetsReturnForm = ({setIsAssetsReturn}:any) => {
  const [assets, setAssetsType] = useState("");
  const [reqapprover, setReqApprover] = useState("");
  const [receivelocation, setLocation] = useState("");
  const [returndate, setReturnDate] = useState(new Date());
  const [emp, setEmp] = useState<any>([]);
  const [assetsreq, setAssetsReq] = useState<any>([]);
  const [description1,setDescription]=useState("")

  const handleNeededDate = (e: any) => {
    setReturnDate(e.target.value);
  };
  const handleAssetsReq = async (
    event: React.FormEvent<HTMLFormElement>
  ) => {
    try {
      event.preventDefault();
      const data = new FormData();
      const empData = JSON.parse(localStorage.getItem("session") || "");
      let assets_type = assets;
      let return_date = returndate.toISOString().substring(0, 10);
      let location = receivelocation;
      let request_approver = reqapprover;
      let description=description1;
      setIsAssetsReturn(false);
      const response: any = await axios.post(
        `/api/user/return_assets_req?&assets_type=${assets_type}&return_date=${return_date}&location=${location}&request_approver=${request_approver}&emp_id=${empData.emp_id}&description=${description}`,
        data,
        {
          headers: { "content-type": "multipart/form-data" },
        }
      );
      setIsAssetsReturn(true);
      toast.success("Assets Return Submitted Successfully");
      console.log("response", response.data);
    } catch (error: any) {
      setIsAssetsReturn(true);
      toast.error(error.response.data.results);
      console.log(error);
    }
  };

  useEffect(() => {
    const fetchEmp = async () => {
      try {
        const empData = JSON.parse(localStorage.getItem("session") || "");

        const res = axios.all([
            axios.post(`/api/user/emp_profile`, { empData }).then((response) => {
              setEmp(response.data.results[0]);
              console.log(response.data, "Emp Data");
            }),
            axios.get(`/api/user/return_assets_req?&emp_id=${empData.emp_id}`).then((response) => {
              setAssetsReq(response.data.results[0]);
              console.log("Assets Data", response);
            }),
          ]);
      } catch (error) {
        console.log(error, "Error Fetching Assets Data");
      }
    };
    fetchEmp();
  }, []);
  console.log({ emp });
  return (
    <>
      <Container>
        <Row>
          <Col>
         
            <Card>
              <Card.Body>
                <Form
                  onSubmit={handleAssetsReq}
                  encType="multipart/form-data"
                >
                  <Row className="align-items-center mb-3">
                    <Col sm={4} className="mb-3">
                      <Form.Label htmlFor="inlineFormInputEID">
                        Employee ID
                      </Form.Label>
                      <Form.Control
                        type="text"
                        id="inlineFormInputEID"
                        name="emp_id"
                        placeholder=""
                        required
                        defaultValue={emp[0]?.emp_id}
                        disabled
                      />
                    </Col>
                    <Col sm={4} className="mb-3">
                      <Form.Label htmlFor="inlineFormInputAssets">
                        Assets Request
                      </Form.Label>
                      <Form.Select
                        name="assets_type"
                        required
                        onChange={(e) => {
                          setAssetsType(e.target.value);
                        }}
                      >
                         <option>Select Assets</option>
                       <GetAssets/>
                      </Form.Select>
                    </Col>
                   
                    <Col sm={4} className="mb-3">
                      <Form.Label htmlFor="inlineFormInputDCD">
                        Return Date
                      </Form.Label>
                      <DateInputWrapper>
                        <DatePicker
                          className="form-control"
                          name="return_date"
                          dateFormat="yyyy-MM-dd"
                          selected={returndate}
                          onChange={(returndate: any) => setReturnDate(returndate)}
                          showYearDropdown
                          scrollableMonthYearDropdown
                          required
                          minDate={new Date()}
                        />
                      </DateInputWrapper>
                    </Col>

                    <Col sm={4} className="mb-3">
                      <Form.Label htmlFor="inlineFormInputLocation">
                        Location
                      </Form.Label>
                      <Form.Select
                        name="location"
                        required
                        id="inlineFormInputLocation"
                        placeholder="Enter Location"
                        onChange={(e) => setLocation(e.target.value)}
                      >
                        <CityComp/>
                      </Form.Select>
                    </Col>
                    <Col sm={4} className="mb-3">
                      <Form.Label htmlFor="inlineFormInputEID">
                        Description
                      </Form.Label>
                      <Form.Control as="textarea"
                      style={{ height: '30px' }}
                        type="text"
                        id="inlineFormInputEID"
                        name="description"
                        placeholder=""
                        required
                        onChange={(e)=>setDescription(e.target.value)}
                      />
                    </Col>
                    <Col sm={4} className="mb-3">
                      <Form.Label htmlFor="inlineFormInputApproval">
                        Approving Authority
                      </Form.Label>
                      <Form.Select
                        name="request_approver"
                        required
                        onChange={(e) => setReqApprover(e.target.value)}
                      >
                        <option>Select Approving Authority</option>
                        <AssignManagerComponent />
                      </Form.Select>
                    </Col>
                    
                  </Row>
                  <Row className="align-items-center mb-3">
                    <Col xs="auto" className="my-1">
                      <Button type="submit">Submit</Button>
                    </Col>
                  </Row>
                </Form>
              </Card.Body>
            </Card>
          </Col>
        </Row>
      </Container>
    </>
  );
};

export default AssetsReturnForm;
