import axios from "axios";
import { useState } from "react";
import {
  Button,
  Card,
  Col,
  Container,
  Form,
  Row,
  Stack,
} from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as Icons from "@fortawesome/free-solid-svg-icons";
import Link from "next/link";
import { toast } from "react-toastify";

const UploadLeave = () => {
  const [file, setFile] = useState("");
  const [isleave, setIsLeave] = useState(false);

  const handleFile = (event: any) => {
    setFile(event.target.files[0]);
    console.log(event.target.files[0], "new file");
  };
  const handleLeaveUpload = async (event: React.FormEvent<HTMLFormElement>) => {
    try {
      event.preventDefault();
      const data = new FormData();
      data.append("leave_file", file);
      setIsLeave(false);

      const response = await axios.post(`/api/upload/uploadleave`, data, {
        headers: { "content-type": "multipart/form-data" },
      });
      console.log(response, "upload response");
      setIsLeave(true);
      toast.success("Leave Uploaded Successfully");
    } catch (error: any) {
    setIsLeave(false);
      toast.error(error.response.data.results);
      console.log(error, "Error Fetching Upload  Data");
    }
  };
  return (
    <>
      <Col>
        <Card className="my-2 docCard">
          <Card.Header className="text-white">
            <b className="text-start">Leave Upload</b>
            <Link
              href="/leave_template.csv"
              className="btn btn-light btn-sm ms-2 "
              style={{ float: "right" }}
            >
              Download Template
              <FontAwesomeIcon icon={Icons.faFileArrowDown} className="ms-1" />
            </Link>
          </Card.Header>
          <Card.Body>
            <Form onSubmit={handleLeaveUpload} encType="multipart/form-data">
              <Row className="mb-3">
                <Form.Group className="mb-3" as={Col} controlId="formGridFile">
                  <Form.Label>File</Form.Label>
                  <Stack direction="horizontal" gap={3}>
                    <Form.Control
                      className="me-auto"
                      type="file"
                      name="leave_file"
                      placeholder="Add your item here..."
                      onChange={handleFile}
                      // multiple
                    />
                    <Button variant="secondary" type="submit">
                      Upload
                    </Button>
                  </Stack>
                </Form.Group>
              </Row>
            </Form>
          </Card.Body>
        </Card>
      </Col>
    </>
  );
};

export default UploadLeave;
