import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:ui_loker/Model/locker_model.dart';
import 'package:ui_loker/Model/penitipan_model.dart';
import 'package:ui_loker/Service/api_service.dart';

class RiwayatTab extends StatefulWidget {
  @override
  _RiwayatTabState createState() => _RiwayatTabState();
}

class _RiwayatTabState extends State<RiwayatTab> {
  List<LockerModel> _lokers = [];
  bool _loading = true;

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

  Future<void> fetchLokers() async {
    try {
      final response = await ApiService.getAllLockers();
      setState(() {
        _lokers = response;
        _loading = false;
      });
    } catch (e) {
      print('Error fetching lockers: $e');
      setState(() {
        _loading = false;
      });
    }
  }

  void showRiwayatPenitipan(BuildContext context, int lokerId) async {
    try {
      final data = await ApiService.getPenitipanByLoker(lokerId);

      showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        builder: (_) {
          return Padding(
            padding: EdgeInsets.all(16),
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: data.map((item) {
                  final format = DateFormat('dd MMM yyyy HH:mm:ss');
                  return Card(
                    margin: EdgeInsets.only(bottom: 12),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    elevation: 4,
                    child: Padding(
                      padding: EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Icon(Icons.person, color: Colors.blue),
                              SizedBox(width: 8),
                              Expanded(
                                child: Text(
                                  item.nama,
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 12),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              InfoItem(
                                icon: Icons.timer,
                                label: 'Durasi',
                                value: item.durasiMenit != null 
                                        ?'${item.durasiMenit} Detik' 
                                        : '- Detik',
                              ),
                              InfoItem(
                                icon: Icons.attach_money,
                                label: 'Tarif',
                                value: item.biaya != null
                                        ?'Rp.${item.biaya}'
                                        : 'Rp.-',
                              ),
                            ],
                          ),
                          SizedBox(height: 12),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              InfoItem(
                                icon: Icons.play_arrow,
                                label: 'Mulai',
                                value:
                                    item.waktuMulai != null
                                      ? format.format(item.waktuMulai! as DateTime)
                                      : 'Belum dimulai',
                              ),
                              InfoItem(
                                icon: Icons.stop,
                                label: 'Selesai',
                                value:
                                    item.waktuSelesai != null
                                      ? format.format(item.waktuSelesai! as DateTime)
                                      : 'Belum selesai',
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  );
                }).toList(),
              ),
            ),
          );
        },
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Gagal memuat riwayat: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return Center(child: CircularProgressIndicator());
    }

    if (_lokers.isEmpty) {
      return Center(child: Text("Belum ada riwayat loker."));
    }

    return ListView.builder(
      padding: EdgeInsets.all(16),
      itemCount: _lokers.length,
      itemBuilder: (context, index) {
        final locker = _lokers[index];
        return GestureDetector(
          onTap: () => showRiwayatPenitipan(context, locker.id),
          child: Container(
            margin: EdgeInsets.only(bottom: 16),
            padding: EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: Colors.black12,
                  blurRadius: 6,
                  offset: Offset(2, 2),
                ),
              ],
            ),
            child: Row(
              children: [
                Icon(Icons.history, color: Colors.pink),
                SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "Riwayat Loker ${locker.nomorLoker ?? locker.id}",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                      SizedBox(height: 4),
                      Text("Status: ${locker.status}"),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

class InfoItem extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;

  const InfoItem({
    Key? key,
    required this.icon,
    required this.label,
    required this.value,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, size: 20, color: Colors.grey[700]),
          SizedBox(width: 6),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(label,
                    style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                        fontWeight: FontWeight.w500)),
                SizedBox(height: 2),
                Text(value,
                    style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
