import 'package:flutter/material.dart';



const kGreen = Color(0xFF1E7A34);
const kGreenBg = Color(0xFFEFF7EF);

/// Centers content and caps its width on large / web / tablet screens so
/// the phone-style UI never stretches ugly-wide, while still filling
/// narrow phone screens edge to edge.
class ResponsiveBody extends StatelessWidget {
  final Widget child;
  final double maxWidth;
  const ResponsiveBody({super.key, required this.child, this.maxWidth = 520});

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.topCenter,
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: maxWidth),
        child: child,
      ),
    );
  }
}

// ----------------------------------------------------------------------
// MODELS
// ----------------------------------------------------------------------

class ServiceCategory {
  final String label;
  final String imageUrl;
  const ServiceCategory(this.label, this.imageUrl);
}

class ServiceItem {
  final String title;
  final String desc;
  final String time;
  final String price;
  final String imageUrl;
  final Color bgColor;

  const ServiceItem({
    required this.title,
    required this.desc,
    required this.time,
    required this.price,
    required this.imageUrl,
    required this.bgColor,
  });

  int get basePrice {
    final digits = RegExp(r'\d+').firstMatch(price)?.group(0);
    return digits != null ? int.parse(digits) : 299;
  }

  String get providerName {
    const map = {
      'Plumbing': 'Ramesh Kumar',
      'Electrical': 'Suresh Iyer',
      'Cleaning': 'Anita Sharma',
      'Appliance Repair': 'Vikram Singh',
      'Carpentry': 'Manoj Verma',
      'Painting': 'Arjun Nair',
      'Pest Control': 'Deepak Rao',
      'Masonry': 'Karthik Reddy',
    };
    return map[title] ?? 'Verified Professional';
  }

  List<String> get included => const [
    'Inspection & diagnosis',
    'Standard service & repair',
    'Minor parts & fittings',
    'Workmanship warranty (7 days)',
  ];
}

enum BookingStatus { booked, confirmed, inProgress, completed }

class BookingInfo {
  final ServiceItem service;
  final String bookingId;
  final String address;
  final DateTime bookedOn;
  final DateTime confirmedOn;
  final DateTime visitDate;
  final String visitTimeSlot;
  final int visitCharge;
  final BookingStatus status;
  final double rating;
  final int jobsDone;

  BookingInfo({
    required this.service,
    required this.bookingId,
    required this.address,
    required this.bookedOn,
    required this.confirmedOn,
    required this.visitDate,
    required this.visitTimeSlot,
    this.visitCharge = 99,
    this.status = BookingStatus.inProgress,
    this.rating = 4.8,
    this.jobsDone = 230,
  });

  int get taxes => ((service.basePrice + visitCharge) * 0.08).round();
  int get total => service.basePrice + visitCharge + taxes;

  factory BookingInfo.fromService(ServiceItem s) {
    final now = DateTime.now();
    return BookingInfo(
      service: s,
      bookingId: 'BK${(s.title.hashCode.toUnsigned(20)).toString().padLeft(9, '0').substring(0, 9)}',
      address: 'Koramangala, 4th Block, Bangalore 560034',
      bookedOn: now.subtract(const Duration(days: 2)),
      confirmedOn: now.subtract(const Duration(days: 2, hours: -1)),
      visitDate: now.add(const Duration(days: 1)),
      visitTimeSlot: '10:00 AM',
    );
  }
}

// ----------------------------------------------------------------------
// DATE / TIME HELPERS  (no intl dependency needed)
// ----------------------------------------------------------------------

const _months = [
  'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
];

String formatDate(DateTime d) => '${d.day} ${_months[d.month - 1]} ${d.year}';

String formatTime(DateTime d) {
  final hour = d.hour % 12 == 0 ? 12 : d.hour % 12;
  final minute = d.minute.toString().padLeft(2, '0');
  final period = d.hour >= 12 ? 'PM' : 'AM';
  return '$hour:$minute $period';
}

