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,
      isLoadingReportType: false,

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

      buttonError: false,
    }
  }

  componentDidMount() {
    this.getData()
  }

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

  setLoadingReportType = (isLoadingReportType) => {
    this.setState({ isLoadingReportType })
  }

  getData() {
    this.setLoadingReportType(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()
        this.setLoadingReportType(false)
      })
    })
  }

  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 = Constant.ALERT_SEVIRITY.SUCCESS) => {
    this.setState({
      showAlert: true,
      alertMessage: message,
      alertSeverity: severity,
    });
  };

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

  handleDownload = async () => {
    try {
      const { data } = this.state
      if (!data?.company_id || data?.company_id?.length === 0) {
        this.showAlert('Data is not complete !', Constant.ALERT_SEVIRITY.WARNING);
        return
      }
      this.setLoading(true)
      const payload = {
        report_id: data.report_id?.id,
        company_id: data.company_id?.map(c => c.id).join(','),
        performance_period: data.performance_period?.id,
        year: data.year?.id,
        month: data.month?.id,
      }
      api.create('DOWNLOAD').exportReportHistorial(payload).then(async (res) => {
        this.setLoading(false)
        const blob = res.data

        if (blob && blob.size > 0) {
          const fileName = `Report_${Constant.PERIOD_TYPE[data.performance_period?.id]}_${data.report_id?.name}_${data.month?.name}_${data.year?.name}.xlsx`
          downloadFileBlob(fileName, blob)
        }

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

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

  render() {
    const { data, showAlert, alertMessage, alertSeverity, listReportType, listPeriodType, isLoading, isLoadingReportType } = 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={isLoadingReportType}
                />
                <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
