import 'package:flutter/material.dart';

import '../../../models/bus_stop_model.dart';
import '../../../models/route_model.dart';
import '../../../services/transportation_service.dart';

class BusArrivalBottomSheet extends StatefulWidget {
  final BusStopModel busStop;
  final RouteModel route;

  const BusArrivalBottomSheet({
    super.key,
    required this.busStop,
    required this.route,
  });

  @override
  State<BusArrivalBottomSheet> createState() => _BusArrivalBottomSheetState();
}

class _BusArrivalBottomSheetState extends State<BusArrivalBottomSheet> {
  final TransportationService _transportationService = TransportationService();
  Map<String, dynamic>? _arrivalInfo;
  List<Map<String, dynamic>> _schedules = [];
  bool _isLoading = true;
  String? _error;

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

  Future<void> _loadArrivalInfo() async {
    try {
      setState(() {
        _isLoading = true;
        _error = null;
      });

      // Load next bus arrival info using the new method with schedule_type
      final arrivalInfo = await _transportationService.getNextBusTime(
        widget.route.id,
        widget.busStop.id,
      );

      // Load all schedules for this route from timetable (current day's schedule)
      final schedules = await _transportationService.getRouteTimetables(
        widget.route.id,
      );

      setState(() {
        _arrivalInfo = arrivalInfo;
        _schedules = schedules;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _error = 'Error cargando información: ${e.toString()}';
        _isLoading = false;
      });
    }
  }

  String _formatTime(String timeStr) {
    try {
      final parts = timeStr.split(':');
      final hour = int.parse(parts[0]);
      final minute = int.parse(parts[1]);
      final period = hour >= 12 ? 'PM' : 'AM';
      final displayHour = hour > 12 ? hour - 12 : (hour == 0 ? 12 : hour);
      return '${displayHour.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')} $period';
    } catch (e) {
      return timeStr;
    }
  }

  String _formatMinutesUntil(int minutes) {
    if (minutes <= 0) return 'Llegando ahora';
    if (minutes == 1) return 'En 1 minuto';
    if (minutes < 60) return 'En $minutes minutos';

    final hours = minutes ~/ 60;
    final remainingMinutes = minutes % 60;
    if (remainingMinutes == 0) {
      return hours == 1 ? 'En 1 hora' : 'En $hours horas';
    }
    return 'En ${hours}h ${remainingMinutes}min';
  }

  String _getScheduleTypeDisplay(String scheduleType) {
    switch (scheduleType) {
      case 'weekday':
        return 'Lunes-Viernes';
      case 'saturday':
        return 'Sábado';
      case 'sunday':
        return 'Domingo';
      default:
        return scheduleType;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Handle bar
          Container(
            margin: const EdgeInsets.only(top: 12),
            height: 4,
            width: 40,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(2),
            ),
          ),

          // Header
          Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      width: 48,
                      height: 48,
                      decoration: BoxDecoration(
                        color: const Color(0xFFFEE715),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: const Icon(
                        Icons.directions_bus,
                        color: Color(0xFF101820),
                        size: 24,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            widget.busStop.displayName,
                            style: const TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF101820),
                            ),
                          ),
                          Text(
                            widget.route.displayName,
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey[600],
                            ),
                          ),
                        ],
                      ),
                    ),
                    IconButton(
                      onPressed: () => Navigator.pop(context),
                      icon: const Icon(Icons.close),
                      color: const Color(0xFF101820),
                    ),
                  ],
                ),
              ],
            ),
          ),

          // Content
          Flexible(child: _buildContent()),
        ],
      ),
    );
  }

  Widget _buildContent() {
    if (_isLoading) {
      return const Padding(
        padding: EdgeInsets.all(40),
        child: Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFEE715)),
          ),
        ),
      );
    }

    if (_error != null) {
      return Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.error_outline, size: 48, color: Colors.red[400]),
            const SizedBox(height: 16),
            Text(
              _error!,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 16, color: Colors.red[600]),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _loadArrivalInfo,
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFFEE715),
                foregroundColor: const Color(0xFF101820),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: const Text('Reintentar'),
            ),
          ],
        ),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Next bus info
          if (_arrivalInfo != null) ...[
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: const Color(0xFFFEE715).withAlpha(26),
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: const Color(0xFFFEE715), width: 1),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    'Próximo Bus',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: const Color(0xFF101820),
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    _formatMinutesUntil(
                      _arrivalInfo!['minutes_until_arrival'] ?? 0,
                    ),
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF101820),
                    ),
                  ),
                  if (_arrivalInfo!['next_departure'] != null) ...[
                    const SizedBox(height: 4),
                    Text(
                      'Salida: ${_formatTime(_arrivalInfo!['next_departure'])}',
                      style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                    ),
                    if (_arrivalInfo!['schedule_type'] != null) ...[
                      const SizedBox(height: 2),
                      Text(
                        'Horario: ${_getScheduleTypeDisplay(_arrivalInfo!['schedule_type'])}',
                        style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                      ),
                    ],
                  ],
                ],
              ),
            ),
            const SizedBox(height: 24),
          ],

          // Next bus button
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _loadArrivalInfo,
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF101820),
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                padding: const EdgeInsets.symmetric(vertical: 16),
              ),
              child: const Text(
                'Next bus',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
          ),

          const SizedBox(height: 24),

          // Bus stop info
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.circular(12),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Información de la Parada',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: const Color(0xFF101820),
                  ),
                ),
                const SizedBox(height: 12),
                if (widget.busStop.fullAddress.isNotEmpty) ...[
                  Row(
                    children: [
                      Icon(
                        Icons.location_on,
                        size: 16,
                        color: Colors.grey[600],
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          widget.busStop.fullAddress,
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[600],
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                ],
                Row(
                  children: [
                    Icon(Icons.category, size: 16, color: Colors.grey[600]),
                    const SizedBox(width: 8),
                    Text(
                      widget.busStop.stopTypeDisplay,
                      style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                    ),
                  ],
                ),
                if (widget.busStop.amenities.isNotEmpty) ...[
                  const SizedBox(height: 8),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Icon(Icons.star, size: 16, color: Colors.grey[600]),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          widget.busStop.amenitiesText,
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[600],
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ],
            ),
          ),

          // Schedule list
          if (_schedules.isNotEmpty) ...[
            const SizedBox(height: 24),
            Text(
              'Horarios de Salida',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: const Color(0xFF101820),
              ),
            ),
            const SizedBox(height: 12),
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.grey[300]!),
              ),
              child: ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: _schedules.length > 6 ? 6 : _schedules.length,
                separatorBuilder:
                    (context, index) =>
                        Divider(height: 1, color: Colors.grey[200]),
                itemBuilder: (context, index) {
                  final schedule = _schedules[index];
                  return Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 12,
                    ),
                    child: Row(
                      children: [
                        Icon(Icons.schedule, size: 16, color: Colors.grey[600]),
                        const SizedBox(width: 12),
                        Text(
                          _formatTime(schedule['departure_time'] ?? ''),
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                            color: Color(0xFF101820),
                          ),
                        ),
                        const Spacer(),
                        if (schedule['frequency_minutes'] != null)
                          Text(
                            'Cada ${schedule['frequency_minutes']} min',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey[600],
                            ),
                          ),
                      ],
                    ),
                  );
                },
              ),
            ),
            if (_schedules.length > 6) ...[
              const SizedBox(height: 8),
              Center(
                child: Text(
                  'Y ${_schedules.length - 6} horarios más...',
                  style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                ),
              ),
            ],
          ],

          const SizedBox(height: 24),
        ],
      ),
    );
  }
}
