import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/database/entities/defines.dart';
import 'package:vitalapp/database/entities/patient.dart';

import 'controller.dart';

final _tableColumnWidths = <int, TableColumnWidth>{
  0: const FixedColumnWidth(180),
  1: const FlexColumnWidth(),
  2: const FlexColumnWidth(),
  3: const FixedColumnWidth(220),
  4: const FixedColumnWidth(220),
};

class PatientSyncPage extends GetView<PatientSyncController> {
  const PatientSyncPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _TableHeader(),
        SingleChildScrollView(
          child: _buildDataTable(),
        ),
      ],
    );
  }

  Widget _buildDataTable() {
    return Obx(
      () {
        final children = <TableRow>[];
        for (var i = 0; i < controller.state.dataList.length; i++) {
          final entity = controller.state.dataList[i];
          children.add(_buildDataRow(entity, i));
        }
        return Table(
          children: children,
          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
          columnWidths: _tableColumnWidths,
        );
      },
    );
  }

  TableRow _buildDataRow(PatientEntity entity, int index) {
    return TableRow(
      decoration: index % 2 == 0
          ? null
          : const BoxDecoration(
              color: Color.fromRGBO(233, 244, 255, 1),
            ),
      children: [
        _buildDataCell(entity.id.toString()),
        _buildDataCell(entity.name),
        _buildDataCell(entity.syncType.getDescription()),
        _buildDataCell(entity.syncState.getDescription()),
        _buildDataCell(""),
      ],
    );
  }

  TableCell _buildDataCell(String title) {
    return TableCell(
      child: Container(
        alignment: Alignment.center,
        height: 37,
        child: Text(
          title,
          style: const TextStyle(fontSize: 14),
        ),
      ),
    );
  }
}

class _TableHeader extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Table(
      children: [
        TableRow(
          decoration: const BoxDecoration(
            color: Color.fromRGBO(215, 234, 255, 1),
          ),
          children: [
            _buildHeaderCell("ID"),
            _buildHeaderCell("姓名"),
            _buildHeaderCell("类型"),
            _buildHeaderCell("状态"),
            _buildHeaderCell("操作"),
          ],
        ),
      ],
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
      columnWidths: _tableColumnWidths,
    );
  }

  TableCell _buildHeaderCell(String title) {
    return TableCell(
      child: Container(
        alignment: Alignment.center,
        height: 37,
        child: Text(
          title,
          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}
