import React, { Component } from "react";
import ContentWrapper from "@/components/Layout/ContentWrapper";
import { Row, Col } from "reactstrap";
import { getPelaporan } from "@/actions/pelaporan";
import { getGraph, getExcel } from "@/actions/graph";
import CaseProgress from "@/components/Penjadwalan/CaseProgress";
import TableLaporan from "@/components/Penjadwalan/TableLaporan";
import { connect } from "react-redux";
import Loader from "@/components/Common/Loader";
import Link from "next/link";
import Button from "reactstrap/lib/Button";
import Router from "next/router";

class Penjadwalan extends Component {
	constructor(props) {
		super(props);
		this.state = {
			pelaporan: {},
			graph: {},
			tahun: new Date().getFullYear(),
		};
	}

	componentDidMount = async () => {
		const { token } = this.props;
		const pelaporan = await getPelaporan(token);
		const graph = await getGraph(this.props.token, { jadwal: true });
		this.setState({ pelaporan, graph });
	};

	nextButton = async () => {
		const tahun = this.state.tahun + 1;
		const graph = await getGraph(this.props.token, { jadwal: true, tahun });
		this.setState({ graph, tahun });
	};

	prevButton = async () => {
		const tahun = this.state.tahun - 1;
		const graph = await getGraph(this.props.token, { jadwal: true, tahun });
		this.setState({ graph, tahun });
	};

	shouldComponentUpdate = (prevProps, prevState) => {
		if (prevState.graph !== this.state.graph) return true;
	};

	excel = () => {
		const url = getExcel(this.props.token, "Laporan", { tahun: this.state.tahun });
		Router.push(url);
	};

	render() {
		const { pelaporan, graph } = this.state;
		return (
			<ContentWrapper>
				<div className="content-heading">
					<div>Penjadwalan Evaluasi</div>
					<div className="ml-auto">
						<Link href="/app/pelaporan">
							<span className="margin-l-5">
								<Button className="btn-header" color="info">
									<h4>&lt; Pelaporan</h4>
								</Button>
							</span>
						</Link>

						<Link href="/app/pemeriksaan">
							<Button className="btn-header" color="info">
								<h4>Pemeriksaan &gt;</h4>
							</Button>
						</Link>
					</div>
				</div>
				<Row>
					<Col lg="4">{graph?.data ? <CaseProgress data={graph.data} nextButton={this.nextButton} prevButton={this.prevButton} tahun={this.state.tahun} excel={this.excel} /> : <Loader />}</Col>
					<Col lg="8">{pelaporan?.data ? <TableLaporan listData={pelaporan.data} to="/app/penjadwalan/todo" linkName="Atur Jadwal" /> : <Loader />}</Col>
				</Row>
			</ContentWrapper>
		);
	}
}

const mapStateToProps = (state) => ({ user: state.user, token: state.token });
export default connect(mapStateToProps)(Penjadwalan);
