<div class="bg-card flex min-w-0 flex-auto flex-col dark:bg-transparent sm:absolute sm:inset-0 sm:overflow-hidden">
  <!-- Header -->
  <div class="relative flex flex-0 flex-col border-b px-6 py-8 sm:flex-row sm:items-center sm:justify-between md:px-8">
    <div *ngIf="isLoading" class="absolute inset-x-0 bottom-0">
      <mat-progress-bar mode="indeterminate"></mat-progress-bar>
    </div>

    <div>
      <div class="text-4xl font-extrabold tracking-tight">
        {{ isClient ? 'My Machines' : 'Machines' }}
      </div>
      <p *ngIf="isClient" class="mt-2 text-sm text-gray-600">
        View-only access - Contact admin to add or modify machines
      </p>
    </div>

    <div class="mt-6 flex shrink-0 items-center sm:ml-4 sm:mt-0">
      <!-- Search -->
      <mat-form-field class="fuse-mat-dense fuse-mat-rounded min-w-64" subscriptSizing="dynamic">
        <mat-icon class="icon-size-5" matPrefix svgIcon="heroicons_solid:magnifying-glass"></mat-icon>
        <input matInput [formControl]="searchInputControl" autocomplete="off" placeholder="Search machines" />
      </mat-form-field>

      <!-- Add button - ONLY for admins -->
      <button *ngIf="!isClient" class="ml-4" mat-flat-button color="primary" (click)="createMachine()">
        <mat-icon svgIcon="heroicons_outline:plus"></mat-icon>
        <span class="ml-2 mr-1">Add</span>
      </button>
    </div>
  </div>

  <!-- Main -->
  <div class="flex flex-auto overflow-auto">
    <div class="flex flex-auto flex-col">
      <div *ngIf="machines$ | async as machines">
        <ng-container *ngIf="machines.length > 0; else noMachines">
          <div class="grid min-w-max">
            <!-- Header -->
            <div
              class="inventory-grid text-secondary sticky top-0 z-10 grid gap-4 bg-gray-50 px-6 py-4 text-md font-semibold shadow dark:bg-black dark:bg-opacity-5 md:px-8">
              <div>ID</div>
              <div>Machine ID</div>
              <div>Model</div>
              <div>Type</div>
              <div>Client</div>
              <div>Branch</div>
              <div>Operation</div>
              <div>Connection</div>
              <div>Password</div>
              <div>Actions</div>
            </div>

            <!-- Rows -->
            <div *ngFor="let machine of machines; trackBy: trackByFn"
              class="inventory-grid grid items-center gap-4 border-b px-6 py-3 md:px-8">
              <div>{{ machine.id }}</div>
              <div>{{ machine.machine_id }}</div>
              <div>{{ machine.machine_model }}</div>
              <div>{{ machine.machine_type }}</div>
              <div>{{ machine.client_name }}</div>
              <div>{{ machine.branch_name }}</div>
              <div>{{ machine.operation_status }}</div>
              <div>{{ machine.connection_status }}</div>

              <!-- Password with toggle -->
              <div class="flex items-center gap-1">
                <span *ngIf="!machine.showPassword">••••••</span>
                <span *ngIf="machine.showPassword">{{ machine.password }}</span>

                <button mat-icon-button type="button" (click)="machine.showPassword = !machine.showPassword">
                  <mat-icon>{{ machine.showPassword ? 'visibility_off' : 'visibility' }}</mat-icon>
                </button>
              </div>

              <!-- Actions -->
              <div class="flex gap-2">
                <!-- Edit button - ONLY for admins -->
                <button *ngIf="!isClient" class="h-7 min-h-7 min-w-10 px-2 leading-6" mat-stroked-button
                  (click)="toggleDetails(machine.id)">
                  <mat-icon class="icon-size-5"
                    [svgIcon]="selectedMachine?.id === machine.id ? 'heroicons_solid:chevron-up' : 'heroicons_solid:chevron-down'"></mat-icon>
                </button>

                <!-- View button - for everyone -->
                <button class="h-7 min-h-7 px-3 leading-6" mat-flat-button [color]="isClient ? 'primary' : 'accent'"
                  (click)="viewMachineDetails(machine.id)">
                  View
                </button>
              </div>
            </div>
          </div>

          <!-- Expanded row - OUTSIDE the grid and *ngFor -->
          <div *ngIf="selectedMachine" class="w-full">
            <ng-container *ngTemplateOutlet="rowDetailsTemplate; context: { $implicit: selectedMachine }">
            </ng-container>
          </div>

          <!-- Paginator -->
          <mat-paginator
            class="z-10 border-b bg-gray-50 dark:bg-transparent sm:absolute sm:inset-x-0 sm:bottom-0 sm:border-b-0 sm:border-t"
            [length]="pagination.length" [pageIndex]="pagination.page" [pageSize]="pagination.size"
            [pageSizeOptions]="[5, 10, 25, 100]" showFirstLastButtons>
          </mat-paginator>
        </ng-container>

        <ng-template #noMachines>
          <div class="border-t p-8 text-center text-4xl font-semibold tracking-tight sm:p-16">
            There are no machines!
          </div>

          <!-- Expanded form for adding first machine when list is empty -->
          <div *ngIf="selectedMachine" class="w-full px-8">
            <ng-container *ngTemplateOutlet="rowDetailsTemplate; context: { $implicit: selectedMachine }">
            </ng-container>
          </div>
        </ng-template>
      </div>

      <!-- Expanded Template -->
      <ng-template #rowDetailsTemplate let-machine>
        <div class="overflow-hidden shadow-lg">
          <div class="flex border-b">
            <form class="flex w-full flex-col" [formGroup]="selectedMachineForm">
              <div class="flex flex-col p-8 sm:flex-row">
                <div class="flex flex-auto flex-wrap">
                  <!-- Model -->
                  <mat-form-field class="w-full sm:w-1/2 pr-2">
                    <mat-label>Machine Model</mat-label>
                    <input matInput formControlName="machine_model" />
                  </mat-form-field>

                  <!-- Type -->
                  <mat-form-field class="w-full sm:w-1/2 pl-2">
                    <mat-label>Machine Type</mat-label>
                    <input matInput formControlName="machine_type" />
                  </mat-form-field>

                  <!-- Client field - hide for Clients, show for admins -->
                  <mat-form-field class="w-full sm:w-1/2 pr-2" *ngIf="!isClient">
                    <mat-label>Client</mat-label>
                    <mat-select formControlName="client_id">
                      <mat-option *ngFor="let user of users" [value]="user.id">
                        {{ user.username }}
                      </mat-option>
                    </mat-select>
                  </mat-form-field>
                  <!-- Branch -->
                  <mat-form-field class="w-full sm:w-1/2 pl-2">
                    <mat-label>Branch Name</mat-label>
                    <input matInput formControlName="branch_name" />
                  </mat-form-field>

                  <!-- Operation -->
                  <mat-form-field class="w-full sm:w-1/2 pr-2">
                    <mat-label>Operation Status</mat-label>
                    <mat-select formControlName="operation_status">
                      <mat-option value="active">Active</mat-option>
                      <mat-option value="inactive">Inactive</mat-option>
                      <mat-option value="maintenance">Maintenance</mat-option>
                    </mat-select>
                  </mat-form-field>

                  <!-- Connection -->
                  <mat-form-field class="w-full sm:w-1/2 pl-2">
                    <mat-label>Connection Status</mat-label>
                    <mat-select formControlName="connection_status">
                      <mat-option value="connected">Connected</mat-option>
                      <mat-option value="disconnected">Disconnected</mat-option>
                    </mat-select>
                  </mat-form-field>

                  <!-- Password field only on ADD, hidden on edit -->
                  <mat-form-field class="w-full sm:w-1/2 pr-2" *ngIf="selectedMachine?.id === null">
                    <mat-label>Password</mat-label>
                    <input matInput formControlName="password" type="password" />
                  </mat-form-field>

                </div>
              </div>

              <!-- Footer -->
              <div class="flex w-full items-center justify-between border-t px-8 py-4">
                <!-- Delete button - ONLY show for admins and existing machines -->
                <button *ngIf="!isClient && selectedMachine?.id !== null" class="-ml-4" mat-button color="warn"
                  (click)="deleteSelectedMachine()">
                  Delete
                </button>

                <div *ngIf="isClient || selectedMachine?.id === null"></div>

                <div class="flex items-center">
                  <div *ngIf="flashMessage" class="mr-4 flex items-center">
                    <mat-icon *ngIf="flashMessage === 'success'" class="text-green-500"
                      svgIcon="heroicons_outline:check"></mat-icon>
                    <mat-icon *ngIf="flashMessage === 'error'" class="text-red-500"
                      svgIcon="heroicons_outline:x-mark"></mat-icon>
                    <span class="ml-2">
                      {{ flashMessage === 'success' ? 'Machine updated' : 'An error occurred' }}
                    </span>
                  </div>

                  <!-- Update/Create button - ONLY for admins -->
                  <button *ngIf="!isClient" mat-flat-button color="primary" (click)="updateSelectedMachine()">
                    {{ selectedMachine?.id === null ? 'Create' : 'Update' }}
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </ng-template>
    </div>
  </div>
</div>