<global-bar></global-bar>

@if (requiredData$ | async) {}
@if (items$ | async) {}
@if (exportAction$ | async) {}
@if (bcExportAction$ | async) {}
@if (bcStatusAction$ | async) {}
@if (monthStartChanged$ | async) {}
@if (monthEndChanged$ | async) {}
@if (linesResult$ | async) {}
@if (downloadInvoiceResult$ | async) {}
@if (mergeFilesResult$ | async) {}

<div class="flex flex-col h-full overflow-hidden">
  <form [formGroup]="monthSelectionsForm">
    <fast-header [title]="title$ | async">
      <div class="flex items-center">
        <fast-button type="basic" class="w-full max-w-28 mr-1.5"
          [disabled]="gridLoading() || !this.isAnyRowSelected() || !(requiredData$ | async)?.hasDistributePermission" (click)="openDistribute()"
          fast-tip="Email all selected and approved invoices to their respective emails" tipPosition="bottom">
          Distribute
        </fast-button>
        <fast-button type="basic" class="w-full max-w-28 mr-1.5 whitespace-nowrap"
          [disabled]="gridLoading() || !this.isAnyRowSelected() || (isMergingFiles$ | async)" (click)="mergeFiles()"
          fast-tip="Merge the selected invoices generated PDF's into one document" tipPosition="bottom">
          {{(isMergingFiles$ | async) ? 'Merging...' : 'Merge Files' }}
        </fast-button>
        <fast-button type="basic" class="w-full max-w-28 mr-1.5"
          [disabled]="gridLoading() || !this.isAnyRowSelected() || !(requiredData$ | async)?.hasApprovalPermission" (click)="onApproveClicked()"
          fast-tip="Approve all line items for the selected invoices" tipPosition="bottom">
          <fast-svg icon="checkOutline" />Approve
        </fast-button>
      </div>
      <div class="flex grow items-center basis-1/2">
        @if (mySelection.length !== 0) {
        <fast-label fast-tip="Clear all selections" class="flex grow justify-center cursor-pointer mr-1.5 text-center" (click)="clearSelection()">
          {{mySelection.length}} invoices selected</fast-label>
        }
      </div>
      <div class="flex grow items-center basis-full">
        <fast-label class="whitespace-nowrap mr-1">From</fast-label>
        <fast-datepicker type="date-month" class="w-37.5 mr-2.5" formControlName="monthStart" bottomView="year"></fast-datepicker>
        <fast-label class="whitespace-nowrap mr-1">To</fast-label>
        <fast-datepicker type="date-month" class="w-37.5" formControlName="monthEnd" bottomView="year"></fast-datepicker>
      </div>
      <ng-template #bcStatusToolTemplate>
        <div class="flex flex-col">
          <span>{{this.currentStatus()?.status}}</span>
          <span>Ran At: {{util.formatDate(this.currentStatus()?.ranAt, 'MM/DD/YYYY h:mm A')}}</span>
          <div class="whitespace-pre-line">{{this.currentStatus()?.message}}</div>
        </div>
      </ng-template>
      <div class="flex grow justify-end basis-full">
        @if(bcExportStatus() === 'Success') {
        <fast-button class="w-full max-w-28 mr-2.5 whitespace-nowrap
        " type="success" (click)="exportToBc()" [disabled]="bcExporting$ | async" [hidden]="bcExporting$ | async" fast-tip [tipContent]="bcStatusToolTemplate"
          [tipMaxWidth]="800">
          <fast-svg icon="exportExternal" />BC Export
        </fast-button>
        }
        @else if(bcExportStatus() === 'Error') {
        <fast-button class="w-full max-w-28 mr-2.5 whitespace-nowrap" type="fail" (click)="exportToBc()" [disabled]="bcExporting$ | async"
          [hidden]="bcExporting$ | async" fast-tip [tipContent]="bcStatusToolTemplate" [tipMaxWidth]="800">
          <fast-svg icon="exportExternal" />BC Export
        </fast-button>
        }
        @else {
        <fast-button class="w-full max-w-28 mr-2.5 whitespace-nowrap" type="basic" (click)="exportToBc()" [disabled]="bcExporting$ | async"
          [hidden]="bcExporting$ | async">
          <fast-svg icon="exportExternal" />BC Export
        </fast-button>
        }
        <fast-button class="w-full max-w-28 mr-2.5 whitespace-nowrap" type="basic" (click)="exportToBc()" [hidden]="(bcExporting$ | async) === false"
          [disabled]="true">
          <fast-svg icon="exportExternal" />Exporting...
        </fast-button>
        <fast-button class="w-full max-w-28 mr-2.5" type="export" [disabled]="this.gridData === null || this.gridData.length === 0"
          [exporting]="exporting$ | async" (click)="export()" tabindex="-1"></fast-button>
      </div>
    </fast-header>
  </form>
  <div class="flex flex-row grow overflow-auto">
    <fast-grid #grid [loading]="gridLoading()" [data]="items$ | async" (cellClick)="edit($event.dataItem)" [pageable]="true" [pageSize]="state.take"
      [skip]="state.skip" [sort]="state.sort" [sortable]="{mode: 'multiple'}" [filterable]="'menu, row'" [filter]="state.filter"
      (dataStateChange)="dataStateChange($event)" [selectBy]="mySelectionKey" [selectable]="selectableSettings" [selectedKeys]="mySelection" [resizable]="true"
      [scrollable]="'scrollable'">
      <fast-grid-col type="checkbox" [width]="50" field="_" [filterable]="false" [headerTemplate]="initialHeader" [cellTemplate]="initialCell">
        <ng-template #initialHeader>
          <div class="flex justify-center align-center items-center p-0 m-0 h-full w-full" (click)="selectAllToggled($event)">
            <input class="overviewSelectAllCheckbox" kendoCheckBox type="checkbox" size="large" />
          </div>
        </ng-template>
        <ng-template #initialCell let-dataItem="dataItem" let-rowIndex="rowIndex">
          <div class="flex justify-center align-center items-center p-0 m-0 w-full h-full" (click)="toggleSelection($event, dataItem.Id, rowIndex)">
            @if (isCheckable(dataItem.Id)) {
            <input class="m-0" kendoCheckBox type="checkbox" size="large" [checked]="mySelection.includes(dataItem.Id)" />
            }
          </div>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="text" field="IsApproved" [width]="70" [headerTemplate]="approvedHeaderTemplate" [cellTemplate]="approvedCellTemplate">
        <ng-template #approvedHeaderTemplate>
          <ng-template #isApprovedToolTemplate>
            <div class="flex flex-col">
              <span>Type "y" or "yes" in the filter box for approved invoices</span>
              <span>Type "n" or "no" for unapproved invoices</span>
            </div>
          </ng-template>
          <div class="flex align-center justify-center w-full h-9" fast-tip [tipContent]="isApprovedToolTemplate" title="">
            <fast-svg class="flex self-center text-green-500" icon="check" fast-tip [tipContent]="isApprovedToolTemplate" />
            <span class="absolute underline decoration-dashed underline-offset-2 mt-2" fast-tip
              [tipContent]="isApprovedToolTemplate">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
          </div>
        </ng-template>
        <ng-template #approvedCellTemplate let-dataItem="dataItem">
          <div class="flex align-center justify-center h-full">
            @if (dataItem.IsApproved === 'yes') {
            <fast-svg class="flex self-center text-green-500" icon="check" />
            }
          </div>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="text" field="InvoiceNum" [width]="120" [title]="'Invoice #'" [cellTemplate]="summaryCellTemplate" class="p-0!">
        <ng-template #summaryCellTemplate let-dataItem="dataItem" let-column="column">
          <ng-template #summaryTooltip let-item="item">
            <div>
              <div style="white-space: pre-line;" [innerHTML]="item.SummaryInfo">
              </div>
            </div>
          </ng-template>
          <div class="underline decoration-dotted p-2" [class]="{'bg-base-yellow-250/50': dataItem | hasDifferences}" fast-tip
            #summaryTooltipDirective="fast-tip" [tipContent]="summaryTooltip" [tipContext]="{item: dataItem}"
            (mouseover)="onSummaryMouseover($event, summaryTooltipDirective)">
            {{dataItem.InvoiceNum}}
          </div>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="text" field="Traders" [width]="90" [title]="'Traders'"></fast-grid-col>
      <fast-grid-col class="group" type="text" field="FileNameOriginal" [width]="50" [title]="'File'" [filterable]="false" [cellTemplate]="fileCellTemplate"
        [class]="'p-0!'">
        <ng-template #fileCellTemplate let-dataItem="dataItem">
          @if (dataItem.FileNameOriginal) {
          <div class="flex cursor-pointer h-full justify-center" (click)="onFileIconClick(dataItem, $event)">
            <fast-svg class="text-red-600 group-hover:text-red-700 group-active:text-red-900" icon="pdfFile" />
          </div>
          }
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="text" field="Month" [width]="100" [title]="'Month'" [filterable]="false">
      </fast-grid-col>
      <fast-grid-col type="text" field="InternalEntity" [width]="250" [title]="'Internal Entity'"></fast-grid-col>
      <fast-grid-col type="text" field="Counterparty" [width]="250" [title]="'Counterparty'"></fast-grid-col>
      <fast-grid-col type="text" field="InvoiceType" [width]="200" [title]="'Version'"></fast-grid-col>
      <fast-grid-col type="date-short" field="DueDate" [width]="100" [title]="'Due Date'" [filterable]="false"></fast-grid-col>
      <fast-grid-col type="text" field="EmailedByName" [width]="200" [title]="'Emailed By'"></fast-grid-col>
      <fast-grid-col type="date-time" field="EmailedTime" [width]="200" [title]="'Emailed Time'"></fast-grid-col>
      <fast-grid-col type="text" field="CounterpartyEmailAddresses" [width]="200" [title]="'Email Addresses'"></fast-grid-col>
    </fast-grid>
  </div>
</div>

@if (detailOpened$ | async) {
<app-invoice-gas-detail #detail class="flex flex-col grow overflow-hidden" [invoiceId]="this.detailId" [counterpartyId]="this.counterpartyId"
  [internalEntityId]="this.internalEntityId" [month]="this.month" (closed)="closeDetail()"
  (refreshItems)="this.refreshItems$.next(null)"></app-invoice-gas-detail>
}

@if (distributeOpened$ | async) {
<app-invoice-distribute #distribution class="flex flex-col grow overflow-hidden" [mySelection]="this.mySelection"
  (closed)="closeDistribute()"></app-invoice-distribute>
}