import 'package:flutter/material.dart';

import 'package:doormile/core/theme/app_colors.dart';
import 'package:doormile/core/theme/app_theme.dart';
import 'package:doormile/core/widgets/common.dart';

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

  @override
  State<SavedAddressesScreen> createState() => _SavedAddressesScreenState();
}

class _SavedAddressesScreenState extends State<SavedAddressesScreen> {
  final List<Map<String, dynamic>> _addresses = [
    {
      'title': 'Home',
      'address': '12th Main, Indiranagar, Bengaluru, Karnataka 560038',
      'icon': Icons.home_rounded,
    },
    {
      'title': 'Office',
      'address': 'Sector 4, HSR Layout, Bengaluru, Karnataka 560102',
      'icon': Icons.business_rounded,
    },
    {
      'title': "Mom's House",
      'address': 'Jayanagar 4th Block, Bengaluru, Karnataka 560011',
      'icon': Icons.favorite_rounded,
    },
  ];

  void _showAddAddressSheet() {
    final titleCtrl = TextEditingController();
    final addressCtrl = TextEditingController();

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        padding: EdgeInsets.only(
          bottom: MediaQuery.of(context).viewInsets.bottom,
        ),
        decoration: const BoxDecoration(
          color: AppColors.surface,
          borderRadius: BorderRadius.vertical(top: Radius.circular(28)),
        ),
        child: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('Add New Address', style: AppTheme.headlineSm),
                    IconButton(
                      icon: const Icon(Icons.close_rounded),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ],
                ),
                const SizedBox(height: 24),
                Text('LABEL (e.g. Gym)', style: AppTheme.caption.copyWith(letterSpacing: 1)),
                const SizedBox(height: 8),
                TextField(
                  controller: titleCtrl,
                  decoration: InputDecoration(
                    hintText: 'Enter label...',
                    filled: true,
                    fillColor: AppColors.surfaceContainerLowest,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(16),
                      borderSide: const BorderSide(color: AppColors.surfaceContainer),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(16),
                      borderSide: const BorderSide(color: AppColors.surfaceContainer),
                    ),
                  ),
                ),
                const SizedBox(height: 16),
                Text('FULL ADDRESS', style: AppTheme.caption.copyWith(letterSpacing: 1)),
                const SizedBox(height: 8),
                TextField(
                  controller: addressCtrl,
                  maxLines: 3,
                  decoration: InputDecoration(
                    hintText: 'Enter complete address...',
                    filled: true,
                    fillColor: AppColors.surfaceContainerLowest,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(16),
                      borderSide: const BorderSide(color: AppColors.surfaceContainer),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(16),
                      borderSide: const BorderSide(color: AppColors.surfaceContainer),
                    ),
                  ),
                ),
                const SizedBox(height: 24),
                PrimaryButton(
                  label: 'Save Address',
                  onPressed: () {
                    if (titleCtrl.text.trim().isNotEmpty && addressCtrl.text.trim().isNotEmpty) {
                      setState(() {
                        _addresses.add({
                          'title': titleCtrl.text.trim(),
                          'address': addressCtrl.text.trim(),
                          'icon': Icons.location_on_rounded, // default icon
                        });
                      });
                      Navigator.pop(context);
                    }
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.surface,
      body: AppBackground(
        child: Column(
          children: [
            const ImmersiveHeader(
              title: 'Saved Addresses',
              subtitle: 'Manage your pickup & drop-off locations',
              icon: Icons.location_on_rounded,
              showBack: true,
            ),
            Expanded(
              child: ListView.separated(
                padding: const EdgeInsets.all(20),
                itemCount: _addresses.length + 1,
                separatorBuilder: (_, __) => const SizedBox(height: 16),
                itemBuilder: (context, i) {
                  if (i == _addresses.length) {
                    return Padding(
                      padding: const EdgeInsets.only(top: 8),
                      child: PrimaryButton(
                        label: 'Add New Address',
                        trailingIcon: Icons.add_rounded,
                        onPressed: _showAddAddressSheet,
                      ),
                    );
                  }
                  final item = _addresses[i];
                  return _AddressCard(
                    title: item['title'],
                    address: item['address'],
                    icon: item['icon'],
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _AddressCard extends StatelessWidget {
  final String title;
  final String address;
  final IconData icon;

  const _AddressCard({required this.title, required this.address, required this.icon});

  @override
  Widget build(BuildContext context) {
    return AppCard(
      padding: const EdgeInsets.all(16),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: AppColors.primary.withValues(alpha: 0.08),
              borderRadius: BorderRadius.circular(14),
            ),
            child: Icon(icon, color: AppColors.primary, size: 24),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(title, style: AppTheme.labelMd),
                    const Icon(Icons.more_horiz_rounded, color: AppColors.onSurfaceVariant, size: 20),
                  ],
                ),
                const SizedBox(height: 4),
                Text(address, style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant)),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