// ----------------------------------------------------------------------
// HOME PAGE
// ----------------------------------------------------------------------

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

  static const categories = [
    ServiceCategory('Plumbing', 'https://img.icons8.com/color/96/water-tap.png'),
    ServiceCategory('Electrical', 'https://img.icons8.com/color/96/lightning-bolt.png'),
    ServiceCategory('Cleaning', 'https://img.icons8.com/color/96/cleaning-bucket.png'),
    ServiceCategory('Appliances', 'https://img.icons8.com/color/96/washing-machine.png'),
    ServiceCategory('Carpentry', 'https://img.icons8.com/color/96/wood.png'),
  ];

  static const services = [
    ServiceItem(
      title: 'Plumbing',
      desc: 'Leak repairs, installations, pipe fitting & more',
      time: '60-90 mins',
      price: 'From ₹299',
      imageUrl: 'https://img.icons8.com/color/96/water-tap.png',
      bgColor: Color(0xFFE7EEF7),
    ),
    ServiceItem(
      title: 'Electrical',
      desc: 'Wiring, light fitting, fan installation & more',
      time: '45-90 mins',
      price: 'From ₹249',
      imageUrl: 'https://img.icons8.com/color/96/lightning-bolt.png',
      bgColor: Color(0xFFFCEFD9),
    ),
    ServiceItem(
      title: 'Cleaning',
      desc: 'Home, bathroom, kitchen cleaning & more',
      time: '60-120 mins',
      price: 'From ₹349',
      imageUrl: 'https://img.icons8.com/color/96/cleaning-bucket.png',
      bgColor: Color(0xFFE7EEF7),
    ),
    ServiceItem(
      title: 'Appliance Repair',
      desc: 'AC, fridge, washing machine, microwave & more',
      time: '60-120 mins',
      price: 'From ₹399',
      imageUrl: 'https://img.icons8.com/color/96/washing-machine.png',
      bgColor: Color(0xFFEDEDED),
    ),
    ServiceItem(
      title: 'Carpentry',
      desc: 'Furniture repair, installation, wood work & more',
      time: '60-120 mins',
      price: 'From ₹349',
      imageUrl: 'https://img.icons8.com/color/96/wood.png',
      bgColor: Color(0xFFFBE5E1),
    ),
    ServiceItem(
      title: 'Painting',
      desc: 'Wall painting, touch-ups, distemper & more',
      time: '120-240 mins',
      price: 'From ₹599',
      imageUrl: 'https://img.icons8.com/color/96/paint-roller.png',
      bgColor: Color(0xFFE7F4E9),
    ),
    ServiceItem(
      title: 'Pest Control',
      desc: 'Cockroach, termite, rodent control & more',
      time: '45-90 mins',
      price: 'From ₹299',
      imageUrl: 'https://img.icons8.com/color/96/spray.png',
      bgColor: Color(0xFFFBE5E1),
    ),
    ServiceItem(
      title: 'Masonry',
      desc: 'Wall repair, plastering, tiles, waterproofing & more',
      time: '120-240 mins',
      price: 'From ₹599',
      imageUrl: 'https://img.icons8.com/color/96/shovel.png',
      bgColor: Color(0xFFEDEDED),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: ResponsiveBody(
          child: ListView(
            padding: const EdgeInsets.only(bottom: 24),
            children: [
              // Header
              Padding(
                padding: const EdgeInsets.fromLTRB(8, 8, 16, 8),
                child: Row(
                  children: [
                    InkWell(
                      onTap: () => Navigator.of(context).maybePop(),
                      borderRadius: BorderRadius.circular(20),
                      child: const Padding(
                        padding: EdgeInsets.all(8),
                        child: Icon(Icons.arrow_back, size: 22),
                      ),
                    ),
                    const SizedBox(width: 4),
                    const Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Local Services',
                            style: TextStyle(
                              fontSize: 19,
                              fontWeight: FontWeight.w700,
                              letterSpacing: -0.3,
                              height: 1.2,
                            ),
                          ),
                          Text(
                            'Trusted experts at your doorstep',
                            style: TextStyle(fontSize: 12, color: Colors.black54),
                          ),
                        ],
                      ),
                    ),
                    InkWell(
                      onTap: () {},
                      borderRadius: BorderRadius.circular(20),
                      child: const Padding(
                        padding: EdgeInsets.all(8),
                        child: Icon(Icons.location_on_outlined, size: 22),
                      ),
                    ),
                  ],
                ),
              ),

              // Search bar
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Container(
                  height: 50,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(14),
                    border: Border.all(color: Colors.grey.shade200),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.04),
                        blurRadius: 12,
                        offset: const Offset(0, 4),
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      const SizedBox(width: 14),
                      Icon(Icons.search, color: Colors.grey.shade500, size: 21),
                      const SizedBox(width: 8),
                      Expanded(
                        child: TextField(
                          style: const TextStyle(fontSize: 13.5, color: Colors.black87),
                          decoration: InputDecoration(
                            isDense: true,
                            border: InputBorder.none,
                            hintText: 'Search for services (Plumbing, Electrician...)',
                            hintStyle: TextStyle(color: Colors.grey.shade500, fontSize: 13),
                          ),
                        ),
                      ),
                      Container(width: 1, height: 22, color: Colors.grey.shade200),
                      InkWell(
                        onTap: () {},
                        customBorder: const CircleBorder(),
                        child: Padding(
                          padding: const EdgeInsets.all(13),
                          child: Icon(Icons.mic_none_rounded, color: Colors.grey.shade600, size: 20),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),

              // Category icons row
              SizedBox(
                height: 92,
                child: ListView(
                  scrollDirection: Axis.horizontal,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  children: [
                    const _CategoryCircle(
                      label: 'All Services',
                      selected: true,
                      child: Icon(Icons.grid_view, color: kGreen),
                    ),
                    for (final c in categories)
                      _CategoryCircle(label: c.label, imageUrl: c.imageUrl),
                    const _CategoryCircle(
                      label: 'More',
                      child: Icon(Icons.keyboard_arrow_down),
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 12),

              // Trust badges
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
                  decoration: BoxDecoration(
                    color: kGreenBg,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _TrustBadge(
                        icon: Icons.verified_user_outlined,
                        title: 'Verified Professionals',
                        subtitle: 'Background checked',
                      ),
                      _TrustBadge(
                        icon: Icons.access_time,
                        title: 'On-time Service',
                        subtitle: 'Punctual & reliable',
                      ),
                      _TrustBadge(
                        icon: Icons.lock_outline,
                        title: 'Safe Payments',
                        subtitle: '100% secured',
                      ),
                    ],
                  ),
                ),
              ),

              const SizedBox(height: 20),

              // Popular Services header
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text('Popular Services', style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold)),
                    Row(
                      children: [
                        Text('View All', style: TextStyle(color: kGreen, fontWeight: FontWeight.w600, fontSize: 13)),
                        const Icon(Icons.chevron_right, color: kGreen, size: 18),
                      ],
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 12),

              // Services grid — FIXED: uses mainAxisExtent (a real pixel
              // height) instead of a childAspectRatio, so the card can
              // never overflow no matter the text length, font-scale
              // setting, or screen width. Column count also adapts for
              // wider / tablet screens.
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    final width = constraints.maxWidth;
                    final crossAxisCount = width > 700
                        ? 4
                        : width > 460
                        ? 3
                        : 2;
                    return GridView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: services.length,
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: crossAxisCount,
                        crossAxisSpacing: 12,
                        mainAxisSpacing: 12,
                        mainAxisExtent: 196,
                      ),
                      itemBuilder: (context, index) => _ServiceCard(service: services[index]),
                    );
                  },
                ),
              ),

              const SizedBox(height: 20),

              // Banner
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: kGreenBg,
                    borderRadius: BorderRadius.circular(14),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Text('Save More with Service Plan',
                                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15)),
                            const SizedBox(height: 4),
                            const Text(
                              'Priority support • Regular maintenance • Exclusive discounts',
                              style: TextStyle(fontSize: 12, color: Colors.black54),
                            ),
                            const SizedBox(height: 10),
                            ElevatedButton(
                              onPressed: () {},
                              style: ElevatedButton.styleFrom(
                                backgroundColor: kGreen,
                                foregroundColor: Colors.white,
                                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                                padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 10),
                              ),
                              child: const Text('Explore Plans'),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(width: 8),
                      Image.network(
                        'https://img.icons8.com/color/96/maintenance.png',
                        width: 70,
                        height: 70,
                        errorBuilder: (c, e, s) => const Icon(Icons.handyman, size: 60),
                      ),
                    ],
                  ),
                ),
              ),

              const SizedBox(height: 24),

              // Why book with us
              const Padding(
                padding: EdgeInsets.symmetric(horizontal: 16),
                child: Text('Why book with us?', style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold)),
              ),
              const SizedBox(height: 12),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    final width = constraints.maxWidth;
                    final crossAxisCount = width > 700 ? 4 : 2;
                    return GridView.count(
                      crossAxisCount: crossAxisCount,
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      crossAxisSpacing: 12,
                      mainAxisSpacing: 12,
                      childAspectRatio: 1.6,
                      children: const [
                        _WhyBookItem(
                          icon: Icons.verified_user_outlined,
                          iconBg: Color(0xFFE2F3E4),
                          iconColor: kGreen,
                          title: 'Verified & Rated\nProfessionals',
                        ),
                        _WhyBookItem(
                          icon: Icons.calendar_today_outlined,
                          iconBg: Color(0xFFE5ECFB),
                          iconColor: Color(0xFF2255CC),
                          title: 'Easy Booking &\nReschedule',
                        ),
                        _WhyBookItem(
                          icon: Icons.call_outlined,
                          iconBg: Color(0xFFE2F3E4),
                          iconColor: kGreen,
                          title: 'Real-time Updates\n& Tracking',
                        ),
                        _WhyBookItem(
                          icon: Icons.account_balance_wallet_outlined,
                          iconBg: Color(0xFFDDF3F1),
                          iconColor: Color(0xFF128C7E),
                          title: 'Cashless Payments\n& Invoices',
                        ),
                      ],
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _CategoryCircle extends StatelessWidget {
  final String label;
  final String? imageUrl;
  final Widget? child;
  final bool selected;

  const _CategoryCircle({
    required this.label,
    this.imageUrl,
    this.child,
    this.selected = false,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 6),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 56,
            height: 56,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: selected ? kGreenBg : Colors.white,
              border: Border.all(
                color: selected ? kGreen : Colors.grey.shade300,
                width: selected ? 1.5 : 1,
              ),
            ),
            child: Center(
              child: child ??
                  (imageUrl != null
                      ? ClipOval(
                    child: Image.network(
                      imageUrl!,
                      width: 30,
                      height: 30,
                      fit: BoxFit.cover,
                      loadingBuilder: (context, child, progress) {
                        if (progress == null) return child;
                        return const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(strokeWidth: 1.5),
                        );
                      },
                      errorBuilder: (c, e, s) => const Icon(Icons.build, size: 24),
                    ),
                  )
                      : const SizedBox()),
            ),
          ),
          const SizedBox(height: 6),
          SizedBox(
            width: 64,
            child: Text(
              label,
              textAlign: TextAlign.center,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 11,
                fontWeight: selected ? FontWeight.w600 : FontWeight.normal,
                color: selected ? kGreen : Colors.black87,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _TrustBadge extends StatelessWidget {
  final IconData icon;
  final String title;
  final String subtitle;

  const _TrustBadge({required this.icon, required this.title, required this.subtitle});

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, color: kGreen, size: 22),
          const SizedBox(height: 6),
          Text(title, textAlign: TextAlign.center, maxLines: 2, style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600)),
          const SizedBox(height: 2),
          Text(subtitle, textAlign: TextAlign.center, maxLines: 1, style: const TextStyle(fontSize: 10, color: Colors.black54)),
        ],
      ),
    );
  }
}

