import { useEffect, useState } from "react";
import { Button, Card, Col, Container, Form, Row } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as Icons from "@fortawesome/free-solid-svg-icons";
import DatePicker from "react-datepicker";
import styled from "@emotion/styled";
import axios from "axios";
import { toast } from "react-toastify";
import ResignList from "./ResignList";
import AssignManagerComponent from "./AssignManagerComponent";
import { log } from "util";
import EmpList from "../HR/EmpList";
const TitleCardWrapper = styled.div`
  .card {
    background: #bef1b9ed;
    border: 0px;
    box-shadow: 0 0.2rem 0.2rem rgba(0, 0, 0, 0.15) !important;
    .title {
      @media (max-width: 992px) {
        text-align: center;
      }
    }
  }
`;
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;
  }
`;
 function ResignationForm() {
  const[applied, setIsApplied]=useState(false);
  const [emp, setEmp] =useState<any>([]);
  const [approvingAuthority, setApprovingAuthority] = useState('');
  const [resignationDate, setResignationDate] = useState(new Date());
  const [regsubject, setSubject] = useState('');
  const [regreason, setReason] = useState('');
  const [getlocdata, setLocalData]= useState<any>([])
  const [workingData,setWorkingData]=useState(new Date());
  const [empData,setEmpData]=useState<any>()
  // const [dataWork,setDataWork]=useState()
  
  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    try {
      event.preventDefault();
      const empData = JSON.parse(localStorage.getItem("session") || "");
      // console.log(empData)
      const data = new FormData(event.currentTarget);
      let date_of_resign = resignationDate.toISOString().substring(0, 10);
      let subject = regsubject;
      let reason = regreason;
      let approv_auth = approvingAuthority;
      let last_working_day=workingData.toISOString().substring(0, 10);
      setIsApplied(false);
      const response: any = await axios.post(`/api/user/emp_resignation?&date_of_resign=${date_of_resign}&subject=${subject}&reason=${reason}&approv_auth=${approv_auth}&emp_id=${empData.emp_id}&last_working_day=${last_working_day}`);
      console.log("response: ", response.data);
      setIsApplied(true);
      toast.success("Resignation submitted successfully");
    } catch (error: any) {
      setIsApplied(false);
      toast.error(error.response.data.results);
      console.log(error, "error while applying");
    }
  };
  useEffect(() => {
    const fetchEmp = async () => {
      const empData = JSON.parse(localStorage.getItem("session") || "");
      setLocalData(empData);
      console.log(empData);
      
    };
    fetchEmp();
  }, []);
  
  useEffect(() => {
    const fetchEmp = async () => {
      try {
        const response = await axios.post("/api/users");
        setEmpData(response.data.results);
        console.log(response.data.results,"vvvvvvvvvvvv");
        
      } catch (error) {
        console.log(error, "Fetching user data error");
      }
    };
    fetchEmp();
  }, []);
 
  const lastWorkingDay:any = new Date(resignationDate);
  // setWorkingData( lastWorkingDay.setDate(resignationDate.getDate() + 90))

  // const lastWorkingDay1:any = new Date(resignationDate);
  // setDataWork( lastWorkingDay1.setDate(resignationDate.getDate() + 15))

    
  return (
    <>
    <Container>
        <Row>
          
          <Col sm={12} md={12} lg={12}>
            <TitleCardWrapper>
              <Card className="mb-3">
                <Card.Body className="p-1">
                  <Row className="title">
                    <Col lg="1" className="text-center">
                      <Card.Img
                        variant="start"
                        src="https://img.icons8.com/external-flat-wichaiwi/64/external-dismissal-unemployment-flat-wichaiwi.png"
                        width="50px"
                        height="50px"
                        alt=""
                      />
                    </Col>
                    <Col lg="11">
                      <Card.Title className="my-3 text-dark">
                        Resignation Form
                      </Card.Title>
                    </Col>
                  </Row>
                </Card.Body>
              </Card>
            </TitleCardWrapper>
          </Col>
        </Row>
      </Container>
    <Container>
        <Card style={{borderRadius:"0px"}}>
        <Card.Body>
            <Form onSubmit={handleSubmit}>
              
        
      <Row className="mb-3">
      <Form.Group as={Col} lg="6" sm="12" className="mb-3" controlId="formGridEmpId">
          <Form.Label>Emp ID</Form.Label>
          <Form.Control type="text" name="emp_id" placeholder="" defaultValue={getlocdata?.emp_id} disabled/>
        </Form.Group>
      <Form.Group as={Col} lg="6" sm="12" className="mb-3" controlId="formGridAA">
      
                      <Form.Label htmlFor="inlineFormInputApproval">
                        Approving Authority
                      </Form.Label>
                      <Form.Select
                        name="request_approver"
                        required
                        onChange={(e) => setApprovingAuthority(e.target.value)}
                      >
                        <option>Select Approving Authority</option>
                        <AssignManagerComponent />
                      </Form.Select>
                </Form.Group>
        <Form.Group as={Col} lg="6" sm="12" className="mb-3"  controlId="formGridRD">
        <Form.Label>Resignation Date</Form.Label>
        <DateInputWrapper>
                        <DatePicker
                
                          className="form-control"
                          name="date_of_resign"
                          dateFormat="yyyy-MM-dd"
                          selected={resignationDate}
                          onChange={(startdate: any) => setResignationDate(startdate)}
                          showYearDropdown
                          scrollableMonthYearDropdown
                          required={true}
                          minDate={new Date()}
                        />
                      </DateInputWrapper>
      </Form.Group>
        <Form.Group as={Col} lg="6" sm="12" className="mb-3"  controlId="formGridRD">
        <Form.Label>Last Working Day</Form.Label>
        <DateInputWrapper>
          {
            empData?.map((emp:any,i:any)=>{
              if(emp?.emp_id===getlocdata?.emp_id){
                     if(emp.emp_type==="Permanent"){

                       return <DatePicker
                       key={i}
                       className="form-control"
                       name="lastDate"
                       dateFormat="yyyy-MM-dd"
                       selected={lastWorkingDay.setDate(resignationDate.getDate() + 90)}
                       onChange={(startDate: any) => setWorkingData(startDate)}
                     
                       />
                      }else{
                        return <DatePicker
                        key={i}
                       className="form-control"
                       name="lastDate"
                       dateFormat="yyyy-MM-dd"
                       selected={lastWorkingDay.setDate(resignationDate.getDate() + 15)}
                       onChange={(date: any) => setWorkingData(date)}
                     
                       />
                      }
              }
            })
          }
                       
                      </DateInputWrapper>
      </Form.Group>
      
      <Form.Group as={Col} lg="6" sm="12" className="mb-3" controlId="formGridSubject">
          <Form.Label>Subject</Form.Label>
          <Form.Control type="text" name="subject" required placeholder="Enter Subject" onChange={(e)=>setSubject(e.target.value)}/>
        </Form.Group>
      
        <Form.Group as={Col} lg="12" sm="12" className="mb-3" controlId="formGridreson">
          <Form.Label>Reason for Resignation</Form.Label>
          <Form.Control as="textarea" required type="text" name="reason" placeholder="Enter Resignation Reason" onChange={(e)=>setReason(e.target.value)}/>
        </Form.Group>
      
      </Row>
      
      <Button variant="primary" type="submit">
        Submit
      </Button>
    </Form>
         
        </Card.Body>
        </Card>
    </Container>
    <ResignList applied={applied}/>
    </>
  )
}

export default  ResignationForm