import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sizer/sizer.dart';

import '../../core/app_export.dart';
import './widgets/bus_route_card_widget.dart';
import './widgets/nearby_landmarks_widget.dart';
import './widgets/report_issue_widget.dart';
import './widgets/stop_amenities_widget.dart';
import './widgets/user_comments_widget.dart';

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

  @override
  State<BusStopDetails> createState() => _BusStopDetailsState();
}

class _BusStopDetailsState extends State<BusStopDetails> {
  bool _isLoading = true;
  DateTime _lastUpdated = DateTime.now();

  // Mock data for bus stop details
  final Map<String, dynamic> _busStopData = {
    "stopId": "BS001",
    "stopName": "Parada Central Boquete",
    "address": "Av. Central, frente al Parque José Domingo de Obaldía",
    "coordinates": {"lat": 8.7833, "lng": -82.4333},
    "lastUpdated": "2025-10-19 18:45:00",
  };

  final List<Map<String, dynamic>> _routesData = [
    {
      "routeName": "Boquete - David",
      "nextBusMinutes": 12,
      "upcomingTimes": ["19:15", "19:45", "20:15", "20:45"],
      "isDelayed": false,
    },
    {
      "routeName": "David - Boquete",
      "nextBusMinutes": 25,
      "upcomingTimes": ["19:30", "20:00", "20:30", "21:00"],
      "isDelayed": true,
    },
    {
      "routeName": "Boquete - Caldera",
      "nextBusMinutes": 45,
      "upcomingTimes": ["19:50", "20:50", "21:50"],
      "isDelayed": false,
    },
  ];

  final Map<String, dynamic> _amenitiesData = {
    "hasShelter": true,
    "hasBench": true,
    "isAccessible": false,
    "hasLighting": true,
    "hasTrashCan": true,
  };

  final List<Map<String, dynamic>> _landmarksData = [
    {
      "name": "Parque José Domingo de Obaldía",
      "distance": "50m",
      "type": "park",
    },
    {
      "name": "Banco Nacional de Panamá",
      "distance": "120m",
      "type": "bank",
    },
    {
      "name": "Supermercado El Mandado",
      "distance": "200m",
      "type": "store",
    },
    {
      "name": "Hospital Regional de Boquete",
      "distance": "350m",
      "type": "hospital",
    },
  ];

  final List<Map<String, dynamic>> _commentsData = [
    {
      "userName": "María González",
      "userAvatar":
          "https://images.unsplash.com/photo-1687757660301-7aac1198ed63",
      "semanticLabel":
          "Profile photo of a woman with long brown hair wearing a blue blouse, smiling at the camera",
      "comment":
          "Muy buena parada, siempre está limpia y los buses llegan a tiempo. El refugio protege bien de la lluvia.",
      "timestamp": "Hace 2 horas",
      "rating": 5,
    },
    {
      "userName": "Carlos Rodríguez",
      "userAvatar":
          "https://images.unsplash.com/photo-1735651705945-64bc6d18d555",
      "semanticLabel":
          "Profile photo of a middle-aged man with short gray hair and glasses wearing a white shirt",
      "comment":
          "La parada está bien ubicada pero necesita mejor iluminación en las noches. Los horarios son confiables.",
      "timestamp": "Hace 1 día",
      "rating": 4,
    },
    {
      "userName": "Ana Morales",
      "userAvatar":
          "https://images.unsplash.com/photo-1722291493584-9e75986c6c5c",
      "semanticLabel":
          "Profile photo of a young woman with curly black hair wearing a red top, smiling outdoors",
      "comment":
          "Excelente ubicación cerca del parque. Los buses de la ruta Boquete-David son muy puntuales.",
      "timestamp": "Hace 3 días",
      "rating": 5,
    },
  ];

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

  Future<void> _loadBusStopData() async {
    // Simulate loading data
    await Future.delayed(const Duration(seconds: 1));

    if (mounted) {
      setState(() {
        _isLoading = false;
        _lastUpdated = DateTime.now();
      });
    }
  }

