import 'package:base_project/core/constants/ui_constants.dart';
import 'package:base_project/core/providers/dynamic_theme_provider.dart';
import 'package:base_project/shared/widgets/app_bar/modern_app_bar.dart';
import 'package:base_project/shared/widgets/inputs/modern_text_field.dart';
import 'package:base_project/shared/widgets/buttons/modern_button.dart';
import 'package:base_project/view_model/profile/profile_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

class AccountUpdateView extends StatefulWidget {
  const AccountUpdateView({super.key});

  @override
  State<AccountUpdateView> createState() => _AccountUpdateViewState();
}

class _AccountUpdateViewState extends State<AccountUpdateView>
    with TickerProviderStateMixin {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _companyName;
  late TextEditingController _workspace;
  late TextEditingController _gstNumber;
  late TextEditingController _mobile;
  late TextEditingController _email; // read-only
  late TextEditingController _pancard;
  late TextEditingController _working;
  bool _active = true;

  late AnimationController _anim;
  late Animation<double> _fade;
  late Animation<Offset> _slide;

  @override
  void initState() {
    super.initState();
    _companyName = TextEditingController();
    _workspace = TextEditingController();
    _gstNumber = TextEditingController();
    _mobile = TextEditingController();
    _email = TextEditingController();
    _pancard = TextEditingController();
    _working = TextEditingController();

    _anim =
        AnimationController(duration: UIConstants.durationSlow, vsync: this);
    _fade = CurvedAnimation(parent: _anim, curve: UIConstants.curveNormal);
    _slide = Tween<Offset>(begin: const Offset(0, .2), end: Offset.zero)
        .animate(
            CurvedAnimation(parent: _anim, curve: UIConstants.curveNormal));

    WidgetsBinding.instance.addPostFrameCallback((_) {
      final vm = Provider.of<ProfileViewModel>(context, listen: false);
      final acc = vm.sysAccount ?? {};
      _companyName.text = (acc['companyName'] ?? '').toString();
      _workspace.text = (acc['workspace'] ?? '').toString();
      _gstNumber.text = (acc['gstNumber'] ?? '').toString();
      _mobile.text = (acc['mobile'] ?? '').toString();
      _email.text = (acc['email'] ?? '').toString();
      _pancard.text = (acc['pancard'] ?? '').toString();
      _working.text = (acc['working'] ?? '').toString();
      _active = acc['active'] == true;
      _anim.forward();
    });
  }

  @override
  void dispose() {
    _companyName.dispose();
    _workspace.dispose();
    _gstNumber.dispose();
    _mobile.dispose();
    _email.dispose();
    _pancard.dispose();
    _working.dispose();
    _anim.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<DynamicThemeProvider>(
      builder: (context, theme, child) {
        final colorScheme = theme.getCurrentColorScheme(
          Theme.of(context).brightness == Brightness.dark,
        );

        return Scaffold(
          appBar: ModernAppBar(
            title: 'Account Update',
            automaticallyImplyLeading: true,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back),
              onPressed: () => Navigator.pop(context),
            ),
            showThemeToggle: false,
            showUserProfile: false,
          ),
          body: AnimatedBuilder(
            animation: _anim,
            builder: (context, _) {
              return FadeTransition(
                opacity: _fade,
                child: SlideTransition(
                  position: _slide,
                  child: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [
                          colorScheme.primary.withOpacity(0.1),
                          colorScheme.secondary.withOpacity(0.05),
                          colorScheme.surface,
                        ],
                        stops: const [0.0, 0.3, 1.0],
                      ),
                    ),
                    child: SingleChildScrollView(
                      padding: UIConstants.getResponsivePadding(
                        context,
                        mobile: UIConstants.screenPaddingMedium,
                        tablet: UIConstants.screenPaddingLarge,
                        desktop: UIConstants.screenPaddingLarge,
                      ),
                      child: _buildFormCard(colorScheme),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  Widget _buildFormCard(ColorScheme colorScheme) {
    return Consumer<ProfileViewModel>(
      builder: (context, vm, _) {
        return Form(
          key: _formKey,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.95),
              borderRadius: BorderRadius.circular(UIConstants.radius24),
              border: Border.all(
                  color: colorScheme.surface.withOpacity(0.2), width: 1),
              boxShadow: [
                BoxShadow(
                  color: colorScheme.primary.withOpacity(0.1),
                  blurRadius: 20,
                  offset: const Offset(0, 10),
                  spreadRadius: 5,
                ),
              ],
            ),
            padding: UIConstants.cardPaddingLarge,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                ModernTextField(
                  label: 'Company Name',
                  hint: 'Enter company name',
                  controller: _companyName,
                  prefixIcon: const Icon(Icons.business),
                  validator: (v) =>
                      (v == null || v.isEmpty) ? 'Required' : null,
                ),
                SizedBox(height: UIConstants.spacing20),
                ModernTextField(
                  label: 'Workspace',
                  hint: 'Enter workspace',
                  controller: _workspace,
                  prefixIcon: const Icon(Icons.apartment_outlined),
                  validator: (v) =>
                      (v == null || v.isEmpty) ? 'Required' : null,
                ),
                SizedBox(height: UIConstants.spacing20),
                ModernTextField(
                  label: 'GST Number',
                  hint: 'Enter GST number',
                  controller: _gstNumber,
                  prefixIcon: const Icon(Icons.confirmation_number_outlined),
                ),
                SizedBox(height: UIConstants.spacing20),
                ModernTextField(
                  label: 'Mobile',
                  hint: 'Enter mobile number',
                  controller: _mobile,
                  keyboardType: TextInputType.phone,
                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  prefixIcon: const Icon(Icons.phone_outlined),
                ),
                SizedBox(height: UIConstants.spacing20),
                AbsorbPointer(
                  child: ModernTextField(
                    label: 'Email (read-only)',
                    hint: 'Email',
                    controller: _email,
                    prefixIcon: const Icon(Icons.email_outlined),
                  ),
                ),
                SizedBox(height: UIConstants.spacing20),
                ModernTextField(
                  label: 'PAN Card',
                  hint: 'Enter PAN',
                  controller: _pancard,
                  prefixIcon: const Icon(Icons.badge_outlined),
                ),
                SizedBox(height: UIConstants.spacing20),
                ModernTextField(
                  label: 'Working',
                  hint: 'Working status',
                  controller: _working,
                  prefixIcon: const Icon(Icons.work_outline),
                ),
                SizedBox(height: UIConstants.spacing20),
                Row(
                  children: [
                    Switch(
                      value: _active,
                      onChanged: (v) => setState(() => _active = v),
                    ),
                    const SizedBox(width: 8),
                    const Text('Active')
                  ],
                ),
                SizedBox(
                    height: UIConstants.getResponsiveSpacing(
                  context,
                  mobile: UIConstants.spacing32,
                  tablet: UIConstants.spacing40,
                  desktop: UIConstants.spacing48,
                )),
                ModernButton(
                  text: 'Update Account',
                  type: ModernButtonType.primary,
                  size: ModernButtonSize.large,
                  isLoading: vm.isUpdating,
                  icon: const Icon(Icons.save_outlined),
                  onPressed: () {
                    if (!_formKey.currentState!.validate()) return;
                    vm.updateAccount(context, {
                      'companyName': _companyName.text.trim(),
                      'workspace': _workspace.text.trim(),
                      'gstNumber': _gstNumber.text.trim(),
                      'mobile': _mobile.text.trim(),
                      'email': _email.text.trim(),
                      'pancard': _pancard.text.trim(),
                      'working': _working.text.trim(),
                      'active': _active,
                    });
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