class _ServiceCard extends StatelessWidget {
  final ServiceItem service;
  const _ServiceCard({required this.service});

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      borderRadius: BorderRadius.circular(18),
      child: InkWell(
        borderRadius: BorderRadius.circular(18),
        splashColor: kGreen.withOpacity(0.08),
        highlightColor: kGreen.withOpacity(0.04),
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(builder: (_) => ServiceDetailPage(service: service)),
          );
        },
        child: Container(
          padding: const EdgeInsets.all(14),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(18),
            border: Border.all(color: Colors.black.withOpacity(0.04)),
            boxShadow: [
              BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 16, offset: const Offset(0, 6)),
              BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 2, offset: const Offset(0, 1)),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 48,
                    height: 48,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [service.bgColor, service.bgColor.withOpacity(0.6)],
                      ),
                      borderRadius: BorderRadius.circular(14),
                    ),
                    child: Center(
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Image.network(
                          service.imageUrl,
                          width: 26,
                          height: 26,
                          fit: BoxFit.contain,
                          loadingBuilder: (context, child, progress) {
                            if (progress == null) return child;
                            return const SizedBox(
                              width: 16,
                              height: 16,
                              child: CircularProgressIndicator(strokeWidth: 1.5),
                            );
                          },
                          errorBuilder: (c, e, s) => const Icon(Icons.build, size: 22, color: Colors.white),
                        ),
                      ),
                    ),
                  ),
                  const Spacer(),
                  Container(
                    padding: const EdgeInsets.all(4),
                    decoration: BoxDecoration(color: Colors.black.withOpacity(0.04), shape: BoxShape.circle),
                    child: const Icon(Icons.arrow_outward_rounded, size: 14, color: Colors.black54),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              Text(
                service.title,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  fontWeight: FontWeight.w700,
                  fontSize: 14.5,
                  height: 1.2,
                  letterSpacing: -0.2,
                  color: Color(0xFF1A1A1A),
                ),
              ),
              const SizedBox(height: 4),
              Expanded(
                child: Text(
                  service.desc,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 11.5, height: 1.35, color: Colors.black.withOpacity(0.5)),
                ),
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.access_time_rounded, size: 12, color: Colors.black.withOpacity(0.4)),
                        const SizedBox(width: 3),
                        Flexible(
                          child: Text(
                            service.time,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(fontSize: 10.5, color: Colors.black.withOpacity(0.45)),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(color: kGreen.withOpacity(0.08), borderRadius: BorderRadius.circular(8)),
                    child: Text(
                      service.price,
                      style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w800, color: kGreen),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _WhyBookItem extends StatelessWidget {
  final IconData icon;
  final Color iconBg;
  final Color iconColor;
  final String title;

  const _WhyBookItem({required this.icon, required this.iconBg, required this.iconColor, required this.title});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(border: Border.all(color: Colors.grey.shade200), borderRadius: BorderRadius.circular(12)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 36,
            height: 36,
            decoration: BoxDecoration(color: iconBg, shape: BoxShape.circle),
            child: Icon(icon, color: iconColor, size: 18),
          ),
          const SizedBox(height: 8),
          Text(title, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600)),
        ],
      ),
    );
  }
}

