import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:vnoteapp/architecture/utils/datetime.dart';
import 'package:vnoteapp/components/button.dart';
import 'package:vnoteapp/components/dialog_date.dart';
import 'package:vnoteapp/components/dynamic_drawer.dart';
import 'package:vnoteapp/components/input.dart';
import 'package:vnoteapp/components/search_input.dart';
import 'package:vnoteapp/consts/rpc_enum_labels.dart';
import 'package:vnoteapp/consts/styles.dart';
import 'package:vnoteapp/managers/contract/index.dart';
import 'package:vnoteapp/pages/home/controller.dart';
import 'package:vnoteapp/pages/patient/list/widgets/status.dart';

import 'controller.dart';

class PatientListPage extends GetView<PatientListController> {
  const PatientListPage({super.key});

  @override
  Widget build(BuildContext context) {
    final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
    return Scaffold(
      key: scaffoldKey,
      body: Container(
        padding: const EdgeInsets.all(8),
        color: Colors.grey.shade200,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            _HeaderWidget(
              onFilterPressed: () {
                // Get.find<HomeController>()
                //     .homeScaffoldKey
                //     .currentState
                //     ?.openEndDrawer();

                VDynamicDrawerWrapper.show(
                  scaffoldKey: Get.find<HomeController>().homeScaffoldKey,
                  builder: (_) => _filterdrawer(context),
                );
                // scaffoldKey.currentState?.openEndDrawer();
              },
            ),
            const SizedBox(height: 20),
            Expanded(child: _buildListView()),
          ],
        ),
      ),
    );
  }

  VDrawer _filterdrawer(BuildContext context) {
    final scrollController = ScrollController();

    return VDrawer(
      width: 600,
      title: "筛选",
      scaffoldKey: Get.find<HomeController>().homeScaffoldKey,
      onConfirm: () {
        controller.reloadList(isFilter: true);
        VDynamicDrawerWrapper.hide(
          scaffoldKey: Get.find<HomeController>().homeScaffoldKey,
        );
      },
      child: Scrollbar(
        controller: scrollController,
        thumbVisibility: true,
        child: SingleChildScrollView(
          controller: scrollController,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '病人创建时间：',
                  style: TextStyle(fontSize: 20),
                ),
                const SizedBox(
                  height: 20,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Expanded(
                      child: Obx(
                        () => VInput(
                          readOnly: true,
                          controller: TextEditingController(
                            text: DateFormat('yyyy-MM-dd').format(
                              controller.state.startTime.value!.toLocal(),
                            ),
                          ),
                          radius: 4,
                          onTap: () async {
                            final result = await VDialogDate(
                              title: '起始时间',
                              initialValue: controller.state.startTime.value,
                            ).show();
                            controller.state.startTime.value = result;
                          },
                        ),
                      ),
                    ),
                    Container(
                        margin: const EdgeInsets.symmetric(horizontal: 16),
                        child: const Text('一')),
                    Expanded(
                      child: Obx(
                        () => VInput(
                          readOnly: true,
                          controller: TextEditingController(
                            text: DateFormat('yyyy-MM-dd').format(
                              controller.state.endTime.value!.toLocal(),
                            ),
                          ),
                          radius: 4,
                          onTap: () async {
                            final result = await VDialogDate(
                              title: '结束时间',
                              initialValue: controller.state.endTime.value,
                            ).show();
                            controller.state.startTime.value = result;
                          },
                        ),
                      ),
                    )
                  ],
                ),
                // Obx(
                //   () => VListFormCell(
                //     label: '起始时间',
                //     content: DateFormat('yyyy-MM-dd').format(
                //         controller.state.startTime.value ?? DateTime.now()),
                //     onTap: () async {
                //       final result = await VDialogDate(
                //         title: '服务日期',
                //         initialValue: controller.state.startTime.value,
                //       ).show();
                //       controller.state.startTime.value = result;
                //     },
                //   ),
                // ),
                // const Text(
                //   '起始时间',
                //   style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                // ),
                // const SizedBox(height: 8),
                // Row(
                //   children: [
                //     Expanded(
                //       child: Obx(
                //         () => VListFormCell(
                //           label: '起始时间',
                //           content: DateFormat('yyyy-MM-dd').format(
                //               controller.state.startTime.value ??
                //                   DateTime.now()),
                //           onTap: () async {
                //             final result = await VDialogDate(
                //               title: '服务日期',
                //               initialValue: controller.state.startTime.value,
                //             ).show();
                //             controller.state.startTime.value = result;
                //           },
                //         ),
                //       ),

                //       // Obx(
                //       //   () => VDatePicker(
                //       //     value: controller.state.startTime.value,
                //       //     onChanged: (value) {
                //       //       controller.state.startTime.value = value;
                //       //     },
                //       //   ),
                //       // ),
                //     ),
                //     const SizedBox(width: 8),
                //     Expanded(
                //       child: Obx(
                //         () => VDatePicker(
                //           value: controller.state.endTime.value,
                //           onChanged: (value) {
                //             controller.state.endTime.value = value;
                //           },
                //         ),
                //       ),
                //     ),
                //   ],
                // ),
                // const SizedBox(height: 16),
                // ElevatedButton(
                //   onPressed: () {
                //     controller.reloadList(isFilter: true);
                //     Navigator.of(context).pop();
                //   },
                //   child: const Text('确定'),
                // )
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildListView() {
    final scrollController = ScrollController();
    scrollController.addListener(
      () {
        // 如果滑动到底部
        try {
          if (scrollController.position.atEdge) {
            if (scrollController.position.pixels != 0) {
              if (controller.state.hasNextPage) {
                controller.loadNextPageList();
              }
            }
          }
        } catch (e) {
          // logger.e("listViewScrollController exception:", e);
        }
      },
    );
    return RefreshIndicator(
      onRefresh: () async {
        controller.reloadList();
      },
      child: Obx(
        () {
          final list = controller.state.dataList;
          final children = <Widget>[];
          for (var i = 0; i < list.length; i++) {
            children.add(_PatientCard(dto: list[i]));
          }
          return Scrollbar(
            trackVisibility: true,
            controller: scrollController,
            child: GridView(
              shrinkWrap: true,
              controller: scrollController,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                mainAxisSpacing: 16,
                crossAxisSpacing: 20,
                childAspectRatio: 360 / 180,
              ),
              children: children,
            ),
          );
        },
      ),
    );
  }
}

