// widgets/AccountSettingsWidget.ts
import { Widget } from '../components/Widget';
import { createElement } from '../utils/utils';
import { globalAPI, ApiResponse } from '../api/api';

export class AccountSettingsWidget extends Widget {
    private onSettingsUpdated: () => void;

    constructor(onSettingsUpdated: () => void) {
        super();
        this.onSettingsUpdated = onSettingsUpdated;
    }

    render(): HTMLElement {
        this.container.innerHTML = '';

        const header = createElement('div');
        header.classList.add('widget-header');
        header.textContent = 'Account Settings';
        this.container.appendChild(header);

        const widgetBody = createElement('div');
        widgetBody.classList.add('widget-body');

        const form = createElement('form');

        // Profile Picture Section
        const profilePictureSection = createElement('div');
        profilePictureSection.classList.add('mb-3');
        const profilePictureLabel = createElement('label') as HTMLLabelElement; // Cast first
        profilePictureLabel.classList.add('form-label');
        profilePictureLabel.htmlFor = 'profilePicture'; // Set htmlFor as property
        profilePictureLabel.textContent = 'Profile Picture';
        const profilePictureInput = createElement('input') as HTMLInputElement;
        profilePictureInput.type = 'file';
        profilePictureInput.classList.add('form-control');
        profilePictureInput.id = 'profilePicture';
        profilePictureSection.appendChild(profilePictureLabel);
        profilePictureSection.appendChild(profilePictureInput);
        form.appendChild(profilePictureSection);

        // Student Details Section (Read-only in prototype)
        const studentDetailsSection = createElement('div');
        studentDetailsSection.classList.add('mb-3');
        studentDetailsSection.innerHTML = `
            <div class="mb-2"><strong>Student Details</strong> <span class="text-muted">(Contact department head for corrections)</span></div>
            <div class="mb-2">
                <label for="fullName" class="form-label">Full Name</label>
                <input type="text" class="form-control" id="fullName" value="John Doe" readonly disabled>
            </div>
            <div>
                <label for="birthdate" class="form-label">Birthdate</label>
                <input type="text" class="form-control" id="birthdate" value="2000-01-01" readonly disabled>
            </div>
        `;
        form.appendChild(studentDetailsSection);

        // Password Change Section
        const passwordChangeSection = createElement('div');
        passwordChangeSection.classList.add('mb-3');
        passwordChangeSection.innerHTML = `
            <div class="mb-2"><strong>Change Password</strong></div>
            <div class="mb-2">
                <label for="newPassword" class="form-label">New Password</label>
                <input type="password" class="form-control" id="newPassword" placeholder="New Password">
            </div>
            <div>
                <label for="confirmPassword" class="form-label">Confirm New Password</label>
                <input type="password" class="form-control" id="confirmPassword" placeholder="Confirm New Password">
            </div>
        `;
        form.appendChild(passwordChangeSection);

        const saveButton = createElement('button');
        saveButton.type = 'submit';
        saveButton.classList.add('btn', 'btn-primary');
        saveButton.textContent = 'Save Changes';
        form.appendChild(saveButton);

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            // In a real application, you would collect and validate form data,
            // then send it to the backend API for updateAccountSettings.
            // For this prototype, we'll just simulate a successful update.

            const newPassword = (document.getElementById('newPassword') as HTMLInputElement).value;
            const confirmPassword = (document.getElementById('confirmPassword') as HTMLInputElement).value;

            if (newPassword && newPassword !== confirmPassword) {
                alert('New password and confirm password do not match.');
                return;
            }

            const settingsData = {
                // profilePicture: ..., // Handle profile picture upload in real app
                password: newPassword || undefined, // Send password only if changed
                // ... other settings to update
            };

            try {
                const response: ApiResponse<void> = await globalAPI.updateAccountSettings('mockUserId', settingsData); // Typed response
                if (response.success) {
                    alert('Account settings updated successfully!');
                    this.onSettingsUpdated(); // Call the callback to hide the modal
                } else {
                    alert('Failed to update account settings.');
                }
            } catch (error) {
                console.error('Error updating account settings:', error);
                alert('Error occurred while updating account settings.');
            }
        });


        widgetBody.appendChild(form);
        this.container.appendChild(widgetBody);
        return this.container;
    }
}