import React from "react";
import moment from "moment";

import DateInput from "../../../components/DatePicker";

export default class PenaltiesCalculatorForm extends React.Component 
{
	constructor(props) 
	{
		super(props);
		this.state = {
			selected_date: moment().toDate(),  
			valid_date_start: moment().toDate(), 
			valid_date_end: moment().add(1, "month").toDate(), 
			fines_calculation_disabled: false, 
		};
	}

	componentDidMount() 
	{
	}

	componentDidUpdate(prevProps, prevState) 
	{
	}

	_handle_onFinesDate_start = (date) => 
	{
		const {
			valid_date_start,
			valid_date_end,
		} = this.state;
		const md = moment(date, "DD.MM.YYYY");

		if (md.isValid()) 
		{
			if (date >= valid_date_start && date <= valid_date_end) 
			{
				this.setState({
					selected_date: date,
					fines_calculation_disabled: false,
				});
			} 
			else 
			{
				this.setState({
					selected_date: date,
					fines_calculation_disabled: true,
				});
			}
		} 
		else 
		{
			this.setState({ fines_calculation_disabled: true });
		}
	};

	_handle_onApply = () => 
	{
		const { selected_date } = this.state;

		this.props.onPenalties(moment(selected_date).format("YYYY.MM.DD"));
	}

	render() 
	{
		const {
			selected_date, 
			valid_date_start, 
			valid_date_end, 
			fines_calculation_disabled, 
		} = this.state;

		return (
			<>
				<div className="dropdown_block">
					<div className="block_header">
						<p>Расчёт планируемых пени</p>
					</div>
				</div>
				<div className="block_with_form">
					<p>Введите планируемую дату оплаты просроченной задолженности для расчёта пеней</p>
					<form className="paymentDateForm">
						<div className="form_field">
							<DateInput
								placeholder="Планируемая дата"
								value={ selected_date }
								min={ valid_date_start }
								max={ valid_date_end }
								onChange={ this._handle_onFinesDate_start }
							/>
						</div>
						<button className="button button-blue" disabled={ fines_calculation_disabled } onClick={ this._handle_onApply }>Применить</button>
					</form>
				</div>
			</>
		);
	}
}