import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/provider/account.dart';

import 'package:pweb/pages/settings/profile/account/name/actions.dart';
import 'package:pweb/providers/account_name.dart';
import 'package:pweb/pages/settings/profile/account/name/text.dart';


class _AccountNameConstants {
  static const inputWidth = 200.0;
  static const spacing = 8.0;
  static const errorSpacing = 4.0;
  static const borderWidth = 2.0;
}

class AccountName extends StatelessWidget {
  final String firstName;
  final String lastName;
  final String title;
  final String hintText;
  final String lastNameHint;
  final String errorText;

  const AccountName({
    super.key,
    required this.firstName,
    required this.lastName,
    required this.title,
    required this.hintText,
    required this.lastNameHint,
    required this.errorText,
  });

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (ctx) => AccountNameState(
        initialFirstName: firstName,
        initialLastName: lastName,
        errorMessage: errorText,
        accountProvider: ctx.read<AccountProvider>(),
      ),
      child: _AccountNameBody(
        hintText: hintText,
        lastNameHint: lastNameHint,
      ),
    );
  }
}

class _AccountNameBody extends StatelessWidget {
  const _AccountNameBody({
    required this.hintText,
    required this.lastNameHint,
  });

  final String hintText;
  final String lastNameHint;

  @override
  Widget build(BuildContext context) {
    final state = context.watch<AccountNameState>();
    final provider = context.watch<AccountProvider>();
    final theme = Theme.of(context);

    final currentFirstName = provider.account?.name ?? state.initialFirstName;
    final currentLastName = provider.account?.lastName ?? state.initialLastName;
    state.syncNames(currentFirstName, currentLastName);

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AccountNameText(
              hintText: hintText,
              lastNameHint: lastNameHint,
              inputWidth: _AccountNameConstants.inputWidth,
              borderWidth: _AccountNameConstants.borderWidth,
            ),
            const SizedBox(width: _AccountNameConstants.spacing),
            const AccountNameActions(),
          ],
        ),
        const SizedBox(height: _AccountNameConstants.errorSpacing),
        if (state.errorText.isNotEmpty)
          Text(
            state.errorText,
            style: theme.textTheme.bodySmall?.copyWith(
              color: theme.colorScheme.error,
            ),
          ),
      ],
    );
  }
}
