import 'package:citycards_partner_flutter/core/app_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import '../blocs/scan_history/scan_history_bloc.dart';
import '../models/scan_history_model.dart';

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

  @override
  State<ScanHistoryPage> createState() => _ScanHistoryPageState();
}

class _ScanHistoryPageState extends State<ScanHistoryPage> {
  @override
  void initState() {
    super.initState();

    // ✅ API call when page opens
    context.read<ScanHistoryBloc>().add(const FetchScanHistoryEvent());
  }

  @override
  Widget build(BuildContext context) {
    return const _ScanHistoryView();
  }
}

class _ScanHistoryView extends StatelessWidget {
  const _ScanHistoryView();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        title: const Text(
          "Scan History",
          style: TextStyle(
            fontWeight: FontWeight.w600,
            fontSize: 32,
            color: Colors.black,
          ),
        ),
        leading: Padding(
          padding: const EdgeInsets.only(left: 12),
          child: InkWell(
            onTap: () => Navigator.pop(context),
            child: const CircleAvatar(
                maxRadius: 44,
                backgroundColor: Color(0xffF95F62),
                child: Icon(Icons.arrow_back, color: Colors.white)),
          ),
        ),
        actions: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0),
            child: InkWell(
              onTap: () => Navigator.pushNamed(context, AppRouter.profileScreen),
              child: Image.asset("assets/app/profile.png", scale: 4),
            ),
          ),
          const SizedBox(width: 2)
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: BlocBuilder<ScanHistoryBloc, ScanHistoryState>(
          builder: (context, state) {
            final bloc = context.read<ScanHistoryBloc>();

            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  "View a detailed log of all scanned QR codes, including timestamps, results, and customer details for easy tracking and verification.",
                  style: TextStyle(fontSize: 14, color: Colors.black, fontWeight: FontWeight.w400),
                ),
                const SizedBox(height: 16),

                // Filters
                Row(
                  children: [
                    // Date Filter
                    Expanded(
                      flex: 3,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text("Date", style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
                          const SizedBox(height: 4),
                          Container(
                            height: 40,
                            padding: const EdgeInsets.symmetric(horizontal: 10),
                            decoration: BoxDecoration(color: const Color(0xffF8F8F8), borderRadius: BorderRadius.circular(8)),
                            child: Row(
                              children: [
                                Expanded(
                                  child: Text(
                                    state.selectedDate == null ? "All" : DateFormat('dd/MM/yy').format(state.selectedDate!),
                                    style: const TextStyle(fontSize: 13),
                                  ),
                                ),
                                IconButton(
                                  padding: EdgeInsets.zero,
                                  constraints: const BoxConstraints(),
                                  icon: const Icon(Icons.calendar_month, color: Color(0xffF95F62), size: 20),
                                  onPressed: () async {
                                    final picked = await showDatePicker(
                                      context: context,
                                      initialDate: state.selectedDate ?? DateTime.now(),
                                      firstDate: DateTime(2020),
                                      lastDate: DateTime(2030),
                                      builder: (context, child) {
                                        return Theme(
                                          data: Theme.of(context).copyWith(
                                            colorScheme: const ColorScheme.light(
                                              primary: Color(0xffF95F62),       // header & selected day bg
                                              onPrimary: Colors.white,           // header text & selected day text
                                              onSurface: Colors.black,           // calendar day text
                                            ),
                                          ),
                                          child: child!,
                                        );
                                      },
                                    );
                                    if (picked != null) bloc.add(UpdateScanHistoryDateEvent(date: picked));
                                  },
                                ),
                                if (state.selectedDate != null)
                                  IconButton(
                                    padding: const EdgeInsets.only(left: 8),
                                    constraints: const BoxConstraints(),
                                    icon: const Icon(Icons.close, color: Colors.grey, size: 18),
                                    onPressed: () => bloc.add(const UpdateScanHistoryDateEvent(date: null)),
                                  ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 12),
                    // Status Filter
                    Expanded(
                      flex: 2,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text("Status", style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
                          const SizedBox(height: 4),
                          Container(
                            height: 40,
                            decoration: BoxDecoration(color: const Color(0xffF8F8F8), borderRadius: BorderRadius.circular(8)),
                            padding: const EdgeInsets.symmetric(horizontal: 10),
                            child: DropdownButtonHideUnderline(
                              child: DropdownButton<String>(
                                isExpanded: true,
                                value: state.selectedStatus,
                                icon: const Icon(Icons.keyboard_arrow_down, color: Color(0xffF95F62)),
                                items: const [
                                  DropdownMenuItem(value: 'all', child: Text("All", style: TextStyle(fontSize: 13))),
                                  DropdownMenuItem(value: 'success', child: Text("Success", style: TextStyle(fontSize: 13))),
                                  DropdownMenuItem(value: 'failed', child: Text("Failed", style: TextStyle(fontSize: 13))),
                                ],
                                onChanged: (val) {
                                  if (val != null) bloc.add(UpdateScanHistoryStatusEvent(status: val));
                                },
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 20),
                Expanded(child: _buildStateUI(state, context)),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildStateUI(ScanHistoryState state, BuildContext context) {
    if (state is ScanHistoryLoading) {
      return const Center(child: CircularProgressIndicator(color: Color(0xffF95F62)));
    } else if (state is ScanHistoryError) {
      return Center(child: Text(state.errorMessage));
    } 
    
    List<ScanHistory> displayItems = [];
    if (state is ScanHistoryLoaded) displayItems = state.filteredItems;
    else if (state is ScanHistoryDetailState) displayItems = state.filteredItems;

    if (displayItems.isEmpty && state is! ScanHistoryInitial) {
      return const Center(child: Text("No records found", style: TextStyle(color: Colors.black54)));
    }

    return RefreshIndicator(
      onRefresh: () async => context.read<ScanHistoryBloc>().add(const RefreshScanHistoryEvent()),
      child: ListView.builder(
        itemCount: displayItems.length,
        itemBuilder: (context, index) => _buildCard(displayItems[index], context),
      ),
    );
  }

  Widget _buildCard(ScanHistory item, BuildContext context) {
    final status = item.status.toLowerCase();
    Color bgColor = const Color(0xffE9F9EF);
    Color borderColor = const Color(0xffB5E5C1);
    IconData icon = Icons.check_circle;
    Color iconColor = const Color(0xff2DCC70);

    if (status == "failed") {
       bgColor = const Color(0xffFCEAEA);
       borderColor = const Color(0xffF5B1B1);
       icon = Icons.cancel;
       iconColor = const Color(0xffF95F62);
    } else if (status == "pending") {
       bgColor = Colors.orange.shade50;
       borderColor = Colors.orange.shade200;
       icon = Icons.pending;
       iconColor = Colors.orange;
    }

    return InkWell(
      onTap: () {
        context.read<ScanHistoryBloc>().add(SelectScanHistoryEvent(selectedItem: item));
        Navigator.pushNamed(context, AppRouter.scanHistoryDetailPage, arguments: item.id).then((_) {
          if (context.mounted) context.read<ScanHistoryBloc>().add(const ClearSelectedScanHistoryEvent());
        });
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: bgColor,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: borderColor),
        ),
        child: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("Pass ID: ${item.bookingNumber}", style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 13)),
                  const SizedBox(height: 4),
                  Text("Reason: ${item.reason}", style: const TextStyle(fontSize: 12, color: Colors.black87)),
                  const SizedBox(height: 4),
                  Text("Time: ${item.displayCreatedAt}", style: const TextStyle(fontSize: 12, color: Colors.black87)),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      Icon(icon, color: iconColor, size: 20),
                      const SizedBox(width: 6),
                      Text(item.status.toUpperCase(), style: const TextStyle(color: Colors.black, fontWeight: FontWeight.w600, fontSize: 24)),
                    ],
                  ),
                ],
              ),
            ),
            const Icon(Icons.qr_code_2_sharp, size: 78, color: Colors.black45),
          ],
        ),
      ),
    );
  }
}