import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import '../blocs/scan_history_bloc.dart';
import '../repositories/scan_history_repository.dart';
import '../viewmodels/scan_history_viewmodel.dart';
import '../models/scan_history_model.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => ScanHistoryBloc(
        viewModel: ScanHistoryViewModel(repository: ScanHistoryRepository()),
      )..add(LoadScanHistory()),
      child: 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: Text(
          "Scan History",
          style: GoogleFonts.poppins(
            fontWeight: FontWeight.w700,
            color: Colors.black,
          ),
        ),
        leading: const Padding(
          padding: EdgeInsets.only(left: 12),
          child: CircleAvatar(
            maxRadius: 44,
            backgroundColor: Color(0xffF95F62),
              child: Icon(Icons.arrow_back, color: Colors.white)),
        ),
        actions: const [
          Padding(
            padding: EdgeInsets.only(right: 12),
            child: Icon(Icons.account_circle, color: Color(0xffF95F62)),
          ),
        ],
      ),
      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: [
                Text(
                  "View a detailed log of all scanned QR codes, including timestamps, results, and customer details for easy tracking and verification.",
                  style: GoogleFonts.poppins(
                    fontSize: 14,
                    color: Colors.black,fontWeight: FontWeight.w400
                  ),
                ),
                const SizedBox(height: 16),

                // Date + Status Row
                Row(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        onTap: () async {
                          final picked = await showDatePicker(
                            context: context,
                            initialDate: state.selectedDate,
                            firstDate: DateTime(2020),
                            lastDate: DateTime(2030),
                            builder: (context, child) {
                              return Theme(
                                data: Theme.of(context).copyWith(
                                  colorScheme: const ColorScheme.light(
                                    primary: Color(0xffF95F62),
                                  ),
                                ),
                                child: child!,
                              );
                            },
                          );
                          if (picked != null) {
                            bloc.add(UpdateDate(picked));
                          }
                        },
                        child: Row(
                          children: [
                            Text("Date",
                                style: GoogleFonts.poppins(
                                    fontSize: 13, color: Colors.black,fontWeight: FontWeight.w400)),
                            const SizedBox(width: 12),
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                              decoration: BoxDecoration(
                                color: const Color(0xffF8F8F8),
                                borderRadius: BorderRadius.circular(50),
                              ),
                              child: Row(
                                children: [
                                  const Icon(Icons.calendar_month,
                                      color: Color(0xffF95F62), size: 18),
                                  const SizedBox(width: 8),
                                  Text(
                                    "${state.selectedDate.day.toString().padLeft(2, '0')}/${state.selectedDate.month.toString().padLeft(2, '0')}/${state.selectedDate.year.toString().substring(2)}",
                                    style: GoogleFonts.poppins(fontSize: 13),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),

                    // Status Dropdown
                    Expanded(
                      child: Row(
                        children: [
                          Text("Status",
                              style: GoogleFonts.poppins(
                                  fontSize: 14, color: Colors.black,fontWeight: FontWeight.w400)),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Container(
                              decoration: BoxDecoration(
                                color: const Color(0xffF8F8F8),
                                borderRadius: BorderRadius.circular(50),
                              ),
                              padding: const EdgeInsets.symmetric(horizontal: 12),
                              child: DropdownButtonHideUnderline(
                                child: DropdownButton<String>(
                                  isExpanded: true,
                                  dropdownColor: Colors.white,
                                  value: state.selectedStatus,
                                  icon: const Icon(Icons.keyboard_arrow_down_rounded,size: 26,
                                      color: Color(0xffF95F62)),
                                  items: const [
                                    DropdownMenuItem(
                                        value: 'All Status',
                                        child: Text("All Status")),
                                    DropdownMenuItem(
                                        value: 'Failed', child: Text("Failed")),
                                    DropdownMenuItem(
                                        value: 'Success',
                                        child: Text("Success")),
                                  ],
                                  onChanged: (val) {
                                    if (val != null) bloc.add(UpdateStatus(val));
                                  },
                                  style: GoogleFonts.poppins(
                                      fontSize: 14, color: Colors.black,fontWeight: FontWeight.w400),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 20),

                // Data Section
                Expanded(child: _buildStateUI(state)),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildStateUI(ScanHistoryState state) {
    if (state.isLoading) {
      return const Center(
        child: CircularProgressIndicator(color: Color(0xffF95F62)),
      );
    } else if (state.error != null) {
      return Center(child: Text(state.error!));
    } else if (state.history.isEmpty) {
      return Center(
        child: Text("No records found",
            style: GoogleFonts.poppins(color: Colors.black54)),
      );
    }

    return ListView.builder(
      itemCount: state.history.length,
      itemBuilder: (context, index) {
        final item = state.history[index];
        return _buildCard(item);
      },
    );
  }

  Widget _buildCard(ScanHistoryModel item) {
    final isSuccess = item.status == "Success";
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: isSuccess ? const Color(0xffE9F9EF) : const Color(0xffFCEAEA),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
            color: isSuccess ? const Color(0xffB5E5C1) : const Color(0xffF5B1B1)),
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("Pass ID: ${item.passId}",
                    style: GoogleFonts.poppins(
                        fontWeight: FontWeight.w600, fontSize: 13)),
                if (item.reason != null) ...[
                  const SizedBox(height: 4),
                  Text("Reason: ${item.reason!}",
                      style: GoogleFonts.poppins(
                          fontSize: 12, color: Colors.black87)),
                ],
                const SizedBox(height: 4),
                Text("Time: ${item.time}",
                    style: GoogleFonts.poppins(
                        fontSize: 12, color: Colors.black87)),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Icon(
                      isSuccess ? Icons.check_circle : Icons.cancel,
                      color: isSuccess
                          ? const Color(0xff2DCC70)
                          : const Color(0xffF95F62),
                      size: 20,
                    ),
                    const SizedBox(width: 6),
                    Text(
                      item.status,
                      style: GoogleFonts.poppins(
                        color: Colors.black,
                        fontWeight: FontWeight.w600,
                        fontSize: 24,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          const Icon(Icons.qr_code_2_sharp, size: 78, color: Colors.black45),
        ],
      ),
    );
  }
}