// ----------------------------------------------------------------------
// SERVICE DETAIL PAGE  (matches screenshot 1 of the second image)
// ----------------------------------------------------------------------

class ServiceDetailPage extends StatefulWidget {
  final ServiceItem service;
  const ServiceDetailPage({super.key, required this.service});

  @override
  State<ServiceDetailPage> createState() => _ServiceDetailPageState();
}

class _ServiceDetailPageState extends State<ServiceDetailPage> {
  late BookingInfo booking;

  @override
  void initState() {
    super.initState();
    booking = BookingInfo.fromService(widget.service);
  }

  void _openReschedulePauseSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) => ReschedulePauseSheet(
        booking: booking,
        onRescheduled: (newDate, newSlot) {
          setState(() {
            booking = BookingInfo(
              service: booking.service,
              bookingId: booking.bookingId,
              address: booking.address,
              bookedOn: booking.bookedOn,
              confirmedOn: booking.confirmedOn,
              visitDate: newDate,
              visitTimeSlot: newSlot,
              status: booking.status,
              rating: booking.rating,
              jobsDone: booking.jobsDone,
            );
          });
        },
      ),
    );
  }

  void _confirmCancel() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Cancel Booking?'),
        content: const Text('Are you sure you want to cancel this booking? This action cannot be undone.'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Keep Booking')),
          TextButton(
            onPressed: () {
              Navigator.pop(ctx);
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('Booking cancelled')),
              );
            },
            child: const Text('Cancel Booking', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final s = widget.service;
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: ResponsiveBody(
          child: ListView(
            padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
            children: [
              // top bar
              Row(
                children: [
                  InkWell(
                    onTap: () => Navigator.of(context).maybePop(),
                    borderRadius: BorderRadius.circular(20),
                    child: const Padding(padding: EdgeInsets.all(8), child: Icon(Icons.arrow_back, size: 22)),
                  ),
                  const Spacer(),
                  InkWell(
                    onTap: () {},
                    borderRadius: BorderRadius.circular(20),
                    child: const Padding(padding: EdgeInsets.all(8), child: Icon(Icons.more_vert, size: 22)),
                  ),
                ],
              ),
              const SizedBox(height: 4),

              // header: icon + title
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 64,
                    height: 64,
                    decoration: BoxDecoration(color: s.bgColor, borderRadius: BorderRadius.circular(16)),
                    padding: const EdgeInsets.all(14),
                    child: Image.network(
                      s.imageUrl,
                      fit: BoxFit.contain,
                      loadingBuilder: (c, child, progress) => progress == null
                          ? child
                          : const Center(child: CircularProgressIndicator(strokeWidth: 1.5)),
                      errorBuilder: (c, e, s2) => const Icon(Icons.build),
                    ),
                  ),
                  const SizedBox(width: 14),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('${s.title} Service',
                            style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w800), maxLines: 2),
                        const SizedBox(height: 3),
                        const Text('Trusted experts at your service',
                            style: TextStyle(fontSize: 12.5, color: Colors.black54)),
                        const SizedBox(height: 8),
                        InkWell(
                          onTap: () => Navigator.of(context).push(
                            MaterialPageRoute(builder: (_) => BookingTimelinePage(booking: booking)),
                          ),
                          borderRadius: BorderRadius.circular(20),
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                            decoration: BoxDecoration(color: kGreenBg, borderRadius: BorderRadius.circular(20)),
                            child: const Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text('Active Booking',
                                    style: TextStyle(fontSize: 11.5, fontWeight: FontWeight.w700, color: kGreen)),
                                SizedBox(width: 3),
                                Icon(Icons.chevron_right, size: 14, color: kGreen),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20),

              // Next visit card
              Container(
                padding: const EdgeInsets.all(14),
                decoration: BoxDecoration(color: kGreenBg, borderRadius: BorderRadius.circular(14)),
                child: Row(
                  children: [
                    const Icon(Icons.calendar_today_outlined, color: kGreen, size: 20),
                    const SizedBox(width: 10),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text('Next Visit', style: TextStyle(fontSize: 11.5, color: Colors.black54)),
                          const SizedBox(height: 2),
                          Text('Tomorrow • ${booking.visitTimeSlot}',
                              style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w700)),
                        ],
                      ),
                    ),
                    OutlinedButton(
                      onPressed: _openReschedulePauseSheet,
                      style: OutlinedButton.styleFrom(
                        foregroundColor: kGreen,
                        side: const BorderSide(color: kGreen),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
                      ),
                      child: const Text('Reschedule', style: TextStyle(fontSize: 12.5)),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 18),

              // Booking Details card
              _SectionCard(
                title: 'Booking Details',
                trailing: TextButton(onPressed: () {}, child: const Text('Edit')),
                child: Column(
                  children: [
                    _DetailRow(icon: Icons.grid_view_rounded, label: 'Service', value: '${s.title} Service'),
                    _DetailRow(icon: Icons.location_on_outlined, label: 'Address', value: booking.address),
                    _DetailRow(icon: Icons.calendar_today_outlined, label: 'Date & Time',
                        value: 'Tomorrow, ${formatDate(booking.visitDate)} • ${booking.visitTimeSlot}'),
                    _DetailRow(icon: Icons.access_time, label: 'Duration', value: 'Estimated ${s.time}'),
                    const Divider(height: 24),
                    Row(
                      children: [
                        CircleAvatar(
                          radius: 22,
                          backgroundColor: kGreen.withOpacity(0.12),
                          child: Text(
                            s.providerName.split(' ').map((w) => w[0]).take(2).join(),
                            style: const TextStyle(color: kGreen, fontWeight: FontWeight.bold),
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(s.providerName, style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 14)),
                              const SizedBox(height: 2),
                              Row(
                                children: [
                                  const Icon(Icons.star, size: 14, color: Colors.amber),
                                  const SizedBox(width: 3),
                                  Text('${booking.rating} (${booking.jobsDone} jobs)',
                                      style: const TextStyle(fontSize: 12, color: Colors.black54)),
                                ],
                              ),
                            ],
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            ScaffoldMessenger.of(context)
                                .showSnackBar(SnackBar(content: Text('Calling ${s.providerName}...')));
                          },
                          customBorder: const CircleBorder(),
                          child: Container(
                            padding: const EdgeInsets.all(10),
                            decoration: BoxDecoration(border: Border.all(color: kGreen), shape: BoxShape.circle),
                            child: const Icon(Icons.call, color: kGreen, size: 18),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 16),

              // Price details
              _SectionCard(
                title: 'Price Details',
                child: Column(
                  children: [
                    _PriceRow('Service Charges', s.basePrice),
                    _PriceRow('Visit Charges', booking.visitCharge),
                    _PriceRow('Taxes & Fees', booking.taxes),
                    const Divider(height: 24),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text('Total Payable', style: TextStyle(fontWeight: FontWeight.w800, fontSize: 15)),
                        Text('₹${booking.total}', style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 15)),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        const Icon(Icons.check_circle, color: kGreen, size: 15),
                        const SizedBox(width: 6),
                        Expanded(
                          child: Text('Payment will be collected after service completion',
                              style: TextStyle(fontSize: 11.5, color: Colors.black.withOpacity(0.55))),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 16),

              // What's included
              _SectionCard(
                title: "What's Included",
                child: Column(
                  children: [
                    for (final item in s.included)
                      Padding(
                        padding: const EdgeInsets.only(bottom: 10),
                        child: Row(
                          children: [
                            const Icon(Icons.check_circle_outline, color: kGreen, size: 18),
                            const SizedBox(width: 10),
                            Expanded(child: Text(item, style: const TextStyle(fontSize: 13))),
                          ],
                        ),
                      ),
                  ],
                ),
              ),
              const SizedBox(height: 16),

              // Manage booking
              _SectionCard(
                title: 'Manage Booking',
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    final width = constraints.maxWidth;
                    final crossAxisCount = width > 420 ? 4 : 2;
                    return GridView.count(
                      crossAxisCount: crossAxisCount,
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10,
                      childAspectRatio: 1.5,
                      children: [
                        _ManageAction(
                          icon: Icons.calendar_today_outlined,
                          label: 'Reschedule',
                          color: kGreen,
                          bg: kGreenBg,
                          onTap: _openReschedulePauseSheet,
                        ),
                        _ManageAction(
                          icon: Icons.pause_circle_outline,
                          label: 'Pause / Hold',
                          color: const Color(0xFF2255CC),
                          bg: const Color(0xFFE5ECFB),
                          onTap: _openReschedulePauseSheet,
                        ),
                        _ManageAction(
                          icon: Icons.skip_next_outlined,
                          label: 'Skip This Visit',
                          color: const Color(0xFFB07A15),
                          bg: const Color(0xFFFCEFD9),
                          onTap: () => ScaffoldMessenger.of(context)
                              .showSnackBar(const SnackBar(content: Text('Visit skipped'))),
                        ),
                        _ManageAction(
                          icon: Icons.cancel_outlined,
                          label: 'Cancel Booking',
                          color: Colors.red.shade700,
                          bg: const Color(0xFFFBE5E1),
                          onTap: _confirmCancel,
                        ),
                      ],
                    );
                  },
                ),
              ),
              const SizedBox(height: 16),

              // Need help
              _SectionCard(
                title: 'Need Help?',
                child: InkWell(
                  onTap: () => ScaffoldMessenger.of(context)
                      .showSnackBar(const SnackBar(content: Text('Opening support chat...'))),
                  child: Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.all(10),
                        decoration: BoxDecoration(color: kGreenBg, shape: BoxShape.circle),
                        child: const Icon(Icons.headset_mic_outlined, color: kGreen, size: 20),
                      ),
                      const SizedBox(width: 12),
                      const Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('Chat with Support', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 13.5)),
                            SizedBox(height: 2),
                            Text("We're here to help you 24x7",
                                style: TextStyle(fontSize: 11.5, color: Colors.black54)),
                          ],
                        ),
                      ),
                      const Icon(Icons.chevron_right, color: Colors.black45),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),

              // Save more banner
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(color: kGreenBg, borderRadius: BorderRadius.circular(14)),
                child: Row(
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text('Save More with Service Plan',
                              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)),
                          const SizedBox(height: 4),
                          Text('Get regular ${s.title.toLowerCase()} check-ups & priority support.',
                              style: const TextStyle(fontSize: 11.5, color: Colors.black54)),
                          const SizedBox(height: 10),
                          ElevatedButton(
                            onPressed: () {},
                            style: ElevatedButton.styleFrom(
                              backgroundColor: kGreen,
                              foregroundColor: Colors.white,
                              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 9),
                            ),
                            child: const Text('Explore Plans', style: TextStyle(fontSize: 12.5)),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 8),
                    Image.network(
                      'https://img.icons8.com/color/96/maintenance.png',
                      width: 56,
                      height: 56,
                      errorBuilder: (c, e, st) => const Icon(Icons.handyman, size: 48),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 16),
              Center(
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.shield_outlined, size: 14, color: Colors.black.withOpacity(0.4)),
                    const SizedBox(width: 6),
                    Text('Your data and payments are 100% secure',
                        style: TextStyle(fontSize: 11, color: Colors.black.withOpacity(0.45))),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _SectionCard extends StatelessWidget {
  final String title;
  final Widget child;
  final Widget? trailing;
  const _SectionCard({required this.title, required this.child, this.trailing});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(title, style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 15)),
              if (trailing != null) trailing!,
            ],
          ),
          const SizedBox(height: 12),
          child,
        ],
      ),
    );
  }
}

