import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:doormile/main.dart';
import 'package:doormile/shared/state/app_state.dart';
import 'package:doormile/core/theme/app_colors.dart';
import 'package:doormile/core/theme/app_theme.dart';
import 'package:doormile/core/widgets/common.dart';
import 'package:doormile/features/booking/screens/booking_scaffold.dart';

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

  @override
  State<ParcelDetailsScreen> createState() => _ParcelDetailsScreenState();
}

class _ParcelDetailsScreenState extends State<ParcelDetailsScreen> {
  final _types = const [
    ('Documents', Icons.description),
    ('Electronics', Icons.devices),
    ('Food', Icons.restaurant),
    ('Clothing', Icons.checkroom),
    ('Fragile', Icons.auto_awesome),
    ('Other', Icons.more_horiz),
  ];
  final _weights = const ['0–1 kg', '1–5 kg', '5–10 kg', '10 kg+'];
  final _sizes = const [
    ('Small', 'Fits in a backpack (e.g. Phone, Keys)'),
    ('Medium', 'Fits in a courier box (e.g. Laptop, Shoes)'),
    ('Large', 'Requires vehicle trunk (e.g. Monitor, Luggage)'),
  ];
  final _days = const ['Today', 'Tomorrow'];
  final _slots = const ['10:00 AM - 12:00 PM', '12:00 PM - 02:00 PM', '02:00 PM - 04:00 PM'];