  Future<void> _refreshData() async {
    setState(() {
      _isLoading = true;
    });

    await _loadBusStopData();

    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Información actualizada'),
          backgroundColor: AppTheme.successGreen,
          duration: Duration(seconds: 2),
        ),
      );
    }
  }

  void _shareStopInfo() {
    HapticFeedback.lightImpact();

    final stopName = _busStopData['stopName'] as String;
    final address = _busStopData['address'] as String;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('Compartiendo información de: $stopName'),
        backgroundColor: AppTheme.primaryBlack,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  void _handleNotificationToggle() {
    HapticFeedback.lightImpact();
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Notificación configurada'),
        backgroundColor: AppTheme.accentYellow,
        duration: Duration(seconds: 2),
      ),
    );
  }

  void _handleAddComment() {
    HapticFeedback.lightImpact();
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Función de comentarios próximamente'),
        backgroundColor: AppTheme.primaryBlack,
        duration: Duration(seconds: 2),
      ),
    );
  }

  void _handleReportSubmitted() {
    HapticFeedback.lightImpact();
  }

  String _formatLastUpdated() {
    final now = DateTime.now();
    final difference = now.difference(_lastUpdated);

    if (difference.inMinutes < 1) {
      return 'Actualizado hace unos segundos';
    } else if (difference.inMinutes < 60) {
      return 'Actualizado hace ${difference.inMinutes} min';
    } else {
      return 'Actualizado hace ${difference.inHours}h';
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final stopName = _busStopData['stopName'] as String? ?? '';
    final address = _busStopData['address'] as String? ?? '';

    return Scaffold(
      backgroundColor: AppTheme.backgroundGray,
      appBar: AppBar(
        backgroundColor: theme.colorScheme.surface,
        elevation: 0,
        leading: GestureDetector(
          onTap: () {
            HapticFeedback.lightImpact();
            Navigator.pop(context);
          },
          child: Container(
            margin: EdgeInsets.all(2.w),
            decoration: BoxDecoration(
              color: theme.colorScheme.surface,
              borderRadius: BorderRadius.circular(8),
              boxShadow: [
                BoxShadow(
                  color: theme.shadowColor.withValues(alpha: 0.1),
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Center(
              child: CustomIconWidget(
                iconName: 'close',
                color: theme.colorScheme.onSurface,
                size: 24,
              ),
            ),
          ),
        ),
        actions: [
          GestureDetector(
            onTap: _shareStopInfo,
            child: Container(
              margin: EdgeInsets.all(2.w),
              padding: EdgeInsets.all(2.w),
              decoration: BoxDecoration(
                color: theme.colorScheme.surface,
                borderRadius: BorderRadius.circular(8),
                boxShadow: [
                  BoxShadow(
                    color: theme.shadowColor.withValues(alpha: 0.1),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: CustomIconWidget(
                iconName: 'share',
                color: theme.colorScheme.onSurface,
                size: 24,
              ),
            ),
          ),
        ],
        systemOverlayStyle: SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: theme.brightness == Brightness.light
              ? Brightness.dark
              : Brightness.light,
        ),
      ),
      body: _isLoading
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const CircularProgressIndicator(
                    color: AppTheme.accentYellow,
                  ),
                  SizedBox(height: 2.h),
                  Text(
                    'Cargando información de la parada...',
                    style: theme.textTheme.bodyMedium?.copyWith(
                      color: theme.colorScheme.onSurface.withValues(alpha: 0.6),
                    ),
                  ),
                ],
              ),
            )
          : RefreshIndicator(
              onRefresh: _refreshData,
              color: AppTheme.accentYellow,
              backgroundColor: theme.colorScheme.surface,
              child: SingleChildScrollView(
                physics: const AlwaysScrollableScrollPhysics(),
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 2.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Stop header information
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.all(4.w),
                        decoration: BoxDecoration(
                          color: theme.colorScheme.surface,
                          borderRadius: BorderRadius.circular(12),
                          boxShadow: [
                            BoxShadow(
                              color: theme.shadowColor.withValues(alpha: 0.1),
                              blurRadius: 8,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              stopName,
                              style: theme.textTheme.headlineSmall?.copyWith(
                                fontWeight: FontWeight.w700,
                                color: theme.colorScheme.onSurface,
                              ),
                            ),
                            SizedBox(height: 1.h),
                            Row(
                              children: [
                                CustomIconWidget(
                                  iconName: 'location_on',
                                  color: AppTheme.primaryBlack,
                                  size: 16,
                                ),
                                SizedBox(width: 1.w),
                                Expanded(
                                  child: Text(
                                    address,
                                    style: theme.textTheme.bodyMedium?.copyWith(
                                      color: theme.colorScheme.onSurface
                                          .withValues(alpha: 0.7),
                                    ),
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 2,
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(height: 2.h),
                            Container(
                              padding: EdgeInsets.symmetric(
                                  horizontal: 3.w, vertical: 1.h),
                              decoration: BoxDecoration(
                                color: AppTheme.successGreen
                                    .withValues(alpha: 0.1),
                                borderRadius: BorderRadius.circular(6),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  CustomIconWidget(
                                    iconName: 'access_time',
                                    color: AppTheme.successGreen,
                                    size: 14,
                                  ),
                                  SizedBox(width: 1.w),
                                  Text(
                                    _formatLastUpdated(),
                                    style: theme.textTheme.labelSmall?.copyWith(
                                      color: AppTheme.successGreen,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 3.h),

                      // Real-time arrival predictions
                      Text(
                        'Llegadas en tiempo real',
                        style: theme.textTheme.titleLarge?.copyWith(
                          fontWeight: FontWeight.w600,
                          color: theme.colorScheme.onSurface,
                        ),
                      ),
                      SizedBox(height: 2.h),

                      // Route cards
                      ..._routesData
                          .map((routeData) => BusRouteCardWidget(
                                routeData: routeData,
                                onNotificationToggle: _handleNotificationToggle,
                              ))
                          .toList(),

                      SizedBox(height: 4.h),

                      // Stop amenities
                      StopAmenitiesWidget(amenitiesData: _amenitiesData),

                      SizedBox(height: 3.h),

                      // Nearby landmarks
                      NearbyLandmarksWidget(landmarks: _landmarksData),

                      SizedBox(height: 3.h),

                      // User comments section
                      UserCommentsWidget(
                        comments: _commentsData,
                        onAddComment: _handleAddComment,
                      ),

                      SizedBox(height: 3.h),

                      // Report issue section
                      ReportIssueWidget(
                        onReportSubmitted: _handleReportSubmitted,
                      ),

                      SizedBox(height: 4.h),
                    ],
                  ),
                ),
              ),
            ),
    );
  }
}
