import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_pos_ecommerce/module/ecommerce/presentation/home/bloc/checkout/checkout_bloc.dart';
import 'package:flutter_pos_ecommerce/module/pos/presentation/setting/bloc/profile/profile_bloc.dart';
import 'package:flutter_pos_ecommerce/module/pos/presentation/setting/pages/profile_page.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../../../../../core/constants/colors.dart';
import '../../../../../core/router/app_router.dart';
import '../../auth/bloc/logout/logout_bloc.dart';
import '../widgets/custome_textfield.dart';

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

  @override
  State<AccountPage> createState() => _AccountPageState();
}

class _AccountPageState extends State<AccountPage> {
  final _nameController = TextEditingController();
  final _emailController = TextEditingController();
  final _phoneController = TextEditingController();
  File? _foto;

  @override
  void initState() {
    super.initState();
    context.read<ProfileBloc>().add(const ProfileEvent.getProfile());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Akun'),
        actions: [
          IconButton(
            icon: const Icon(
              Icons.login_outlined,
              color: AppColors.primary,
            ),
            onPressed: () {
              showDialog(
                  context: context,
                  builder: (context) => const ShowDialogLogout());
            },
          ),
        ],
      ),
      body: BlocConsumer<ProfileBloc, ProfileState>(
        listener: (context, state) {
          state.maybeWhen(
            profileLoaded: (profile) {
              _nameController.text = profile['user']['name'];
              _emailController.text = profile['user']['email'];
              _phoneController.text = profile['user']['phone'];
            },
            profileUpdated: () {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Profile Berhasil di Perbarui'),
                  backgroundColor: AppColors.primary,
                ),
              );
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => const ProfilePage()));
            },
            error: (message) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(message),
                  backgroundColor: Colors.red,
                ),
              );
            },
            orElse: () {},
          );
        },
        builder: (context, state) {
          return state.maybeWhen(
            loading: () => const Center(child: CircularProgressIndicator()),
            profileLoaded: (_) => _buildProfileForm(context),
            orElse: () => const Center(child: CircularProgressIndicator()),
          );
        },
      ),
    );
  }

  Widget _buildProfileForm(BuildContext context) {
    return ListView(
      padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 20),
      children: [
        Container(
          padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 30),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            color: Colors.white,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Center(
                child: GestureDetector(
                    onTap: () async {
                      final pickedFile = await ImagePicker()
                          .pickImage(source: ImageSource.gallery);
                      if (pickedFile != null) {
                        setState(() {
                          _foto = File(pickedFile.path);
                        });
                      }
                    },
                    child: const SizedBox()
                    //  CircleAvatar(
                    //   radius: 60,
                    //   backgroundImage: _foto != null
                    //       ? FileImage(_foto!)
                    //       : const AssetImage('assets/images/img_friend4.png')
                    //           as ImageProvider,
                    // ),
                    ),
              ),
              // const SizedBox(height: 10),
              // const Text(
              //   "Ganti Foto Profile",
              //   style: TextStyle(
              //     fontWeight: FontWeight.w700,
              //     fontSize: 15,
              //   ),
              // ),
              const SizedBox(height: 12),
              CustomeTextField(
                title: "Nama",
                controller: _nameController,
              ),
              const SizedBox(height: 10),
              CustomeTextField(
                title: "Email",
                controller: _emailController,
              ),
              const SizedBox(height: 10),
              CustomeTextField(
                title: "No.HP",
                controller: _phoneController,
              ),
              const SizedBox(height: 50),
              SizedBox(
                width: double.infinity,
                height: 50,
                child: TextButton(
                  onPressed: () {
                    if (_nameController.text.isNotEmpty &&
                        _emailController.text.isNotEmpty &&
                        _phoneController.text.isNotEmpty) {
                      context
                          .read<ProfileBloc>()
                          .add(ProfileEvent.updateProfile(
                            name: _nameController.text,
                            email: _emailController.text,
                            phone: _phoneController.text,
                            foto: _foto,
                          ));
                    } else {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('All fields are required'),
                          backgroundColor: Colors.red,
                        ),
                      );
                    }
                  },
                  style: TextButton.styleFrom(
                    backgroundColor: AppColors.primary,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(56),
                    ),
                  ),
                  child: const Text(
                    "Edit",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

class ShowDialogLogout extends StatelessWidget {
  const ShowDialogLogout({super.key});

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 30),
      title: const Text(
        "Logout",
        style: TextStyle(
          color: AppColors.black,
          fontWeight: FontWeight.w700,
        ),
      ),
      content: const Text(
        "Apakah anda ingin logout ? ",
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text(
            'Cancel',
            style: TextStyle(
              color: AppColors.primary,
              fontWeight: FontWeight.w700,
            ),
          ),
        ),
        BlocConsumer<LogoutBloc, LogoutState>(
          listener: (context, state) {
            state.maybeWhen(
                orElse: () {},
                loaded: () {
                  context
                      .read<CheckoutBloc>()
                      .add(const CheckoutEvent.started());
                  ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                    content: Text('Logout Success'),
                    backgroundColor: AppColors.primary,
                  ));
                  context.goNamed(
                    RouteConstants.login,
                  );
                },
                error: (message) {
                  context
                      .read<CheckoutBloc>()
                      .add(const CheckoutEvent.started());
                  context.goNamed(
                    RouteConstants.login,
                  );
                });
          },
          builder: (context, state) {
            return state.maybeWhen(
              loading: () => const CircularProgressIndicator(),
              orElse: () => TextButton(
                  onPressed: () {
                    context.read<LogoutBloc>().add(const LogoutEvent.logout());
                  },
                  child: const Text(
                    'Logout',
                    style: TextStyle(
                      color: AppColors.primary,
                      fontWeight: FontWeight.w700,
                    ),
                  )),
            );
          },
        )
      ],
    );
  }
}