class _HeaderWidget extends GetView<PatientListController> {
  final VoidCallback onFilterPressed;

  const _HeaderWidget({
    required this.onFilterPressed,
  });
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 76,
      child: Row(
        children: [
          Expanded(
            child: SizedBox(
              height: 70,
              child: VSearchInput(
                placeholder: "身份证号码/姓名/手机号",
                onSearch: (value) {
                  controller.state.searchString = value;
                  controller.reloadList();
                },
              ),
            ),
          ),
          const SizedBox(width: 8),
          SizedBox(
            width: 180,
            height: 70,
            child: VButton(
              child: const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.note_add_outlined, size: 24),
                  Text("新建档案", style: TextStyle(fontSize: 20)),
                ],
              ),
              onTap: () {
                controller.onCreateClicked();
              },
            ),
          ),
          const SizedBox(width: 8),
          SizedBox(
            width: 180,
            height: 70,
            child: VButton(
              onTap: onFilterPressed,
              child: const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.filter_alt, size: 24),
                  Text("筛选", style: TextStyle(fontSize: 20)),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _PatientCard extends StatelessWidget {
  final PatientDTO dto;

  const _PatientCard({required this.dto});

  @override
  Widget build(BuildContext context) {
    final body = Stack(
      children: [
        Container(
          padding: const EdgeInsets.symmetric(
            horizontal: 16,
            vertical: 12,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 8),
              LayoutBuilder(
                builder: (context, c) {
                  final width = c.maxWidth - 80 - 20;
                  // 不和状态标签重叠，并保持一定距离
                  return SizedBox(width: width, child: _buildBaseInfoRow());
                },
              ),
              const SizedBox(height: 12),
              _buildClassTags(),
            ],
          ),
        ),
        Positioned(
          top: 0,
          right: 0,
          child: _PatientSignStatusTag(
            dto: dto,
          ),
        ),
      ],
    );
    return Material(
      borderRadius: GlobalStyles.borderRadius,
      child: Ink(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: GlobalStyles.borderRadius,
        ),
        child: InkWell(
          borderRadius: GlobalStyles.borderRadius,
          onTap: () {
            Get.find<PatientListController>().gotoDetail(dto.code!);
          },
          child: body,
        ),
      ),
    );
  }

  Widget _buildBaseInfoRow() {
    final birthday = dto.birthday!.toLocal();
    final age = DataTimeUtils.calculateAge(birthday);
    return Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(
          width: 100,
          child: Text(
            dto.patientName!,
            style: const TextStyle(
              color: Colors.black,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        Expanded(
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Expanded(
                child: Text(
                  RpcEnumLabels.gender[dto.patientGender] ?? "未知",
                  style: const TextStyle(
                    color: Colors.grey,
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              Expanded(
                child: Text(
                  "$age岁",
                  style: const TextStyle(
                    color: Colors.grey,
                    fontSize: 20,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildClassTags() {
    fn(String x) => Text(
          x,
          style: const TextStyle(color: Colors.grey, fontSize: 18),
        );
    return ConstrainedBox(
      constraints: const BoxConstraints(minWidth: double.infinity),
      child: Wrap(
        alignment: WrapAlignment.start,
        spacing: 20,
        runSpacing: 8,
        children: (dto.labelNames ?? []).map((e) => fn(e)).toList(),
      ),
    );
  }
}

class _PatientSignStatusTag extends StatelessWidget {
  final PatientDTO dto;
  _PatientSignStatusTag({required this.dto});
  final ContractUtils _contractUtils = ContractUtils();

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerRight,
      width: 120,
      padding: const EdgeInsets.only(top: 18),
      child: StatusLabel(
        title: _contractUtils.contractStateTransition(dto.contractState),
        color: _contractUtils.contractStateColors(dto.contractState),
      ),
    );
  }
}
