import 'package:base_project/commans/widgets/custom_textform_field.dart';
import 'package:base_project/commans/widgets/custome_elevated_button.dart';
import 'package:base_project/core/constants/ui_constants.dart';
import 'package:base_project/core/providers/dynamic_theme_provider.dart';
import 'package:base_project/utils/validator/text_feild_validator.dart';
import 'package:base_project/view/auth/sign_up_view.dart';
import 'package:base_project/view_model/auth/auth_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:iconsax/iconsax.dart';
import 'package:provider/provider.dart';

class AdminRegView extends StatefulWidget {
  AdminRegView({super.key});

  @override
  State<AdminRegView> createState() => _AdminRegViewState();
}

class _AdminRegViewState extends State<AdminRegView>
    with TickerProviderStateMixin {
  // Controllers and FormKey declarations
  final TextEditingController _companyNameController = TextEditingController();
  final TextEditingController _adminNameController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _workspaceController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  late AnimationController _pageController;
  late AnimationController _cardController;
  late Animation<double> _fade;
  late Animation<Offset> _slide;

  @override
  void initState() {
    super.initState();
    _pageController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 900));
    _cardController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 700));
    _fade = CurvedAnimation(parent: _pageController, curve: Curves.easeInOut);
    _slide = Tween<Offset>(begin: const Offset(0, 0.15), end: Offset.zero)
        .animate(CurvedAnimation(
            parent: _pageController, curve: Curves.easeOutCubic));
    _pageController.forward();
    Future.delayed(
        const Duration(milliseconds: 250), () => _cardController.forward());
  }

  @override
  void dispose() {
    _companyNameController.dispose();
    _adminNameController.dispose();
    _emailController.dispose();
    _phoneController.dispose();
    _workspaceController.dispose();
    _pageController.dispose();
    _cardController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;

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

        return Scaffold(
          appBar: AppBar(
            elevation: 0,
            backgroundColor: Colors.transparent,
            leading: IconButton(
              onPressed: () => Navigator.pop(context),
              icon: const Icon(Icons.arrow_back_ios_new),
              color: Colors.white,
            ),
            centerTitle: true,
          ),
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  colorScheme.primary,
                  colorScheme.primary.withOpacity(0.85),
                  colorScheme.secondary.withOpacity(0.65),
                ],
                stops: const [0.0, 0.6, 1.0],
              ),
            ),
            child: Center(
              child: FadeTransition(
                opacity: _fade,
                child: SlideTransition(
                  position: _slide,
                  child: SingleChildScrollView(
                    padding: UIConstants.getResponsivePadding(
                      context,
                      mobile: const EdgeInsets.all(UIConstants.spacing16),
                      tablet: const EdgeInsets.all(UIConstants.spacing24),
                      desktop: const EdgeInsets.all(UIConstants.spacing32),
                    ),
                    child: Container(
                      width: UIConstants.getResponsiveValue(
                        context,
                        mobile: double.infinity,
                        tablet: 520,
                        desktop: 640,
                      ),
                      padding: UIConstants.cardPaddingLarge,
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.96),
                        borderRadius:
                            BorderRadius.circular(UIConstants.radius24),
                        border: Border.all(
                            color: Colors.white.withOpacity(0.3), width: 1),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.15),
                            blurRadius: 28,
                            offset: const Offset(0, 16),
                            spreadRadius: 8,
                          ),
                        ],
                      ),
                      child: Form(
                        key: _formKey,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  width: 72,
                                  height: 72,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: colorScheme.primary.withOpacity(0.1),
                                    border: Border.all(
                                        color: Colors.white.withOpacity(0.4),
                                        width: 1),
                                  ),
                                  child: Icon(Icons.business_center_outlined,
                                      size: 36, color: colorScheme.primary),
                                ),
                              ],
                            ),
                            const SizedBox(height: UIConstants.spacing16),
                            Text(
                              "Register Your Company",
                              textAlign: TextAlign.center,
                              style: textTheme.headlineMedium?.copyWith(
                                color: colorScheme.primary,
                                fontWeight: FontWeight.w800,
                                letterSpacing: 0.2,
                              ),
                            ),
                            const SizedBox(height: UIConstants.spacing8),
                            Text(
                              "Create your workspace and admin account",
                              textAlign: TextAlign.center,
                              style: textTheme.bodyMedium?.copyWith(
                                color: Colors.black.withOpacity(0.65),
                              ),
                            ),

                            const SizedBox(height: UIConstants.spacing24),

                            // Company Name
                            MyCustomTextFormField(
                              controller: _companyNameController,
                              label: "Company Name",
                              prefixIcon: const Icon(Icons.business),
                              validator: TextFieldValidator.validateField,
                            ),
                            const SizedBox(height: UIConstants.spacing16),

                            // Admin Full Name
                            MyCustomTextFormField(
                              controller: _adminNameController,
                              label: "Admin Name",
                              prefixIcon: const Icon(Iconsax.profile_circle),
                              validator: TextFieldValidator.validateField,
                            ),
                            const SizedBox(height: UIConstants.spacing16),

                            // Company Email
                            MyCustomTextFormField(
                              controller: _emailController,
                              label: "Company Email",
                              prefixIcon: const Icon(Icons.alternate_email),
                              validator: TextFieldValidator.validateEmail,
                              keyboardType: TextInputType.emailAddress,
                            ),
                            const SizedBox(height: UIConstants.spacing16),

                            // Phone Number
                            MyCustomTextFormField(
                              controller: _phoneController,
                              label: "Admin Phone Number",
                              prefixIcon: const Icon(Icons.phone_outlined),
                              validator: TextFieldValidator.validateField,
                              keyboardType: TextInputType.phone,
                              inputFormatters: [
                                FilteringTextInputFormatter.digitsOnly,
                              ],
                            ),
                            const SizedBox(height: UIConstants.spacing16),

                            // Workspace/Branch Name
                            MyCustomTextFormField(
                              controller: _workspaceController,
                              label: "Workspace/Branch Name",
                              prefixIcon: const Icon(Icons.location_city),
                              validator: TextFieldValidator.validateField,
                            ),

                            const SizedBox(height: UIConstants.spacing24),

                            // Register Button
                            Consumer<AuthViewModel>(
                              builder: (context, provider, child) {
                                return MyCustomElevatedButton(
                                  isLoading: provider.isLoading,
                                  child: const Text("Register Company"),
                                  onPressed: () async {
                                    if (_formKey.currentState!.validate()) {
                                      final Map<String, dynamic> signUpData = {
                                        "companyName":
                                            _companyNameController.text.trim(),
                                        "email": _emailController.text.trim(),
                                        "mobile": _phoneController.text.trim(),
                                        "workspace":
                                            _workspaceController.text.trim(),
                                      };
                                      await Provider.of<AuthViewModel>(context,
                                              listen: false)
                                          .createAcc(context, signUpData);
                                      if (mounted) {
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) => SignUpView(
                                              email:
                                                  _emailController.text.trim(),
                                            ),
                                          ),
                                        );
                                      }
                                    }
                                  },
                                );
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
