<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">
        <!-- Loader -->
        @if (isLoading) {
        <div class="absolute inset-x-0 bottom-0">
            <mat-progress-bar [mode]="'indeterminate'"></mat-progress-bar>
        </div>
        }
        <!-- Title -->
        <div class="text-4xl font-extrabold tracking-tight">User Management</div>
        <!-- Actions -->
        <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 users'" />
            </mat-form-field>
            <!-- Add user button -->
            <button class="ml-4" mat-flat-button [color]="'primary'" (click)="createUser()">
                <mat-icon [svgIcon]="'heroicons_outline:plus'"></mat-icon>
                <span class="ml-2 mr-1">Add User</span>
            </button>
        </div>
    </div>

    <!-- Main -->
    <div class="flex flex-auto overflow-hidden">
        <!-- Users list -->
        <div class="flex flex-auto flex-col overflow-hidden sm:mb-18 sm:overflow-y-auto">
            @if (users$ | async; as users) {
            @if (users.length > 0 || selectedUser) {
            <div class="grid">
                <!-- Header -->
                <div class="user-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"
                    matSort matSortDisableClear>
                    <div class="hidden md:block" [mat-sort-header]="'id'">ID</div>
                    <div [mat-sort-header]="'username'">Username</div>
                    <div class="hidden sm:block" [mat-sort-header]="'email'">Email</div>
                    <div class="hidden lg:block" [mat-sort-header]="'contact'">Contact</div>
                    <div class="hidden lg:block" [mat-sort-header]="'roles'">Role</div>
                    <div class="hidden lg:block" [mat-sort-header]="'user_status'">Status</div>
                    <div class="hidden sm:block">Details</div>
                </div>

                <!-- New User Form Row (shows when creating new user) -->
                @if (selectedUser && !selectedUser.id) {
                <div class="user-grid grid items-center gap-4 border-b bg-blue-50 px-6 py-3 md:px-8">
                    <!-- ID -->
                    <div class="hidden truncate md:block">
                        <span class="text-blue-600 font-medium">NEW</span>
                    </div>

                    <!-- Username -->
                    <div class="flex items-center">
                        <div
                            class="relative mr-3 flex h-10 w-10 flex-0 items-center justify-center overflow-hidden rounded-full border bg-blue-200">
                            <mat-icon class="text-blue-600" [svgIcon]="'heroicons_outline:plus'"></mat-icon>
                        </div>
                        <div class="truncate font-medium text-blue-600">
                            New User
                        </div>
                    </div>

                    <!-- Email -->
                    <div class="hidden truncate sm:block text-blue-600">
                        Creating...
                    </div>

                    <!-- Contact -->
                    <div class="hidden truncate lg:block text-blue-600">
                        -
                    </div>

                    <!-- Role -->
                    <div class="hidden lg:block">
                        <span
                            class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-blue-100 text-blue-800">
                            New User
                        </span>
                    </div>

                    <!-- Status -->
                    <div class="hidden lg:block">
                        <span
                            class="inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-800">
                            <span class="mr-1 h-2 w-2 rounded-full bg-green-400"></span>
                            Active
                        </span>
                    </div>

                    <!-- Details button -->
                    <div class="hidden sm:block">
                        <button class="h-7 min-h-7 min-w-10 px-2 leading-6" mat-stroked-button [color]="'primary'"
                            (click)="closeDetails()">
                            <mat-icon class="icon-size-5" [svgIcon]="'heroicons_solid:chevron-up'"></mat-icon>
                        </button>
                    </div>
                </div>

                <!-- New User Form Details -->
                <div class="grid">
                    <ng-container
                        *ngTemplateOutlet="rowDetailsTemplate; context: { $implicit: selectedUser }"></ng-container>
                </div>
                }

                <!-- Existing Users -->
                @for (user of users; track trackByFn($index, user)) {
                <div class="user-grid grid items-center gap-4 border-b px-6 py-3 md:px-8">
                    <!-- ID -->
                    <div class="hidden truncate md:block">
                        {{ user.id }}
                    </div>

                    <!-- Username -->
                    <div class="flex items-center">
                        <div
                            class="relative mr-3 flex h-10 w-10 flex-0 items-center justify-center overflow-hidden rounded-full border bg-gray-200">
                            @if (user.photo) {
                            <img [src]="getFullFileUrl(user.photo)" [alt]="user.username"
                                class="h-full w-full object-cover">
                            } @else {
                            <span class="text-sm font-semibold uppercase">
                                {{ user.username.charAt(0) }}
                            </span>
                            }
                        </div>
                        <div class="truncate">
                            <div class="font-medium">{{ user.username }}</div>
                            @if (user.user_id) {
                            <div class="text-xs text-gray-500">{{ user.user_id }}</div>
                            }
                        </div>
                    </div>

                    <!-- Email -->
                    <div class="hidden truncate sm:block">
                        {{ user.email }}
                    </div>

                    <!-- Contact -->
                    <div class="hidden truncate lg:block">
                        {{ user.contact }}
                    </div>

                    <!-- Role -->
                    <div class="hidden lg:block">
                        <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium" [ngClass]="{
                                'bg-orange-100 text-orange-800': user.roles === 'SuperAdmin',
                                'bg-amber-100 text-amber-800': user.roles === 'Management',
                                'bg-red-100 text-red-800': user.roles === 'Admin',
                                'bg-blue-100 text-blue-800': user.roles === 'Client',
                                'bg-green-100 text-green-800': user.roles === 'Reseller',
                                'bg-yellow-100 text-yellow-800': user.roles === 'Refiller'
                            }">
                            {{ user.roles }}
                        </span>
                    </div>

                    <!-- Status -->
                    <div class="hidden lg:block">
                        @if (user.user_status === 'Active') {
                        <span
                            class="inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-800">
                            <span class="mr-1 h-2 w-2 rounded-full bg-green-400"></span>
                            Active
                        </span>
                        }
                        @if (user.user_status === 'Inactive') {
                        <span
                            class="inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-800">
                            <span class="mr-1 h-2 w-2 rounded-full bg-gray-400"></span>
                            Inactive
                        </span>
                        }
                    </div>

                    <!-- Details button -->
                    <div class="hidden sm:block">
                        <button class="h-7 min-h-7 min-w-10 px-2 leading-6" mat-stroked-button
                            (click)="toggleDetails(user.id)">
                            <mat-icon class="icon-size-5" [svgIcon]="
                                    selectedUser?.id === user.id
                                        ? 'heroicons_solid:chevron-up'
                                        : 'heroicons_solid:chevron-down'
                                "></mat-icon>
                        </button>
                    </div>
                </div>

                <!-- Existing User Details -->
                @if (selectedUser?.id === user.id) {
                <div class="grid">
                    <ng-container *ngTemplateOutlet="rowDetailsTemplate; context: { $implicit: user }"></ng-container>
                </div>
                }
                }
            </div>

            <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"
                [ngClass]="{ 'pointer-events-none': isLoading }" [length]="pagination.length"
                [pageIndex]="pagination.page" [pageSize]="pagination.size" [pageSizeOptions]="[5, 10, 25, 100]"
                [showFirstLastButtons]="true"></mat-paginator>
            } @else {
            <div class="border-t p-8 text-center text-4xl font-semibold tracking-tight sm:p-16">
                No users found!
            </div>
            }
            }

            <!-- Row Details Template -->
            <ng-template #rowDetailsTemplate let-user>
                <div class="overflow-hidden shadow-lg">
                    <div class="flex border-b">
                        <form class="flex w-full flex-col" [formGroup]="selectedUserForm" enctype="multipart/form-data">
                            <div class="flex flex-col p-8 sm:flex-row">
                                <!-- User Avatar/Photo and Status -->
                                <div class="mb-8 flex flex-col items-center sm:mb-0 sm:items-start sm:mr-8">
                                    <!-- Photo Upload Section -->
                                    <div class="flex flex-col items-center mb-6">
                                        <div
                                            class="relative flex h-32 w-32 items-center justify-center overflow-hidden rounded-full border-4 bg-gray-200">
                                            @if (photoPreview || user.photo) {
                                            <img [src]="photoPreview || getFullFileUrl(user.photo)" alt="User photo"
                                                class="h-full w-full object-cover">
                                            } @else {
                                            <span class="text-4xl font-bold uppercase">
                                                {{ user.username ? user.username.charAt(0) : '?' }}
                                            </span>
                                            }
                                            <label
                                                class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 opacity-0 hover:opacity-100 cursor-pointer transition-opacity">
                                                <mat-icon class="text-white">camera_alt</mat-icon>
                                                <input type="file" accept="image/*" class="hidden"
                                                    (change)="onPhotoSelected($event)">
                                            </label>
                                        </div>
                                        <span class="mt-2 text-sm text-gray-600">User Photo</span>
                                    </div>

                                    @if (user.user_id) {
                                    <div class="mb-4 p-3 bg-blue-50 rounded-lg w-full">
                                        <span class="text-xs text-gray-600">User ID</span>
                                        <p class="font-mono font-semibold text-blue-600">{{ user.user_id }}</p>
                                    </div>
                                    }

                                    <div class="flex flex-col w-full">
                                        <span class="mb-2 font-semibold">User Status</span>
                                        <mat-slide-toggle [color]="'primary'"
                                            [checked]="selectedUserForm.get('user_status')?.value === 'Active'"
                                            (change)="onStatusChange($event)">
                                            {{ selectedUserForm.get('user_status')?.value === 'Active' ? 'Active' :
                                            'Inactive' }}
                                        </mat-slide-toggle>
                                    </div>

                                    <div class="mt-6 flex flex-col items-center w-full">
                                        <span class="mb-2 text-sm font-semibold">Company Logo</span>
                                        <div
                                            class="relative flex h-24 w-24 items-center justify-center overflow-hidden rounded-lg border-2 border-dashed border-gray-300 bg-gray-50">
                                            @if (logoPreview || user.company_logo) {
                                            <img [src]="logoPreview || getFullFileUrl(user.company_logo)"
                                                alt="Company logo" class="h-full w-full object-contain p-2">
                                            } @else {
                                            <mat-icon class="text-gray-400">business</mat-icon>
                                            }
                                            <label
                                                class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 opacity-0 hover:opacity-100 cursor-pointer transition-opacity">
                                                <mat-icon class="text-white">upload</mat-icon>
                                                <input type="file" accept="image/*" class="hidden"
                                                    (change)="onLogoSelected($event)">
                                            </label>
                                        </div>
                                    </div>
                                </div>

                                <div class="flex flex-auto flex-wrap">
                                    <div class="flex w-full flex-col lg:w-1/2 lg:pr-4">
                                        <h3 class="mb-4 text-lg font-semibold text-gray-900">Personal Information</h3>

                                        <mat-form-field class="w-full">
                                            <mat-label>Username</mat-label>
                                            <input matInput [formControlName]="'username'" />
                                            <mat-error *ngIf="selectedUserForm.get('username')?.hasError('required')">
                                                Username is required
                                            </mat-error>
                                        </mat-form-field>

                                        <mat-form-field class="w-full">
                                            <mat-label>Email</mat-label>
                                            <input matInput type="email" [formControlName]="'email'" />
                                            <mat-error *ngIf="selectedUserForm.get('email')?.hasError('required')">
                                                Email is required
                                            </mat-error>
                                            <mat-error *ngIf="selectedUserForm.get('email')?.hasError('email')">
                                                Please enter a valid email
                                            </mat-error>
                                        </mat-form-field>

                                        <mat-form-field class="w-full">
                                            <mat-label>Contact</mat-label>
                                            <input matInput type="tel" [formControlName]="'contact'" />
                                            <mat-error *ngIf="selectedUserForm.get('contact')?.hasError('required')">
                                                Contact is required
                                            </mat-error>
                                            <mat-error *ngIf="selectedUserForm.get('contact')?.hasError('pattern')">
                                                Please enter a valid 10-digit contact number
                                            </mat-error>
                                        </mat-form-field>
                                    </div>

                                    <div class="flex w-full flex-col lg:w-1/2 lg:pl-4">
                                        <h3 class="mb-4 text-lg font-semibold text-gray-900">Role & Security</h3>

                                        <mat-form-field class="w-full">
                                            <mat-label>Role</mat-label>
                                            <mat-select [formControlName]="'roles'"
                                                [disabled]="isClient && !selectedUser?.id">
                                                <mat-option *ngFor="let role of availableRoles" [value]="role.value">
                                                    {{ role.label }}
                                                </mat-option>
                                            </mat-select>
                                            <mat-error *ngIf="selectedUserForm.get('roles')?.hasError('required')">
                                                Role is required
                                            </mat-error>
                                            <mat-hint *ngIf="isClient">You can only create Refiller users</mat-hint>
                                        </mat-form-field>

                                        @if (!user.id) {
                                        <mat-form-field class="w-full">
                                            <mat-label>Password</mat-label>
                                            <input matInput type="password" [formControlName]="'password'" />
                                            <mat-error *ngIf="selectedUserForm.get('password')?.hasError('required')">
                                                Password is required
                                            </mat-error>
                                            <mat-error *ngIf="selectedUserForm.get('password')?.hasError('minlength')">
                                                Password must be at least 6 characters
                                            </mat-error>
                                        </mat-form-field>
                                        }

                                        @if (user.id) {
                                        <div class="mt-4 rounded-lg bg-gray-50 p-4">
                                            <h4 class="text-sm font-medium text-gray-900">Account Information</h4>
                                            <p class="mt-1 text-sm text-gray-600">
                                                Created: {{ user.created_at | date:'short' }}
                                            </p>
                                            @if (user.updated_at) {
                                            <p class="text-sm text-gray-600">
                                                Updated: {{ user.updated_at | date:'short' }}
                                            </p>
                                            }
                                        </div>
                                        }
                                    </div>

                                    <!-- Documents Section -->
                                    <div class="flex w-full flex-col mt-6 pt-6 border-t">
                                        <h3 class="mb-4 text-lg font-semibold text-gray-900">Documents & Files</h3>

                                        <!-- Document Upload Button -->
                                        <div class="mb-4">
                                            <label
                                                class="cursor-pointer inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                                                <mat-icon class="mr-2">attach_file</mat-icon>
                                                Upload Documents
                                                <input type="file" multiple accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                                                    class="hidden" (change)="onDocumentsSelected($event)">
                                            </label>
                                            <p class="mt-1 text-xs text-gray-500">PDF, DOC, DOCX, JPG, PNG (Max 10MB
                                                each)</p>
                                        </div>

                                        <!-- New Documents to Upload -->
                                        @if (selectedDocuments.length > 0) {
                                        <div class="mb-6">
                                            <h4 class="text-sm font-medium text-gray-700 mb-3">New Documents to Upload:
                                            </h4>
                                            <div class="space-y-3">
                                                @for (doc of selectedDocuments; track $index) {
                                                <div class="p-3 bg-blue-50 rounded-lg border border-blue-200">
                                                    <div class="flex items-start justify-between mb-2">
                                                        <div class="flex items-center flex-1">
                                                            <mat-icon class="text-blue-600 mr-2">{{
                                                                getDocumentIcon(doc.file.name) }}</mat-icon>
                                                            <div class="flex-1">
                                                                <span class="text-sm font-medium">{{ doc.file.name
                                                                    }}</span>
                                                                <span class="text-xs text-gray-500 ml-2">({{
                                                                    getFileSize(doc.file.size) }})</span>
                                                            </div>
                                                        </div>
                                                        <button type="button" mat-icon-button
                                                            (click)="removeDocument($index)" class="text-red-600 -mt-2">
                                                            <mat-icon>close</mat-icon>
                                                        </button>
                                                    </div>

                                                    <!-- Document Type Selection -->
                                                    <div class="flex flex-col sm:flex-row gap-3 mt-2">
                                                        <mat-form-field class="flex-1" appearance="outline">
                                                            <mat-label>Document Type</mat-label>
                                                            <mat-select [(value)]="doc.documentType"
                                                                (selectionChange)="updateDocumentType($index, $event.value)">
                                                                @for (type of documentTypes; track type.value) {
                                                                <mat-option [value]="type.value">{{ type.label
                                                                    }}</mat-option>
                                                                }
                                                            </mat-select>
                                                        </mat-form-field>

                                                        @if (doc.documentType === 'other') {
                                                        <mat-form-field class="flex-1" appearance="outline">
                                                            <mat-label>Specify Document Type</mat-label>
                                                            <input matInput [(ngModel)]="doc.documentTypeOther"
                                                                [ngModelOptions]="{standalone: true}"
                                                                (ngModelChange)="updateDocumentTypeOther($index, $event)"
                                                                placeholder="e.g., Trade License, Insurance Certificate"
                                                                required>
                                                        </mat-form-field>
                                                        }
                                                    </div>
                                                </div>
                                                }
                                            </div>
                                        </div>
                                        }

                                        <!-- Existing Documents -->
                                        @if (user.documents && user.documents.length > 0) {
                                        <div>
                                            <h4 class="text-sm font-medium text-gray-700 mb-3">Existing Documents:</h4>
                                            <div class="space-y-2">
                                                @for (doc of user.documents; track doc.path) {
                                                <div
                                                    class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                                                    <div class="flex items-center flex-1 min-w-0">
                                                        <mat-icon class="text-gray-600 mr-3 flex-shrink-0">{{
                                                            getDocumentIcon(doc.filename) }}</mat-icon>
                                                        <div class="flex-1 min-w-0">
                                                            <div class="flex items-center gap-2 mb-1">
                                                                <span class="text-sm font-medium truncate">{{
                                                                    doc.filename }}</span>
                                                                <span
                                                                    class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 flex-shrink-0">
                                                                    {{ doc.document_type_other ||
                                                                    getDocumentTypeLabel(doc.document_type) }}
                                                                </span>
                                                            </div>
                                                            <p class="text-xs text-gray-500">
                                                                Uploaded: {{ doc.uploaded_at | date:'short' }}
                                                            </p>
                                                        </div>
                                                    </div>
                                                    <div class="flex items-center gap-1 ml-2 flex-shrink-0">
                                                        <button type="button" mat-icon-button
                                                            (click)="viewDocument(doc)" class="text-blue-600"
                                                            matTooltip="View/Download Document">
                                                            <mat-icon>visibility</mat-icon>
                                                        </button>
                                                        <button type="button" mat-icon-button
                                                            (click)="deleteExistingDocument(doc.path)"
                                                            class="text-red-600" matTooltip="Delete Document">
                                                            <mat-icon>delete</mat-icon>
                                                        </button>
                                                    </div>
                                                </div>
                                                }
                                            </div>
                                        </div>
                                        }

                                        <!-- Empty State -->
                                        @if (!user.documents || user.documents.length === 0) {
                                        <div
                                            class="text-center py-8 px-4 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
                                            <mat-icon class="text-gray-400 mb-2"
                                                style="font-size: 48px; width: 48px; height: 48px;">folder_open</mat-icon>
                                            <p class="text-sm text-gray-600">No documents uploaded yet</p>
                                            <p class="text-xs text-gray-500 mt-1">Upload documents using the button
                                                above</p>
                                        </div>
                                        }
                                    </div>
                                </div>
                            </div>

                            <div class="flex w-full items-center justify-between border-t px-8 py-4 bg-gray-50">
                                <button class="-ml-4" mat-button [color]="'warn'" (click)="deleteSelectedUser()"
                                    type="button">
                                    <mat-icon>delete</mat-icon>
                                    <span class="ml-1">Delete</span>
                                </button>
                                <div class="flex items-center">
                                    @if (flashMessage) {
                                    <div class="mr-4 flex items-center">
                                        @if (flashMessage === 'success') {
                                        <mat-icon class="text-green-500"
                                            [svgIcon]="'heroicons_outline:check'"></mat-icon>
                                        <span class="ml-2">User {{ user.id ? 'updated' : 'created' }}</span>
                                        }
                                        @if (flashMessage === 'error') {
                                        <mat-icon class="text-red-500"
                                            [svgIcon]="'heroicons_outline:x-mark'"></mat-icon>
                                        <span class="ml-2">An error occurred, try again!</span>
                                        }
                                    </div>
                                    }
                                    <button mat-stroked-button class="mr-2" (click)="closeDetails()" type="button">
                                        Cancel
                                    </button>
                                    <button mat-flat-button [color]="'primary'" (click)="updateSelectedUser()"
                                        type="button" [disabled]="selectedUserForm.invalid || isLoading">
                                        @if (isLoading) {
                                        <mat-icon class="animate-spin">refresh</mat-icon>
                                        }
                                        <span class="ml-1">{{ user.id ? 'Update' : 'Create' }}</span>
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </ng-template>
        </div>
    </div>
</div>