import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../application/customer/customer_loader/customer_loader_bloc.dart';
import '../../../../../common/extension/extension.dart';
import '../../../../../common/theme/theme.dart';
import '../../../../../domain/customer/customer.dart';
import '../../../../../injection.dart';
import '../../../../components/border/dashed_border.dart';
import '../../../../components/card/customer_card.dart';
import '../../../../components/card/error_card.dart';
import '../../../../components/loader/loader_with_text.dart';
import '../../../../components/page/page_title.dart';
import '../../../../components/spaces/space.dart';

@RoutePage()
class CustomerPage extends StatelessWidget implements AutoRouteWrapper {
  const CustomerPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.background,
      body: BlocBuilder<CustomerLoaderBloc, CustomerLoaderState>(
        builder: (context, state) {
          return Row(
            children: [
              Expanded(
                flex: 2,
                child: Material(
                  color: AppColor.white,
                  child: Column(
                    children: [
                      const PageTitle(title: 'Daftar Pelanggan'),
                      Expanded(
                        child: state.isFetching
                            ? const Center(child: LoaderWithText())
                            : state.failureOrOption.fold(
                                () => ListView.builder(
                                  itemCount: state.customers.length,
                                  itemBuilder: (context, index) {
                                    final customer = state.customers[index];
                                    return CustomerCard(
                                      customer: customer,
                                      isActive:
                                          customer == state.selectedCustomer,
                                      onTap: () {
                                        context.read<CustomerLoaderBloc>().add(
                                          CustomerLoaderEvent.setSelectedCustomer(
                                            customer,
                                          ),
                                        );
                                      },
                                    );
                                  },
                                ),
                                (f) => _buildErrorState(f, context),
                              ),
                      ),
                    ],
                  ),
                ),
              ),
              Expanded(
                flex: 4,
                child: state.selectedCustomer == null
                    ? Center(
                        child: Text(
                          "Belum ada pelanggan yang dipilih.",
                          style: AppStyle.lg.copyWith(
                            fontSize: 16.0,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      )
                    : Center(
                        child: Container(
                          width: context.deviceHeight * 0.5,
                          height: context.deviceHeight * 0.6,
                          decoration: BoxDecoration(
                            color: AppColor.white,
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Column(
                            children: [
                              Padding(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 12.0,
                                  vertical: 16.0,
                                ),
                                child: Column(
                                  children: [
                                    const CircleAvatar(
                                      radius: 24,
                                      backgroundColor: AppColor.primary,
                                      child: Icon(
                                        Icons.person,
                                        color: Colors.white,
                                      ),
                                    ),
                                    const SizedBox(height: 12),
                                    Text(
                                      state.selectedCustomer?.name ?? "",
                                      style: const TextStyle(
                                        fontSize: 16.0,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const DashedDivider(color: AppColor.border),
                              Padding(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 12.0,
                                  vertical: 16.0,
                                ),
                                child: Column(
                                  children: [
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        const Text(
                                          'No. Handphone',
                                          style: TextStyle(fontSize: 12.0),
                                        ),
                                        Text(
                                          (state
                                                      .selectedCustomer
                                                      ?.phone
                                                      .isEmpty ??
                                                  true)
                                              ? "-"
                                              : state.selectedCustomer?.phone ??
                                                    "-",
                                          style: const TextStyle(
                                            fontSize: 12.0,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                      ],
                                    ),
                                    const SpaceHeight(8),
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        const Text(
                                          'Email',
                                          style: TextStyle(fontSize: 12.0),
                                        ),
                                        Text(
                                          (state
                                                      .selectedCustomer
                                                      ?.email
                                                      .isEmpty ??
                                                  true)
                                              ? "-"
                                              : state.selectedCustomer?.email ??
                                                    "-",
                                          style: const TextStyle(
                                            fontSize: 12.0,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                      ],
                                    ),
                                    const SpaceHeight(8),
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        const Text(
                                          'Alamat',
                                          style: TextStyle(fontSize: 12.0),
                                        ),
                                        Text(
                                          (state
                                                      .selectedCustomer
                                                      ?.address
                                                      .isEmpty ??
                                                  true)
                                              ? "-"
                                              : state
                                                        .selectedCustomer
                                                        ?.address ??
                                                    "-",
                                          style: const TextStyle(
                                            fontSize: 12.0,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildErrorState(CustomerFailure f, BuildContext context) {
    return f.maybeMap(
      orElse: () => ErrorCard(
        title: "Pelanggan",
        message: "Terjadi kesalahan saat memuat pelanggan",
        onTap: () {
          context.read<CustomerLoaderBloc>().add(
            const CustomerLoaderEvent.fetched(isRefresh: true),
          );
        },
      ),
      empty: (value) => ErrorCard(
        title: "Pelanggan",
        message: "Pelanggan masih kosong, silahkan tambahkan pelanggan",
        onTap: () {
          context.read<CustomerLoaderBloc>().add(
            const CustomerLoaderEvent.fetched(isRefresh: true),
          );
        },
      ),
      serverError: (value) => ErrorCard(
        title: "Pelanggan",
        message: "Terjadi kesalahan saat memuat pelanggan",
        onTap: () {
          context.read<CustomerLoaderBloc>().add(
            const CustomerLoaderEvent.fetched(isRefresh: true),
          );
        },
      ),
      dynamicErrorMessage: (value) => ErrorCard(
        title: "Pelanggan",
        message: value.erroMessage,
        onTap: () {
          context.read<CustomerLoaderBloc>().add(
            const CustomerLoaderEvent.fetched(isRefresh: true),
          );
        },
      ),
      unexpectedError: (value) => ErrorCard(
        title: "Pelanggan",
        message: "Terjadi kesalahan saat memuat pelanggan",
        onTap: () {
          context.read<CustomerLoaderBloc>().add(
            const CustomerLoaderEvent.fetched(isRefresh: true),
          );
        },
      ),
    );
  }

  @override
  Widget wrappedRoute(BuildContext context) => BlocProvider(
    create: (context) =>
        getIt<CustomerLoaderBloc>()
          ..add(const CustomerLoaderEvent.fetched(isRefresh: true)),
    child: this,
  );
}