  @override
  Widget build(BuildContext context) {
    final draft = context.watch<AppState>().draft;
    return BookingScaffold(
      title: 'Parcel Details',
      step: 2,
      stepLabel: 'Step 2: Details',
      buttonLabel: 'Continue',
      onContinue: () => Navigator.pushNamed(context, Routes.servicePrice),
      children: [
        Text('What are you sending?', style: AppTheme.headlineSm),
        const SizedBox(height: 14),
        GridView.count(
          crossAxisCount: 3,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          mainAxisSpacing: 12,
          crossAxisSpacing: 12,
          childAspectRatio: 1.05,
          children: _types.map((t) {
            final active = draft.parcelType == t.$1;
            return _SelectTile(
              active: active,
              onTap: () {
                draft.parcelType = t.$1;
                context.read<AppState>().touch();
              },
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(t.$2, color: active ? Colors.white : AppColors.primary, size: 26),
                  const SizedBox(height: 8),
                  Text(t.$1,
                      style: AppTheme.labelMd.copyWith(
                          color: active ? Colors.white : AppColors.onSurface)),
                ],
              ),
            );
          }).toList(),
        ),
        const SizedBox(height: 24),
        Text('Approximate Weight', style: AppTheme.headlineSm),
        const SizedBox(height: 12),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: _weights
              .map((w) => _Pill(
                    label: w,
                    active: draft.weight == w,
                    onTap: () {
                      draft.weight = w;
                      context.read<AppState>().touch();
                    },
                  ))
              .toList(),
        ),
        const SizedBox(height: 24),
        Text('Package Size', style: AppTheme.headlineSm),
        const SizedBox(height: 12),
        ..._sizes.map((s) => Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: _RadioCard(
                active: draft.size == s.$1,
                onTap: () {
                  draft.size = s.$1;
                  context.read<AppState>().touch();
                },
                child: Row(
                  children: [
                    IconBadge(
                      icon: Icons.inventory_2,
                      bg: AppColors.primaryContainer.withValues(alpha: 0.1),
                      color: AppColors.primary,
                    ),
                    const SizedBox(width: 14),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(s.$1,
                              style: AppTheme.labelMd
                                  .copyWith(fontWeight: FontWeight.w700)),
                          const SizedBox(height: 2),
                          Text(s.$2, style: AppTheme.caption),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            )),
        const SizedBox(height: 12),
        Text('Pickup Slot', style: AppTheme.headlineSm),
        const SizedBox(height: 12),
        Row(
          children: _days
              .map((d) => Padding(
                    padding: const EdgeInsets.only(right: 8),
                    child: _Pill(
                      label: d,
                      active: draft.pickupDay == d,
                      onTap: () {
                        draft.pickupDay = d;
                        context.read<AppState>().touch();
                      },
                    ),
                  ))
              .toList(),
        ),
        const SizedBox(height: 12),
        ..._slots.map((slot) => Padding(
              padding: const EdgeInsets.only(bottom: 8),
              child: _RadioCard(
                active: draft.pickupSlot == slot,
                onTap: () {
                  draft.pickupSlot = slot;
                  context.read<AppState>().touch();
                },
                child: Text(slot,
                    style: AppTheme.bodyMd.copyWith(fontWeight: FontWeight.w700)),
              ),
            )),
        const SizedBox(height: 16),
        // Fragile toggle
        AppCard(
          border: Border.all(color: AppColors.outlineVariant),
          child: Row(
            children: [
              const Icon(Icons.warning_amber_rounded, color: AppColors.warning),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Mark as Fragile',
                        style: AppTheme.labelMd.copyWith(fontWeight: FontWeight.w700)),
                    Text('Handle with extra care', style: AppTheme.caption),
                  ],
                ),
              ),
              Switch(
                value: draft.fragile,
                activeTrackColor: AppColors.primary,
                onChanged: (v) {
                  draft.fragile = v;
                  context.read<AppState>().touch();
                },
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        Text('Additional Notes (Optional)',
            style: AppTheme.labelMd.copyWith(color: AppColors.onSurfaceVariant)),
        const SizedBox(height: 8),
        TextField(
          maxLines: 3,
          cursorColor: AppColors.primary,
          onChanged: (v) => draft.notes = v,
          decoration: InputDecoration(
            hintText: 'Gate code, specific handling instructions, etc.',
            hintStyle: AppTheme.bodyMd.copyWith(color: AppColors.outline),
            filled: true,
            fillColor: AppColors.surfaceContainerLowest,
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(14),
              borderSide: const BorderSide(color: AppColors.outlineVariant),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(14),
              borderSide: const BorderSide(color: AppColors.primary),
            ),
          ),
        ),
        const SizedBox(height: 16),
        Container(
          padding: const EdgeInsets.all(14),
          decoration: BoxDecoration(
            color: AppColors.tertiaryFixedDim.withValues(alpha: 0.2),
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: AppColors.tertiary.withValues(alpha: 0.1)),
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const IconBadge(
                icon: Icons.electric_rickshaw,
                bg: Color(0x1A005251),
                color: AppColors.tertiary,
                size: 40,
                iconSize: 20,
                circle: true,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('EV-First & 3-Wheeler Collection',
                        style: AppTheme.labelMd
                            .copyWith(color: AppColors.tertiary, fontWeight: FontWeight.w700)),
                    const SizedBox(height: 2),
                    Text(
                      'A Doormile agent arrives in a 3-wheeler during your slot. Delivered by EV to cut carbon footprint.',
                      style: AppTheme.caption
                          .copyWith(color: AppColors.onTertiaryFixedVariant),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

// ---- Shared selection widgets ----

class _SelectTile extends StatelessWidget {
  final bool active;
  final Widget child;
  final VoidCallback onTap;
  const _SelectTile({required this.active, required this.child, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 150),
        decoration: BoxDecoration(
          color: active ? AppColors.primary : AppColors.surfaceContainerLowest,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
              color: active ? AppColors.primary : AppColors.outlineVariant),
        ),
        child: child,
      ),
    );
  }
}

class _Pill extends StatelessWidget {
  final String label;
  final bool active;
  final VoidCallback onTap;
  const _Pill({required this.label, required this.active, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 150),
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 10),
        decoration: BoxDecoration(
          color: active ? AppColors.primary : AppColors.surfaceContainer,
          borderRadius: BorderRadius.circular(999),
        ),
        child: Text(label,
            style: AppTheme.labelMd
                .copyWith(color: active ? Colors.white : AppColors.onSurface)),
      ),
    );
  }
}

class _RadioCard extends StatelessWidget {
  final bool active;
  final Widget child;
  final VoidCallback onTap;
  const _RadioCard({required this.active, required this.child, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 150),
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: active ? const Color(0xFFF8E0E3) : AppColors.surfaceContainerLowest,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: active ? AppColors.primary : AppColors.outlineVariant,
            width: active ? 2 : 1,
          ),
        ),
        child: Row(
          children: [
            Expanded(child: child),
            const SizedBox(width: 12),
            Container(
              width: 20,
              height: 20,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                    color: active ? AppColors.primary : AppColors.outline, width: 2),
              ),
              child: active
                  ? const Center(
                      child: CircleAvatar(radius: 5, backgroundColor: AppColors.primary))
                  : null,
            ),
          ],
        ),
      ),
    );
  }
}
