import React from "react";
import moment from "moment";
import { SpinnerCircular } from "spinners-react";
import Link from "next/link";

import { signCheckDownloadContractProject, signGetFileContractProject, getFile, } from "../../../actions";

export default class SignedContract extends React.Component
{
	constructor(props)
	{
		super(props);
		this.state = {
			loading: false, 
			url: undefined, 
			error: false, 
			message: undefined, 
		};
	}

	async componentDidMount()
	{
	}

	_handle_downloadFile = () => 
	{
		const { contract } = this.props;

		this.setState({ loading: true, error: false, }, async () => 
		{
			const check_result = await signCheckDownloadContractProject({ contract_number: contract.name });
			if(check_result.status === "success")
			{
				const link_result = await signGetFileContractProject({
					contract_number: contract.name
				});

				await getFile({ id: link_result.url, filename: `ЛК ЭВОЛЮЦИЯ ${ contract.name }.${ link_result.extension }` });
				this.setState({ loading: false, error: false, });	
			}
			else
			{
				this.setState({ loading: false, error: true, message: check_result.message !== undefined && check_result.message !== null ? check_result.message : "Возникла ошибка обработки документа" })
			}
		});
	}

	render()
	{
		const { index, contract, } = this.props;
		const { loading, error, message, } = this.state;

		return (
			<div className="document" key={ index }>
				<div className="icon">
					<span className="extension">PDF</span>
				</div>
				<div className="title">
					<p><Link href={`/contract/${ contract.name }/payments`}>{ contract.name }</Link></p>
					<div className="description">
						<span>{ moment(contract.date).format("DD.MM.YYYY") }</span>
						<span>{ contract.brand_name }</span>
						<span>{ contract.model_name }</span>
					</div>
				</div>
				<div className="actions wide">
					<div className="status">
						<div className="status_icon"></div>
						<span>{ contract.statuscode_name }</span>
					</div>
					{ loading ? (
						<div className="actions actions_with_status">
							<SpinnerCircular style={{ margin: "0px 30px 0px", }} size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
						</div>
					) : (
						<button className="button blue" onClick={ () => this._handle_downloadFile(true) }>Скачать</button>
					) }
				</div>
			</div>
		)
	}
}