class _DetailRow extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;
  const _DetailRow({required this.icon, required this.label, required this.value});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, size: 17, color: Colors.black45),
          const SizedBox(width: 10),
          SizedBox(
            width: 84,
            child: Text(label, style: const TextStyle(fontSize: 12.5, color: Colors.black54)),
          ),
          Expanded(
            child: Text(value, style: const TextStyle(fontSize: 12.5, fontWeight: FontWeight.w600)),
          ),
        ],
      ),
    );
  }
}

class _PriceRow extends StatelessWidget {
  final String label;
  final int amount;
  const _PriceRow(this.label, this.amount);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(fontSize: 13, color: Colors.black54)),
          Text('₹$amount', style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
        ],
      ),
    );
  }
}

class _ManageAction extends StatelessWidget {
  final IconData icon;
  final String label;
  final Color color;
  final Color bg;
  final VoidCallback onTap;
  const _ManageAction({required this.icon, required this.label, required this.color, required this.bg, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
        decoration: BoxDecoration(color: bg, borderRadius: BorderRadius.circular(12)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(icon, color: color, size: 20),
            const SizedBox(height: 6),
            Text(
              label,
              textAlign: TextAlign.center,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(fontSize: 10.5, fontWeight: FontWeight.w700, color: color),
            ),
          ],
        ),
      ),
    );
  }
}

