import React, { Component } from 'react'
import { Paper, } from '@material-ui/core';
import AlertSnackbar from '../../library/AlertSnackbar'
import SectionHeader from '../../library/SectionHeader';
import AutocompleteField from '../../library/AutocompleteField';
import CustomButton from '../../library/CustomButton';
import api from '../../api';
import DDLYear from '../../library/Dropdown/DDLYear';
import DDLMonth from '../../library/Dropdown/DDLMonth';
import DDLCompany from '../../library/Dropdown/DDLCompany';
import ContentContainer from '../../library/ContentContainer';
import Constant from '../../library/Constant';
import { downloadFileBlob } from '../../library/Utils';

class ReportHistorical extends Component {
  constructor(props) {
    super(props)
    this.state = {
      showAlert: false,
      alertMessage: '',
      alertSeverity: Constant.ALERT_SEVIRITY.SUCCESS,
      selectedValue: null,
      data: {},
      isLoading: false,

      listReportType: [],
      listPeriodType: [
        { id: 'MTD', name: 'MTD', },
        { id: 'YTD', name: 'YTD', }
      ],

      buttonError: false,
    }
  }

  componentDidMount() {
    this.getData()
  }

  setLoading = (isLoading) => {
    this.setState({ isLoading })
  }

  getData() {
    this.setLoading(true)
    api.create().getHistoricalReport().then((res) => {
      const list = res.data?.data || []
      const arr = []
      list.forEach(item => {
        arr.push({ id: item.report_type_id, name: item.report_name })
      })
      this.setState({ listReportType: arr }, () => {
        this.setDefaultData()
      })
    })
  }

  setDefaultData = () => {
    const defaultReportType = this.state.listReportType[0] || null
    const defaultPeriodType = this.state.listPeriodType[0] || null
    this.setState({
      data: {
        ...this.state.data,
        report_id: defaultReportType,
        performance_period: defaultPeriodType,
      }
    }, () => {
      this.setLoading(false)
    })
  }

  handleChangeDropdown = (newValue, name) => {
    this.setState(prevState => ({
      data: {
        ...prevState.data,
        [name]: newValue,
      }
    }))
  }

  handleChangeMultiDropdown = (newValues, name) => {
    this.setState(prevState => ({
      data: {
        ...prevState.data,
        [name]: newValues,
      }
    }))
  }

  showAlert = (message, severity = 'success') => {
    this.setState({
      showAlert: true,
      alertMessage: message,
      alertSeverity: severity,
    });
  };

  closeAlert = () => {
    this.setState({ showAlert: false });
  };

  handleDownload = async () => {
    try {

      this.setLoading(true)
      const payload = {
        report_id: this.state.data.report_id?.id,
        company_id: this.state.data.company_id?.map(c => c.id).join(','),
        performance_period: this.state.data.performance_period?.id,
        year: this.state.data.year?.id,
        month: this.state.data.month?.id,
      }
      api.create('DOWNLOAD').exportReportHistorial(payload).then(async (res) => {
        this.setLoading(false)
        const blob = res.data

        if (blob && blob.size > 0) {
          downloadFileBlob('Historical.xlsx', blob)
        }

        this.showAlert('Download Berhasil', 'success');
      })

    } catch (error) {
      // Show error alert
      this.showAlert(`Gagal menyimpan: ${error.message}`, 'error');
    }
  };

  render() {
    const { data, showAlert, alertMessage, alertSeverity, listReportType, listPeriodType, isLoading } = this.state;
    const contentStyle = { display: 'flex', marginTop: 10, gap: '20px' };

    return (
      <ContentContainer isLoading={isLoading} title="Report Historical">
        <div style={{ padding: 20 }}>
          <Paper style={{ paddingTop: 10, paddingBottom: 20 }}>
            <SectionHeader
              title="Report Historical"
            />
            <div style={{ padding: '20px 20px 0px 20px' }}>
              <div style={contentStyle}>
                <AutocompleteField
                  options={listReportType}
                  value={data?.report_id}
                  onChange={(event, newValue) => this.handleChangeDropdown(newValue, 'report_id')}
                  label="Report Type"
                  isLoading={isLoading}
                />
                <AutocompleteField
                  options={listPeriodType}
                  value={data?.performance_period}
                  onChange={(event, newValue) => this.handleChangeDropdown(newValue, 'performance_period')}
                  label="Period Type"
                />
              </div>
              <div style={contentStyle}>
                <DDLMonth
                  value={data?.month}
                  name="month"
                  useCurrentMonthAsDefault={true}
                  onChange={(event, newValue, name) => this.handleChangeDropdown(newValue, name)}
                />

                <DDLYear
                  value={data?.year}
                  name="year"
                  useCurrentYearAsDefault={true}
                  onChange={(event, newValue, name) => this.handleChangeDropdown(newValue, name)}
                />
              </div>
              <DDLCompany
                multiple
                value={data?.company_id}
                name={"company_id"}
                onChange={(event, newValue, name) => this.handleChangeDropdown(newValue, name)}
              />

            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', paddingLeft: 20, paddingRight: 20, marginTop: 20 }}>
              <CustomButton
                disabled={this.state.buttonError}
                onClick={this.handleDownload}
              >
                Download
              </CustomButton>
            </div>


          </Paper>
        </div>

        <AlertSnackbar
          open={showAlert}
          message={alertMessage}
          severity={alertSeverity}
          onClose={this.closeAlert}
        />
      </ContentContainer>
    )
  }
}

export default ReportHistorical
