import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/style.dart';

class _HeaderColumn extends StatelessWidget {
  final String title;
  final double width;
  final bool showFilter;
  final VoidCallback? onFilter;
  final Function(double) onResize;

  const _HeaderColumn({
    required this.title,
    required this.width,
    required this.showFilter,
    required this.onResize,
    this.onFilter,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      cursor: SystemMouseCursors.resizeColumn,
      child: GestureDetector(
        onHorizontalDragUpdate: (details) => onResize(details.delta.dx),
        child: Container(
          width: width,
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          decoration: const BoxDecoration(
            border: Border(right: BorderSide(color: ColorsManager.boxDivider)),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Text(
                  title,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    fontWeight: FontWeight.w400,
                    fontSize: 13,
                    color: ColorsManager.grayColor,
                  ),
                ),
              ),
              if (showFilter)
                IconButton(
                  icon: SvgPicture.asset(Assets.filterTableIcon),
                  onPressed: onFilter,
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
            ],
          ),
        ),
      ),
    );
  }
}

class _TableRow extends StatelessWidget {
  final List<Widget> cells;
  final List<double> columnWidths;
  final bool isLast;

  const _TableRow({
    required this.cells,
    required this.columnWidths,
    required this.isLast,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            for (int i = 0; i < cells.length; i++)
              Container(
                width: columnWidths[i],
                padding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                // decoration: BoxDecoration(
                //   border: Border(
                //     right: BorderSide(color: ColorsManager.boxDivider),
                //   ),
                // ),
                child: cells[i],
              ),
          ],
        ),
        if (!isLast)
          const Divider(
            height: 1,
            thickness: 1,
            color: ColorsManager.boxDivider,
          ),
      ],
    );
  }
}
//===========================================================================

class DynamicTableScreen extends StatefulWidget {
  final List<String> titles;
  final List<List<Widget>> rows;
  final void Function(int columnIndex)? onFilter;
  final double tableSize;

  const DynamicTableScreen({
    required this.titles,
    required this.rows,
    required this.onFilter,
    Key? key,
    required this.tableSize,
  }) : super(key: key);

  @override
  _DynamicTableScreenState createState() => _DynamicTableScreenState();
}

class _DynamicTableScreenState extends State<DynamicTableScreen> {
  late List<double> columnWidths;
  final double _minColumnWidth = 100.0;
  final double _maxColumnWidth = 300.0;
  final double _dividerWidth = 1.0;
  double _lastAvailableWidth = 0;

  @override
  void initState() {
    super.initState();
    columnWidths = List.filled(widget.titles.length, _minColumnWidth);
  }

  void _handleColumnResize(int index, double delta) {
    setState(() {
      double newWidth = columnWidths[index] + delta;
      newWidth = newWidth.clamp(_minColumnWidth, _maxColumnWidth);
      double actualDelta = newWidth - columnWidths[index];
      if (actualDelta == 0) return;

      int nextIndex = (index + 1) % columnWidths.length;
      columnWidths[index] = newWidth;
      columnWidths[nextIndex] = (columnWidths[nextIndex] - actualDelta)
          .clamp(_minColumnWidth, _maxColumnWidth);
    });
  }

  Widget _buildHeader() {
    return Container(
      decoration: containerDecoration.copyWith(
        color: ColorsManager.circleRolesBackground,
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(15),
          topRight: Radius.circular(15),
        ),
      ),
      child: Row(
        children: [
          for (int i = 0; i < widget.titles.length; i++)
            _HeaderColumn(
              title: widget.titles[i],
              width: columnWidths[i],
              showFilter: i != 1 && i != 9 && i != 8 && i != 5,
              onFilter: () => widget.onFilter?.call(i),
              onResize: (delta) => _handleColumnResize(i, delta),
            ),
        ],
      ),
    );
  }

  Widget _buildBody() {
    if (widget.rows.isEmpty) {
      return SizedBox(
        height: 300,
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SvgPicture.asset(Assets.emptyTable),
              const SizedBox(height: 15),
              const Text(
                'No Users',
                style: TextStyle(
                  color: ColorsManager.lightGrayColor,
                  fontSize: 16,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ],
          ),
        ),
      );
    }

    return Container(
      decoration: containerDecoration.copyWith(
        color: ColorsManager.whiteColors,
        borderRadius: const BorderRadius.only(
          bottomLeft: Radius.circular(15),
          bottomRight: Radius.circular(15),
        ),
      ),
      child: ListView(
        shrinkWrap: true,
        children: [
          for (int rowIndex = 0; rowIndex < widget.rows.length; rowIndex++)
            _TableRow(
              cells: widget.rows[rowIndex],
              columnWidths: columnWidths,
              isLast: rowIndex == widget.rows.length - 1,
            ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final availableWidth = constraints.maxWidth;
        final totalDividersWidth = (widget.titles.length - 1) * _dividerWidth;

        if (_lastAvailableWidth != availableWidth) {
          final equalWidth =
              (availableWidth - totalDividersWidth) / widget.titles.length;
          final clampedWidth =
              equalWidth.clamp(_minColumnWidth, _maxColumnWidth);

          WidgetsBinding.instance.addPostFrameCallback((_) {
            setState(() {
              columnWidths = List.filled(widget.titles.length, clampedWidth);
              _lastAvailableWidth = availableWidth;
            });
          });
        }

        final totalTableWidth =
            columnWidths.fold(0.0, (sum, w) => sum + w) + totalDividersWidth;
        return SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Container(
            width: totalTableWidth,
            decoration: containerDecoration.copyWith(
              color: ColorsManager.whiteColors,
              borderRadius: const BorderRadius.all(Radius.circular(20)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildHeader(),
                Container(height: widget.tableSize - 37, child: _buildBody()),
              ],
            ),
          ),
        );
      },
    );
  }
}
