import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';

// ------------------ Bloc ------------------
abstract class TimeSlotEvent {}
class IncrementCapacity extends TimeSlotEvent {}
class DecrementCapacity extends TimeSlotEvent {}
class SelectStartTime extends TimeSlotEvent {
  final TimeOfDay time;
  SelectStartTime(this.time);
}
class SelectEndTime extends TimeSlotEvent {
  final TimeOfDay time;
  SelectEndTime(this.time);
}

class TimeSlotState {
  final int capacity;
  final TimeOfDay startTime;
  final TimeOfDay endTime;

  TimeSlotState({
    required this.capacity,
    required this.startTime,
    required this.endTime,
  });

  TimeSlotState copyWith({
    int? capacity,
    TimeOfDay? startTime,
    TimeOfDay? endTime,
  }) {
    return TimeSlotState(
      capacity: capacity ?? this.capacity,
      startTime: startTime ?? this.startTime,
      endTime: endTime ?? this.endTime,
    );
  }
}

class TimeSlotBloc extends Bloc<TimeSlotEvent, TimeSlotState> {
  TimeSlotBloc()
      : super(TimeSlotState(
    capacity: 50,
    startTime: const TimeOfDay(hour: 9, minute: 0),
    endTime: const TimeOfDay(hour: 12, minute: 0),
  )) {
    on<IncrementCapacity>((event, emit) {
      emit(state.copyWith(capacity: state.capacity + 1));
    });
    on<DecrementCapacity>((event, emit) {
      if (state.capacity > 1) {
        emit(state.copyWith(capacity: state.capacity - 1));
      }
    });
    on<SelectStartTime>((event, emit) => emit(state.copyWith(startTime: event.time)));
    on<SelectEndTime>((event, emit) => emit(state.copyWith(endTime: event.time)));
  }
}

// ------------------ Dialog ------------------
class AddTimeSlotDialog extends StatelessWidget {
  const AddTimeSlotDialog({super.key});

  Future<TimeOfDay?> _pickTime(BuildContext context, TimeOfDay initialTime) async {
    return await showTimePicker(
      context: context,
      initialTime: initialTime,
      builder: (context, child) {
        return Theme(
          data: ThemeData(
            colorScheme: const ColorScheme.light(primary: Color(0xffF95F62)),
          ),
          child: child!,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => TimeSlotBloc(),
      child: Dialog(
        backgroundColor: Colors.transparent,
        insetPadding: const EdgeInsets.symmetric(horizontal: 24),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(20),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
            child: Container(
              width: 400,
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 20,
                    offset: const Offset(0, 6),
                  ),
                ],
              ),
              child: BlocBuilder<TimeSlotBloc, TimeSlotState>(
                builder: (context, state) {
                  final bloc = context.read<TimeSlotBloc>();
                  return Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Center(
                        child: Text(
                          "Add Time Slots",
                          style: GoogleFonts.poppins(
                            fontWeight: FontWeight.w700,
                            fontSize: 24,
                            color: Colors.black,
                          ),
                        ),
                      ),
                      const SizedBox(height: 20),

                      // Slot Section
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: const Color(0xffF6F6F6),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("Slot 4",
                                style: GoogleFonts.poppins(
                                    fontWeight: FontWeight.w500,
                                    fontSize: 16)),
                            const SizedBox(height: 10),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(child: _timeBox(context, "Start Time", state.startTime, true, bloc)),
                                const SizedBox(width: 10),
                                Expanded(child: _timeBox(context, "End Time", state.endTime, false, bloc)),
                              ],
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 20),

                      // Capacity Section
                      Text("Capacity per Time Slot",
                          style: GoogleFonts.poppins(
                              fontWeight: FontWeight.w600,
                              fontSize: 24,
                              color: Colors.black)),
                      const SizedBox(height: 16),
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.symmetric(vertical: 10),
                        decoration: BoxDecoration(
                          color: const Color(0xffF6F6F6),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            _roundButton("-", () => bloc.add(DecrementCapacity())),
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 24),
                              child: Column(
                                children: [
                                  Text("${state.capacity}",
                                      style: GoogleFonts.poppins(
                                          fontWeight: FontWeight.w600,
                                          fontSize: 18)),
                                  Text("people",
                                      style: GoogleFonts.poppins(
                                          color: Colors.grey, fontSize: 12)),
                                ],
                              ),
                            ),
                            _roundButton("+", () => bloc.add(IncrementCapacity())),
                          ],
                        ),
                      ),
                      const SizedBox(height: 24),

                      // Buttons
                      SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          onPressed: () => Navigator.pop(context),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.black,
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12)),
                            padding: const EdgeInsets.symmetric(vertical: 14),
                          ),
                          child: Text("Create Slot",
                              style: GoogleFonts.poppins(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 15,
                                  color: Colors.white)),
                        ),
                      ),
                      const SizedBox(height: 10),
                      SizedBox(
                        width: double.infinity,
                        child: OutlinedButton(
                          onPressed: () => Navigator.pop(context),
                          style: OutlinedButton.styleFrom(
                            side: const BorderSide(
                                color: Color(0xffF95F62), width: 1.5),
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12)),
                            padding: const EdgeInsets.symmetric(vertical: 14),
                          ),
                          child: Text("Cancel",
                              style: GoogleFonts.poppins(
                                  color: const Color(0xffF95F62),
                                  fontWeight: FontWeight.w600,
                                  fontSize: 15)),
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _timeBox(BuildContext context, String label, TimeOfDay time,
      bool isStart, TimeSlotBloc bloc) {
    return Expanded(
      child: GestureDetector(
        onTap: () async {
          final picked = await _pickTime(context, time);
          if (picked != null) {
            if (isStart) {
              bloc.add(SelectStartTime(picked));
            } else {
              bloc.add(SelectEndTime(picked));
            }
          }
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(label,
                style: GoogleFonts.poppins(
                    fontSize: 13, color: Colors.black87)),
            const SizedBox(height: 6),
            Container(
              width: double.infinity,
              padding:
              const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey.shade400),
                borderRadius: BorderRadius.circular(10),
                color: Colors.white,
              ),
              child: Text(
                time.format(context),
                style: GoogleFonts.poppins(
                    fontWeight: FontWeight.w500, fontSize: 15),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _roundButton(String symbol, VoidCallback onTap) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          width: 46,
          height: 46,
          decoration: BoxDecoration(
            color: const Color(0x22F95F62),
            border: Border.all(color: const Color(0xffF95F62)),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Center(
            child: Text(symbol,
                style: GoogleFonts.poppins(
                    color: const Color(0xffF95F62),
                    fontSize: 24,
                    fontWeight: FontWeight.w500)),
          ),
        ),
      ),
    );
  }
}
