import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'rental_process_screen.dart';

final Color _mainBlueColor = const Color(0xFF002FA7);
final Color _mainTextColor = const Color(0xFF1C1C1E);
final Color _subTextColor = const Color(0xFF6A717B);
final Color _pageBackgroundColor = const Color(0xFFF5F7F9);
final Color _cardBackgroundColor = Colors.white;
final Color _accentContainerColor = const Color(0xFFF0F2F5);
final Color _borderColor = const Color(0xFF007AFF).withOpacity(0.8);

const BoxShadow _cleanShadow = BoxShadow(
  color: Color.fromRGBO(0, 0, 0, 0.07),
  blurRadius: 8,
  offset: Offset(0, 4),
  spreadRadius: 0,
);

class StationInfo {
  final String name;
  final String address;
  final String status;
  final String distance;

  StationInfo({
    required this.name,
    required this.address,
    required this.status,
    required this.distance,
  });
}

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

  @override
  Widget build(BuildContext context) {
    final LatLng centerLocation = LatLng(35.1595, 126.8526);
    final List<StationInfo> stations = [
      StationInfo(
          name: '스테이션 A - 광주대학교',
          address: '효덕로 277',
          status: '온라인',
          distance: '0.5 km'),
      StationInfo(
          name: '스테이션 B - 시청',
          address: '시청대로 123',
          status: '온라인',
          distance: '1.2 km'),
      StationInfo(
          name: '스테이션 C - 공원',
          address: '공원길 55',
          status: '오프라인',
          distance: '2.8 km'),
      StationInfo(
          name: '스테이션 D - 테크 허브',
          address: '이노베이션대로 88',
          status: '온라인',
          distance: '4.1 km'),
    ];

    return Scaffold(
      backgroundColor: _pageBackgroundColor,
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(kToolbarHeight),
        child: Container(
          decoration: BoxDecoration(
            color: _pageBackgroundColor,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                blurRadius: 8,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: AppBar(
            scrolledUnderElevation: 0,
            title: Text(
              '대여/ 반납',
              style: TextStyle(
                  fontSize: 18,
                  letterSpacing: 0.5,
                  fontWeight: FontWeight.bold,
                  color: _mainTextColor),
            ),
            backgroundColor: Colors.transparent,
            elevation: 0,
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [

            SizedBox(
              height: 300.0,
              width: double.infinity,
              child: FlutterMap(
                options: MapOptions(
                  initialCenter: centerLocation,
                  initialZoom: 15.0,
                ),
                children: [
                  TileLayer(
                    urlTemplate: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',
                    userAgentPackageName: 'com.example.helmet_app',
                    subdomains: const ['a', 'b', 'c', 'd'],
                    retinaMode: true,
                  ),
                  MarkerLayer(
                    markers: [
                      _buildBlueMarker(centerLocation),
                      _buildBlueMarker(const LatLng(35.162, 126.855)),
                      _buildBlueMarker(const LatLng(35.157, 126.850)),
                      _buildBlueMarker(const LatLng(35.160, 126.858)),
                    ],
                  ),
                ],
              ),
            ),

            Container(
              color: _pageBackgroundColor,
              padding: const EdgeInsets.fromLTRB(16, 20, 16, 0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '목록 보기',
                    style: TextStyle(
                      color: _mainTextColor,
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 10),

                  ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    padding: const EdgeInsets.only(bottom: 20),
                    itemCount: stations.length,
                    itemBuilder: (context, index) {
                      return _buildStationItem(context, stations[index]);
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStationItem(BuildContext context, StationInfo station) {
    bool isOffline = station.status.startsWith('OFFLINE');

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: _cardBackgroundColor,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [_cleanShadow],
      ),
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(
                width: 80,
                height: 80,
                child: Container(
                  padding: const EdgeInsets.all(6),
                  decoration: BoxDecoration(
                    color: _pageBackgroundColor,
                    borderRadius: BorderRadius.circular(5),
                  ),
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      Container(
                        decoration: BoxDecoration(
                          color: _cardBackgroundColor,
                          borderRadius: BorderRadius.circular(5),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(5.0),
                        child: Image.asset(
                          'assets/images/storage.png',
                          fit: BoxFit.contain,
                          errorBuilder: (context, error, stackTrace) =>
                              Icon(Icons.inventory_2, color: _subTextColor),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(width: 12),

              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      station.name,
                      style: TextStyle(
                        color: _mainTextColor,
                        fontWeight: FontWeight.bold,
                        fontSize: 13,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      station.address,
                      style: TextStyle(
                          color: _subTextColor, fontSize: 11, height: 1.2),
                      maxLines: 2,
                    ),
                    const SizedBox(height: 2),
                    Text(
                      'STATUS: ${station.status}',
                      style: TextStyle(
                        color: isOffline
                            ? Colors.redAccent
                            : _mainBlueColor,
                        fontSize: 11,
                      ),
                    ),
                    Text(
                      station.distance,
                      style: TextStyle(color: _subTextColor, fontSize: 11),
                    ),
                  ],
                ),
              ),

              ElevatedButton(
                onPressed: isOffline ? null : () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => RentalProcessScreen(
                        stationName: station.name,
                      ),
                    ),
                  );
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: isOffline ? Colors.grey.shade400 : _mainBlueColor,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5),
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  minimumSize: const Size(80, 40),
                  elevation: 0,
                ),
                child: const Text(
                    'SELECT',
                    style: TextStyle(fontWeight: FontWeight.w500, letterSpacing: 0.8, fontSize: 14)
                ),
              ),
            ],
          ),

          const SizedBox(height: 12),

          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: _accentContainerColor,
              borderRadius: BorderRadius.circular(5),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '이용 기록',
                      style: TextStyle(
                        color: _mainTextColor,
                        fontWeight: FontWeight.bold,
                        fontSize: 12,
                      ),
                    ),
                    InkWell(
                      onTap: () => _showLogHistory(context, station.name),
                      child: Text(
                        '더보기 >',
                        style: TextStyle(
                          color: _subTextColor,
                          fontSize: 10,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 6),
                Text(
                  '이용 가능: 문 닫힘',
                  style: TextStyle(color: _subTextColor, fontSize: 11),
                ),
                Text(
                  '(2025-11-19)/(08:58)',
                  style: TextStyle(color: _subTextColor, fontSize: 11),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Marker _buildBlueMarker(LatLng point) {
    return Marker(
      point: point,
      width: 40,
      height: 40,
      child: Icon(
        Icons.location_on,
        color: _mainBlueColor,
        size: 40,
      ),
    );
  }

  void _showLogHistory(BuildContext context, String stationName) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) {
        return Container(
          height: MediaQuery.of(context).size.height * 0.6,
          decoration: BoxDecoration(
            color: _cardBackgroundColor,
            borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
            border: Border.all(color: _borderColor, width: 1.5),
          ),
          child: Column(
            children: [
              const SizedBox(height: 12),
              Container(
                width: 40, height: 4,
                decoration: BoxDecoration(color: _subTextColor, borderRadius: BorderRadius.circular(2)),
              ),
              Padding(
                padding: const EdgeInsets.all(20.0),
                child: Text("LOGS: $stationName", style: TextStyle(color: _mainTextColor, fontSize: 16, fontWeight: FontWeight.bold)),
              ),
              Divider(color: _subTextColor.withOpacity(0.5), height: 1),
              Expanded(
                child: ListView(
                  padding: const EdgeInsets.all(20),
                  children: [
                    _buildLogItem("08:58:33", "문 닫힘", Icons.door_front_door, _mainBlueColor),
                    _buildLogItem("08:58:30", "헬멧 반납 확인", Icons.check_circle_outline, _mainBlueColor),
                    _buildLogItem("08:55:12", "사용자 문 잠금 해제", Icons.lock_open, _mainTextColor),
                    _buildLogItem("08:30:00", "UV 살균 완료", Icons.cleaning_services, _mainBlueColor),
                    _buildLogItem("08:00:00", "시스템 가동 중", Icons.power_settings_new, _subTextColor),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildLogItem(String time, String message, IconData icon, Color color) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 20.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(time, style: TextStyle(color: _subTextColor, fontSize: 12)),
          const SizedBox(width: 16),
          Column(
            children: [
              Icon(icon, color: color, size: 20),
              Container(width: 2, height: 20, color: _subTextColor.withOpacity(0.5)),
            ],
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Text(message, style: TextStyle(color: _mainTextColor, fontSize: 14)),
          ),
        ],
      ),
    );
  }
}