import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:intl/intl.dart';
import 'package:pharmacy_mobile/functions/getlist_cache_function.dart';
import 'package:pharmacy_mobile/tables/stocks.dart';
import 'package:pharmacy_mobile/widgets/datatable_widget.dart';
import 'package:pharmacy_mobile/widgets/page_background_widget.dart';
import 'package:pharmacy_mobile/widgets/text_widget.dart';
import 'package:pharmacy_mobile/widgets/title_widget.dart';

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

  @override
  State<ListStocksPage> createState() => _ListStocksPageState();
}

class _ListStocksPageState extends State<ListStocksPage> {
  final _stocks = Stocks();

  late List _stockList = [];
  bool _isLoading = false;

  List<DataRow> _createRows() {
    final today = DateTime.now().toUtc();

    return _stockList.map((item) {
      final dateString = item['expiration_date'];
      final date = DateTime.parse(dateString).toUtc();
      final formattedDate = DateFormat('MMMM d, yyyy').format(date);

      if (date.isBefore(today)) {
        return DataRow(
          cells: [
            DataCell(Text(item['medicine_name'], style: const TextStyle(color: Color.fromRGBO(188, 59, 50, 1)))),
            DataCell(Text(item['quantity'].toString(), style: const TextStyle(color: Color.fromRGBO(188, 59, 50, 1)))),
            DataCell(
              Text(formattedDate,
                  style: const TextStyle(color: Color.fromRGBO(188, 59, 50, 1))), // Highlight expired items
            ),
          ],
        );
      } else {
        return DataRow(
          cells: [
            DataCell(Text(item['medicine_name'])),
            DataCell(Text(item['quantity'].toString())),
            DataCell(Text(formattedDate)),
          ],
        );
      }
    }).toList();
  }

  List<DataColumn> _createColumns() {
    return [
      const DataColumn(label: Text('Medicine')),
      const DataColumn(label: Text('Quantity')),
      const DataColumn(label: Text('Expiration'))
    ];
  }

  void autoRun() async {
    setState(() {
      _isLoading = true;
    });

    final cache = await getListCache(context, 'stock');

    if (cache.isNotEmpty) {
      _stockList = cache;
    } else {
      _stockList = await _stocks.getList();
    }

    setState(() {
      _isLoading = false;
    });
  }

  @override
  void initState() {
    autoRun();
    super.initState();
  }

  @override
  void dispose() {
    _stockList = [];
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageBackgroundWidget(
        child: Column(
          children: [
            const Gap(96),
            const TitleWidget(
              firstTextSize: 14,
              secondTextSize: 24,
              logoSize: 90,
            ),
            const Gap(32),
            const TextWidget(
              text: 'List of Stocks',
              title: true,
            ),
            const Gap(16),
            if (_isLoading)
              const Center(
                  child: CircularProgressIndicator(
                color: Color.fromRGBO(255, 255, 255, 1),
              ))
            else if (_stockList.isEmpty)
              Container(
                  decoration: BoxDecoration(
                    border: Border.all(color: const Color.fromRGBO(205, 59, 208, 0.702), width: 2),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16.0),
                  child: const TextWidget(
                    text: 'No Stock Listed',
                    size: 14,
                  ))
            else
              DataTableWidget(
                column: _createColumns(),
                row: _createRows(),
              ),
          ],
        ),
      ),
    );
  }
}
