import 'package:flutter/material.dart';
import 'package:fotodocumentation/controller/base_controller.dart';
import 'package:fotodocumentation/controller/customer_controller.dart';
import 'package:fotodocumentation/dto/customer_dto.dart';
import 'package:fotodocumentation/l10n/app_localizations.dart';
import 'package:fotodocumentation/pages/ui_utils/component/general_error_widget.dart';
import 'package:fotodocumentation/pages/ui_utils/component/page_header_widget.dart';
import 'package:fotodocumentation/pages/ui_utils/component/search_bar_widget.dart';
import 'package:fotodocumentation/pages/ui_utils/component/waiting_widget.dart';
import 'package:fotodocumentation/pages/ui_utils/general_style.dart';
import 'package:fotodocumentation/utils/di_container.dart';
import 'package:fotodocumentation/utils/global_router.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';

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

  @override
  State<CustomerListWidget> createState() => _CustomerListWidgetState();
}

class _CustomerListWidgetState extends State<CustomerListWidget> {
  CustomerController get _customerController => DiContainer.get();
  GeneralStyle get _generalStyle => DiContainer.get();

  final _searchController = TextEditingController();
  late Future<List<CustomerListDto>> _dtos;
  String? _selectedLetter;
  late DateFormat _dateFormat;

  @override
  void initState() {
    super.initState();
    _dateFormat = DateFormat('dd MMMM yyyy');
    _dtos = _customerController.getAll(_searchController.text, "");
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _body(context),
    );
  }

  Widget _body(BuildContext context) {
    return Container(
      color: _generalStyle.pageBackgroundColor,
      child: Padding(
        padding: const EdgeInsets.only(top: 8.0, left: 50.0, right: 50.0, bottom: 8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            PageHeaderWidget(text: AppLocalizations.of(context)!.customerListHeadline),
            _abcHeaderBar(),
            FractionallySizedBox(
              widthFactor: 0.5,
              alignment: Alignment.centerLeft,
              child: SearchBarWidget(
                searchController: _searchController,
                onSearch: (text) async => actionSearch(text),
              ),
            ),
            Expanded(
              child: _customerListWidget(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _customerListWidget() {
    return FutureBuilder<List<CustomerListDto>>(
      future: _dtos,
      builder: (BuildContext context, AsyncSnapshot<List<CustomerListDto>> snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return const WaitingWidget();
        }
        if (snapshot.hasData) {
          List<CustomerListDto> dtos = snapshot.data ?? [];

          return _listWidget(dtos);
        } else if (snapshot.hasError) {
          var error = snapshot.error;
          return (error is ServerError) ? GeneralErrorWidget.fromServerError(error) : GeneralErrorWidget(error: snapshot.error.toString());
        }
        return const WaitingWidget();
      },
    );
  }

  Widget _listWidget(List<CustomerListDto> dtos) {
    if (dtos.isEmpty) {
      return Text(AppLocalizations.of(context)!.customerListEmpty,
          style: TextStyle(
            fontFamily: _generalStyle.fontFamily,
            fontWeight: FontWeight.bold,
            fontSize: 20,
            color: _generalStyle.secondaryWidgetBackgroundColor,
          ));
    }
    return Card(
      margin: EdgeInsets.zero,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          _tableHeaderRow(context),
          Divider(thickness: 2, height: 1, color: _generalStyle.secondaryWidgetBackgroundColor),
          Expanded(
            child: ListView.separated(
              padding: const EdgeInsets.all(0),
              itemCount: dtos.length,
              itemBuilder: (BuildContext context, int index) {
                return _tableDataRow(context, dtos[index]);
              },
              separatorBuilder: (BuildContext context, int index) => Divider(
                color: _generalStyle.secondaryWidgetBackgroundColor,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _tableHeaderRow(BuildContext context) {
    final headerStyle = TextStyle(
      fontFamily: _generalStyle.fontFamily,
      fontWeight: FontWeight.bold,
      fontSize: 20,
      color: _generalStyle.secondaryWidgetBackgroundColor,
    );

    final headerStyleSuffix = TextStyle(
      fontFamily: _generalStyle.fontFamily,
      fontWeight: FontWeight.normal,
      fontSize: 20,
      color: _generalStyle.secondaryWidgetBackgroundColor,
    );
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        children: [
          const SizedBox(width: 48),
          Expanded(
            flex: 1,
            child: Text(
              AppLocalizations.of(context)!.customerListHeaderCustomerNumber,
              style: headerStyle,
            ),
          ),
          Expanded(
            flex: 3,
            child: Text(
              AppLocalizations.of(context)!.customerListHeaderName,
              style: headerStyle,
            ),
          ),
          Expanded(
            flex: 2,
            child: Wrap(
              children: [
                Text(
                  AppLocalizations.of(context)!.customerListHeaderLastDate,
                  style: headerStyle,
                ),
                Text(
                  AppLocalizations.of(context)!.customerListHeaderLastDateSuffix,
                  style: headerStyleSuffix,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _tableDataRow(BuildContext context, CustomerListDto dto) {
    final dataStyle = TextStyle(
      fontFamily: _generalStyle.fontFamily,
      fontSize: 16.0,
      color: _generalStyle.secondaryTextLabelColor,
    );

    final dateStr = dto.lastUpdateDate == null ? "" : _dateFormat.format(dto.lastUpdateDate!);
    return InkWell(
      onTap: () => _actionSelect(context, dto),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
        child: Row(
          children: [
            SizedBox(
              width: 48,
              child: Icon(Icons.folder_open_outlined, color: _generalStyle.secondaryWidgetBackgroundColor),
            ),
            Expanded(
              flex: 1,
              child: Text(dto.customerNumber, style: dataStyle),
            ),
            Expanded(
              flex: 3,
              child: Text(dto.name, style: dataStyle),
            ),
            Expanded(
              flex: 2,
              child: Text(dateStr, style: dataStyle),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> actionSearch(String text) async {
    _reloadData();
  }

  Future<void> _actionSelect(BuildContext context, CustomerListDto dto) async {
    context.go("${GlobalRouter.pathCustomer}/${dto.id}");
  }

  void _reloadData() {
    _dtos = _customerController.getAll(_searchController.text, _selectedLetter ?? "");
    setState(() {});
  }

  Widget _abcHeaderBar() {
    const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Wrap(
        spacing: 8,
        runSpacing: 8,
        children: letters.split('').map((letter) {
          final isSelected = _selectedLetter == letter;
          return InkWell(
            onTap: () {
              setState(() {
                _selectedLetter = isSelected ? null : letter;
                _reloadData();
              });
            },
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                color: isSelected ? _generalStyle.secondaryWidgetBackgroundColor : Colors.white,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                letter,
                style: TextStyle(
                  fontFamily: _generalStyle.fontFamily,
                  fontWeight: FontWeight.bold,
                  fontSize: 20.0,
                  color: isSelected ? Colors.white : _generalStyle.secondaryWidgetBackgroundColor,
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}