// ----------------------------------------------------------------------
// BOOKING TIMELINE PAGE  (matches screenshot 2 of the second image)
// ----------------------------------------------------------------------

class BookingTimelinePage extends StatelessWidget {
  final BookingInfo booking;
  const BookingTimelinePage({super.key, required this.booking});

  @override
  Widget build(BuildContext context) {
    final s = booking.service;
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        title: const Text('Booking Details', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
        centerTitle: false,
      ),
      body: SafeArea(
        child: ResponsiveBody(
          child: ListView(
            padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
            children: [
              // header card
              Container(
                padding: const EdgeInsets.all(14),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(14),
                  border: Border.all(color: Colors.grey.shade200),
                ),
                child: Row(
                  children: [
                    Container(
                      width: 52,
                      height: 52,
                      padding: const EdgeInsets.all(10),
                      decoration: BoxDecoration(color: s.bgColor, borderRadius: BorderRadius.circular(12)),
                      child: Image.network(
                        s.imageUrl,
                        fit: BoxFit.contain,
                        errorBuilder: (c, e, st) => const Icon(Icons.build),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('${s.title} Service', style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 15)),
                          const SizedBox(height: 4),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                            decoration: BoxDecoration(color: kGreenBg, borderRadius: BorderRadius.circular(20)),
                            child: const Text('Active Booking',
                                style: TextStyle(fontSize: 10.5, fontWeight: FontWeight.w700, color: kGreen)),
                          ),
                          const SizedBox(height: 4),
                          Text('Booking ID: ${booking.bookingId}',
                              style: const TextStyle(fontSize: 11, color: Colors.black45)),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 20),

              // horizontal stepper
              _Stepper(status: booking.status, bookedOn: booking.bookedOn, confirmedOn: booking.confirmedOn, visitDate: booking.visitDate),
              const SizedBox(height: 20),

              _SectionCard(
                title: 'Visit Timeline',
                child: _VisitTimeline(booking: booking),
              ),
              const SizedBox(height: 16),

              _SectionCard(
                title: 'Service Address',
                child: Row(
                  children: [
                    const Icon(Icons.home_outlined, color: kGreen, size: 20),
                    const SizedBox(width: 10),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text('Home', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 13.5)),
                          const SizedBox(height: 2),
                          Text(booking.address, style: const TextStyle(fontSize: 12, color: Colors.black54)),
                        ],
                      ),
                    ),
                    TextButton(onPressed: () {}, child: const Text('View Map')),
                  ],
                ),
              ),
              const SizedBox(height: 16),

              _SectionCard(
                title: 'Payment Summary',
                child: Column(
                  children: [
                    _PriceRow('Service Charges', s.basePrice),
                    _PriceRow('Visit Charges', booking.visitCharge),
                    _PriceRow('Taxes & Fees', booking.taxes),
                    const Divider(height: 24),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text('Total Payable', style: TextStyle(fontWeight: FontWeight.w800, fontSize: 15)),
                        Text('₹${booking.total}', style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 15)),
                      ],
                    ),
                    const SizedBox(height: 6),
                    Row(
                      children: [
                        const Icon(Icons.check_circle, color: kGreen, size: 14),
                        const SizedBox(width: 6),
                        Expanded(
                          child: Text('Payment will be collected after service completion',
                              style: TextStyle(fontSize: 11, color: Colors.black.withOpacity(0.55))),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 20),

              SizedBox(
                width: double.infinity,
                height: 50,
                child: ElevatedButton(
                  onPressed: () => ScaffoldMessenger.of(context)
                      .showSnackBar(SnackBar(content: Text('Calling ${s.providerName}...'))),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: kGreen,
                    foregroundColor: Colors.white,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                  ),
                  child: Text('Contact ${s.providerName.split(' ').first}',
                      style: const TextStyle(fontWeight: FontWeight.w700)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _Stepper extends StatelessWidget {
  final BookingStatus status;
  final DateTime bookedOn;
  final DateTime confirmedOn;
  final DateTime visitDate;
  const _Stepper({required this.status, required this.bookedOn, required this.confirmedOn, required this.visitDate});

  @override
  Widget build(BuildContext context) {
    final steps = [
      ('Booked', formatDate(bookedOn), true),
      ('Confirmed', formatDate(confirmedOn), true),
      ('In Progress', formatDate(visitDate), status.index >= BookingStatus.inProgress.index),
      ('Completed', 'Pending', status.index >= BookingStatus.completed.index),
    ];
    return Row(
      children: [
        for (int i = 0; i < steps.length; i++) ...[
          Expanded(
            child: Column(
              children: [
                Row(
                  children: [
                    if (i > 0)
                      Expanded(
                        child: Container(
                          height: 2,
                          color: steps[i].$3 ? kGreen : Colors.grey.shade300,
                        ),
                      )
                    else
                      const Spacer(),
                    Container(
                      width: 22,
                      height: 22,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: steps[i].$3 ? kGreen : Colors.white,
                        border: Border.all(color: steps[i].$3 ? kGreen : Colors.grey.shade300, width: 2),
                      ),
                      child: steps[i].$3
                          ? const Icon(Icons.check, size: 13, color: Colors.white)
                          : null,
                    ),
                    if (i < steps.length - 1)
                      Expanded(
                        child: Container(
                          height: 2,
                          color: steps[i + 1].$3 ? kGreen : Colors.grey.shade300,
                        ),
                      )
                    else
                      const Spacer(),
                  ],
                ),
                const SizedBox(height: 6),
                Text(steps[i].$1,
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 10.5, fontWeight: FontWeight.w700, color: steps[i].$3 ? Colors.black87 : Colors.black38)),
                Text(steps[i].$2,
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 9.5, color: Colors.black45)),
              ],
            ),
          ),
        ],
      ],
    );
  }
}

class _VisitTimeline extends StatelessWidget {
  final BookingInfo booking;
  const _VisitTimeline({required this.booking});

  @override
  Widget build(BuildContext context) {
    final items = [
      ('Booking Confirmed', '${formatDate(booking.confirmedOn)} • ${formatTime(booking.confirmedOn)}', true),
      ('Provider Assigned', '${formatDate(booking.confirmedOn)} • ${formatTime(booking.confirmedOn.add(const Duration(hours: 1)))}', true),
      ('On the Way', '${formatDate(booking.visitDate)} • ${formatTime(booking.visitDate.subtract(const Duration(minutes: 30)))}', true),
      ('In Progress', '${formatDate(booking.visitDate)} • ${booking.visitTimeSlot}', booking.status.index >= BookingStatus.inProgress.index),
      ('Completed', 'Pending', booking.status.index >= BookingStatus.completed.index),
    ];
    return Column(
      children: [
        for (int i = 0; i < items.length; i++)
          IntrinsicHeight(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Column(
                  children: [
                    Container(
                      width: 10,
                      height: 10,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: items[i].$3 ? kGreen : Colors.grey.shade300,
                      ),
                    ),
                    if (i != items.length - 1)
                      Expanded(
                        child: Container(width: 2, color: Colors.grey.shade200),
                      ),
                  ],
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(bottom: 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(items[i].$1,
                            style: TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.w700,
                                color: items[i].$3 ? Colors.black87 : Colors.black38)),
                        const SizedBox(height: 2),
                        Text(items[i].$2, style: const TextStyle(fontSize: 11.5, color: Colors.black45)),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
      ],
    );
  }
}

// ----------------------------------------------------------------------
// RESCHEDULE / PAUSE BOTTOM SHEET  (matches screenshot 3 of second image)
// ----------------------------------------------------------------------

enum _RescheduleOption { reschedule, pause, skip }

class ReschedulePauseSheet extends StatefulWidget {
  final BookingInfo booking;
  final void Function(DateTime newDate, String newSlot)? onRescheduled;
  const ReschedulePauseSheet({super.key, required this.booking, this.onRescheduled});

  @override
  State<ReschedulePauseSheet> createState() => _ReschedulePauseSheetState();
}

class _ReschedulePauseSheetState extends State<ReschedulePauseSheet> {
  _RescheduleOption selected = _RescheduleOption.reschedule;
  late DateTime newDate;
  String newSlot = '11:00 AM – 1:00 PM';
  final reasonController = TextEditingController();

  final slots = const [
    '9:00 AM – 11:00 AM',
    '11:00 AM – 1:00 PM',
    '2:00 PM – 4:00 PM',
    '4:00 PM – 6:00 PM',
  ];

  @override
  void initState() {
    super.initState();
    newDate = widget.booking.visitDate.add(const Duration(days: 2));
  }

  @override
  void dispose() {
    reasonController.dispose();
    super.dispose();
  }

  Future<void> _pickDate() async {
    final picked = await showDatePicker(
      context: context,
      initialDate: newDate,
      firstDate: DateTime.now(),
      lastDate: DateTime.now().add(const Duration(days: 90)),
    );
    if (picked != null) setState(() => newDate = picked);
  }

  @override
  Widget build(BuildContext context) {
    return DraggableScrollableSheet(
      initialChildSize: 0.75,
      minChildSize: 0.5,
      maxChildSize: 0.95,
      expand: false,
      builder: (context, scrollController) {
        return Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
          ),
          child: ResponsiveBody(
            child: ListView(
              controller: scrollController,
              padding: const EdgeInsets.fromLTRB(20, 16, 20, 24),
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text('Reschedule or Pause',
                        style: TextStyle(fontSize: 17, fontWeight: FontWeight.w800)),
                    InkWell(
                      onTap: () => Navigator.of(context).pop(),
                      borderRadius: BorderRadius.circular(20),
                      child: const Padding(padding: EdgeInsets.all(4), child: Icon(Icons.close, size: 20)),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                const Text('Choose an option', style: TextStyle(fontSize: 12.5, color: Colors.black54)),
                const SizedBox(height: 10),

                _OptionCard(
                  icon: Icons.calendar_today_outlined,
                  title: 'Reschedule',
                  subtitle: 'Pick a new date & time',
                  selected: selected == _RescheduleOption.reschedule,
                  onTap: () => setState(() => selected = _RescheduleOption.reschedule),
                ),
                const SizedBox(height: 10),
                _OptionCard(
                  icon: Icons.pause_circle_outline,
                  title: 'Pause / Hold',
                  subtitle: 'Pause this booking for a few days',
                  selected: selected == _RescheduleOption.pause,
                  onTap: () => setState(() => selected = _RescheduleOption.pause),
                ),
                const SizedBox(height: 10),
                _OptionCard(
                  icon: Icons.skip_next_outlined,
                  title: 'Skip This Visit',
                  subtitle: 'Skip and book for later',
                  selected: selected == _RescheduleOption.skip,
                  onTap: () => setState(() => selected = _RescheduleOption.skip),
                ),

                if (selected == _RescheduleOption.reschedule) ...[
                  const SizedBox(height: 20),
                  const Text('Select new date & time',
                      style: TextStyle(fontSize: 13, fontWeight: FontWeight.w700)),
                  const SizedBox(height: 10),
                  const Text('Date', style: TextStyle(fontSize: 11.5, color: Colors.black54)),
                  const SizedBox(height: 4),
                  InkWell(
                    onTap: _pickDate,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 13),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey.shade300),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(formatDate(newDate), style: const TextStyle(fontSize: 13)),
                          const Icon(Icons.keyboard_arrow_down, size: 18),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(height: 14),
                  const Text('Time', style: TextStyle(fontSize: 11.5, color: Colors.black54)),
                  const SizedBox(height: 4),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey.shade300),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton<String>(
                        value: newSlot,
                        isExpanded: true,
                        icon: const Icon(Icons.keyboard_arrow_down, size: 18),
                        items: slots
                            .map((s) => DropdownMenuItem(value: s, child: Text(s, style: const TextStyle(fontSize: 13))))
                            .toList(),
                        onChanged: (v) => setState(() => newSlot = v ?? newSlot),
                      ),
                    ),
                  ),
                  const SizedBox(height: 14),
                  const Text('Reason (Optional)', style: TextStyle(fontSize: 11.5, color: Colors.black54)),
                  const SizedBox(height: 4),
                  TextField(
                    controller: reasonController,
                    maxLines: 3,
                    style: const TextStyle(fontSize: 13),
                    decoration: InputDecoration(
                      hintText: "Tell us if there's anything we should know...",
                      hintStyle: const TextStyle(fontSize: 12.5, color: Colors.black38),
                      contentPadding: const EdgeInsets.all(12),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: BorderSide(color: Colors.grey.shade300),
                      ),
                    ),
                  ),
                ],

                const SizedBox(height: 20),
                SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: ElevatedButton(
                    onPressed: () {
                      widget.onRescheduled?.call(newDate, newSlot);
                      Navigator.of(context).pop();
                      final msg = switch (selected) {
                        _RescheduleOption.reschedule => 'Booking rescheduled to ${formatDate(newDate)}',
                        _RescheduleOption.pause => 'Booking paused',
                        _RescheduleOption.skip => 'This visit will be skipped',
                      };
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: kGreen,
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                    ),
                    child: Text(
                      switch (selected) {
                        _RescheduleOption.reschedule => 'Confirm Reschedule',
                        _RescheduleOption.pause => 'Confirm Pause',
                        _RescheduleOption.skip => 'Confirm Skip',
                      },
                      style: const TextStyle(fontWeight: FontWeight.w700),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

class _OptionCard extends StatelessWidget {
  final IconData icon;
  final String title;
  final String subtitle;
  final bool selected;
  final VoidCallback onTap;

  const _OptionCard({
    required this.icon,
    required this.title,
    required this.subtitle,
    required this.selected,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: selected ? kGreenBg : Colors.white,
          border: Border.all(color: selected ? kGreen : Colors.grey.shade300),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: [
            Container(
              width: 36,
              height: 36,
              decoration: BoxDecoration(
                color: selected ? Colors.white : Colors.grey.shade100,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Icon(icon, size: 18, color: selected ? kGreen : Colors.black54),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(title, style: const TextStyle(fontSize: 13.5, fontWeight: FontWeight.w700)),
                  const SizedBox(height: 2),
                  Text(subtitle, style: const TextStyle(fontSize: 11.5, color: Colors.black54)),
                ],
              ),
            ),
            Icon(
              selected ? Icons.radio_button_checked : Icons.radio_button_off,
              color: selected ? kGreen : Colors.grey.shade400,
              size: 20,
            ),
          ],
        ),
      ),
    );
  }
}