import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/theme/app_typography.dart';
import '../../../../app/theme/app_spacing.dart';
import '../../../../shared/widgets/genex_button.dart';

/// B. 商户核销端 - 主界面
///
/// B1: 员工登录（手机号+门店选择）
/// B2: 扫码核销（主页面）、券信息确认、核销成功、手动输码、离线提示
/// B3: 核销记录列表、待同步队列
/// B4: 门店仪表盘（店长权限）
class MerchantHomePage extends StatelessWidget {
  const MerchantHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            // Header
            _buildHeader(),

            // Network Status
            _buildNetworkStatus(isOnline: true),

            // Main Scanner Area
            Expanded(child: _buildScannerArea(context)),

            // Bottom Actions
            _buildBottomActions(context),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.fromLTRB(20, 12, 20, 12),
      child: Row(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: AppColors.primarySurface,
              borderRadius: AppSpacing.borderRadiusSm,
            ),
            child: const Icon(Icons.store_rounded, color: AppColors.primary, size: 22),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('星巴克 朝阳门店', style: AppTypography.labelMedium),
                Text('收银员 - 张三', style: AppTypography.caption),
              ],
            ),
          ),
          // Today's stats
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            decoration: BoxDecoration(
              color: AppColors.successLight,
              borderRadius: AppSpacing.borderRadiusFull,
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(Icons.check_circle_rounded, size: 14, color: AppColors.success),
                const SizedBox(width: 4),
                Text('今日 23 笔', style: AppTypography.labelSmall.copyWith(
                  color: AppColors.success,
                )),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildNetworkStatus({required bool isOnline}) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 20),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: isOnline ? AppColors.successLight : AppColors.warningLight,
        borderRadius: AppSpacing.borderRadiusSm,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 8, height: 8,
            decoration: BoxDecoration(
              color: isOnline ? AppColors.success : AppColors.warning,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 6),
          Text(
            isOnline ? '在线模式' : '离线模式 - 待同步 3 笔',
            style: AppTypography.caption.copyWith(
              color: isOnline ? AppColors.success : AppColors.warning,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildScannerArea(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: AppColors.gray900,
        borderRadius: AppSpacing.borderRadiusXl,
      ),
      child: Stack(
        children: [
          // Camera placeholder
          Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // Scan frame
                Container(
                  width: 240,
                  height: 240,
                  decoration: BoxDecoration(
                    border: Border.all(color: AppColors.primary, width: 2),
                    borderRadius: AppSpacing.borderRadiusLg,
                  ),
                  child: Stack(
                    children: [
                      // Corner markers
                      ..._buildCornerMarkers(),
                      // Center icon
                      Center(
                        child: Icon(
                          Icons.qr_code_scanner_rounded,
                          size: 48,
                          color: Colors.white.withValues(alpha: 0.5),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 20),
                Text(
                  '将券二维码对准扫描框',
                  style: AppTypography.bodyMedium.copyWith(color: Colors.white70),
                ),
              ],
            ),
          ),

          // Flashlight toggle
          Positioned(
            bottom: 20,
            left: 0,
            right: 0,
            child: Center(
              child: GestureDetector(
                onTap: () {},
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 44,
                      height: 44,
                      decoration: BoxDecoration(
                        color: Colors.white12,
                        shape: BoxShape.circle,
                      ),
                      child: const Icon(Icons.flashlight_on_rounded,
                          color: Colors.white70, size: 22),
                    ),
                    const SizedBox(height: 4),
                    Text('手电筒', style: AppTypography.caption.copyWith(color: Colors.white54)),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<Widget> _buildCornerMarkers() {
    const size = 24.0;
    const thickness = 3.0;
    const color = AppColors.primary;
    const radius = Radius.circular(4);

    return [
      // Top-left
      Positioned(
        top: 0, left: 0,
        child: Container(
          width: size, height: thickness,
          decoration: const BoxDecoration(color: color, borderRadius: BorderRadius.only(topLeft: radius)),
        ),
      ),
      Positioned(
        top: 0, left: 0,
        child: Container(width: thickness, height: size, color: color),
      ),
      // Top-right
      Positioned(
        top: 0, right: 0,
        child: Container(width: size, height: thickness, color: color),
      ),
      Positioned(
        top: 0, right: 0,
        child: Container(width: thickness, height: size, color: color),
      ),
      // Bottom-left
      Positioned(
        bottom: 0, left: 0,
        child: Container(width: size, height: thickness, color: color),
      ),
      Positioned(
        bottom: 0, left: 0,
        child: Container(width: thickness, height: size, color: color),
      ),
      // Bottom-right
      Positioned(
        bottom: 0, right: 0,
        child: Container(width: size, height: thickness, color: color),
      ),
      Positioned(
        bottom: 0, right: 0,
        child: Container(width: thickness, height: size, color: color),
      ),
    ];
  }

  Widget _buildBottomActions(BuildContext context) {
    return Container(
      padding: const EdgeInsets.fromLTRB(20, 12, 20, 16),
      child: Row(
        children: [
          _bottomAction(Icons.keyboard_rounded, '手动输码', () {
            _showManualInput(context);
          }),
          const SizedBox(width: 16),
          _bottomAction(Icons.history_rounded, '核销记录', () {
            // Navigator: → RedeemHistoryPage
          }),
          const SizedBox(width: 16),
          _bottomAction(Icons.bar_chart_rounded, '门店数据', () {
            // Navigator: → StoreDashboardPage
          }),
        ],
      ),
    );
  }

  Widget _bottomAction(IconData icon, String label, VoidCallback onTap) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 12),
          decoration: BoxDecoration(
            color: AppColors.gray50,
            borderRadius: AppSpacing.borderRadiusMd,
            border: Border.all(color: AppColors.borderLight),
          ),
          child: Column(
            children: [
              Icon(icon, color: AppColors.primary, size: 24),
              const SizedBox(height: 4),
              Text(label, style: AppTypography.caption.copyWith(
                color: AppColors.textPrimary,
                fontWeight: FontWeight.w500,
              )),
            ],
          ),
        ),
      ),
    );
  }

  void _showManualInput(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (ctx) => Padding(
        padding: EdgeInsets.only(
          bottom: MediaQuery.of(ctx).viewInsets.bottom,
        ),
        child: Container(
          padding: const EdgeInsets.fromLTRB(20, 8, 20, 24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 36, height: 4,
                decoration: BoxDecoration(
                  color: AppColors.gray300,
                  borderRadius: AppSpacing.borderRadiusFull,
                ),
              ),
              const SizedBox(height: 20),
              Text('手动输入券码', style: AppTypography.h2),
              const SizedBox(height: 16),
              TextField(
                autofocus: true,
                decoration: const InputDecoration(
                  hintText: '请输入券码',
                  prefixIcon: Icon(Icons.confirmation_number_outlined,
                      color: AppColors.textTertiary),
                ),
                textCapitalization: TextCapitalization.characters,
              ),
              const SizedBox(height: 16),
              GenexButton(
                label: '查询',
                onPressed: () {},
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// B2. 核销确认弹窗
class RedeemConfirmSheet extends StatelessWidget {
  const RedeemConfirmSheet({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 36, height: 4,
            decoration: BoxDecoration(
              color: AppColors.gray300,
              borderRadius: AppSpacing.borderRadiusFull,
            ),
          ),
          const SizedBox(height: 20),

          // Consumer Avatar + Info
          Row(
            children: [
              Container(
                width: 48, height: 48,
                decoration: const BoxDecoration(
                  color: AppColors.primarySurface,
                  shape: BoxShape.circle,
                ),
                child: const Icon(Icons.person_rounded, color: AppColors.primary),
              ),
              const SizedBox(width: 12),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('用户昵称', style: AppTypography.labelMedium),
                  Text('消费者', style: AppTypography.caption),
                ],
              ),
            ],
          ),
          const SizedBox(height: 20),

          // Coupon Info
          Container(
            width: double.infinity,
            padding: AppSpacing.cardPadding,
            decoration: BoxDecoration(
              color: AppColors.gray50,
              borderRadius: AppSpacing.borderRadiusMd,
            ),
            child: Column(
              children: [
                _row('券名称', '星巴克 \$25 礼品卡'),
                const SizedBox(height: 8),
                _row('面值', '\$25.00'),
                const SizedBox(height: 8),
                _row('有效期', '2026/12/31'),
                const SizedBox(height: 8),
                _row('使用条件', '无最低消费'),
              ],
            ),
          ),
          const SizedBox(height: 24),

          GenexButton(
            label: '确认核销',
            onPressed: () {
              Navigator.of(context).pop();
              // Show success
            },
          ),
          const SizedBox(height: 8),
          GenexButton(
            label: '取消',
            variant: GenexButtonVariant.text,
            onPressed: () => Navigator.of(context).pop(),
          ),
        ],
      ),
    );
  }

  Widget _row(String label, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(label, style: AppTypography.bodySmall.copyWith(color: AppColors.textSecondary)),
        Text(value, style: AppTypography.labelSmall),
      ],
    );
  }
}

/// B2. 核销成功页
class RedeemSuccessSheet extends StatelessWidget {
  const RedeemSuccessSheet({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 36, height: 4,
            decoration: BoxDecoration(
              color: AppColors.gray300,
              borderRadius: AppSpacing.borderRadiusFull,
            ),
          ),
          const SizedBox(height: 32),
          Container(
            width: 72, height: 72,
            decoration: const BoxDecoration(
              gradient: AppColors.successGradient,
              shape: BoxShape.circle,
            ),
            child: const Icon(Icons.check_rounded, color: Colors.white, size: 36),
          ),
          const SizedBox(height: 16),
          Text('核销成功', style: AppTypography.h1),
          const SizedBox(height: 8),
          Text('星巴克 \$25 礼品卡', style: AppTypography.bodyMedium.copyWith(
            color: AppColors.textSecondary,
          )),
          const SizedBox(height: 32),
          GenexButton(
            label: '继续核销',
            onPressed: () => Navigator.of(context).pop(),
          ),
        ],
      ),
    );
  }
}

/// B3. 核销记录页
class RedeemHistoryPage extends StatelessWidget {
  const RedeemHistoryPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new_rounded, size: 20),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text('核销记录'),
        actions: [
          TextButton(
            onPressed: () {},
            child: Text('今日', style: AppTypography.labelSmall.copyWith(
              color: AppColors.primary,
            )),
          ),
        ],
      ),
      body: ListView.separated(
        padding: const EdgeInsets.all(20),
        itemCount: 8,
        separatorBuilder: (_, __) => const SizedBox(height: 8),
        itemBuilder: (context, index) {
          final isSync = index < 6;
          return Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: AppColors.surface,
              borderRadius: AppSpacing.borderRadiusSm,
              border: Border.all(color: AppColors.borderLight),
            ),
            child: Row(
              children: [
                Container(
                  width: 36, height: 36,
                  decoration: BoxDecoration(
                    color: isSync ? AppColors.successLight : AppColors.warningLight,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    isSync ? Icons.check_rounded : Icons.sync_rounded,
                    size: 18,
                    color: isSync ? AppColors.success : AppColors.warning,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('品牌 ${index + 1} \$${(index + 1) * 10} 券',
                          style: AppTypography.labelSmall),
                      Text('核销员: 张三 · 14:${30 + index}',
                          style: AppTypography.caption),
                    ],
                  ),
                ),
                Text(
                  isSync ? '已同步' : '待同步',
                  style: AppTypography.caption.copyWith(
                    color: isSync ? AppColors.success : AppColors.warning,
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}

/// B4. 门店仪表盘
class StoreDashboardPage extends StatelessWidget {
  const StoreDashboardPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new_rounded, size: 20),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text('门店数据'),
      ),
      body: SingleChildScrollView(
        padding: AppSpacing.pagePadding,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 16),

            // Today Stats
            Row(
              children: [
                _statCard('今日核销', '23笔', Icons.check_circle_rounded, AppColors.success),
                const SizedBox(width: 12),
                _statCard('核销金额', '\$1,456', Icons.attach_money_rounded, AppColors.primary),
              ],
            ),
            const SizedBox(height: 24),

            // Weekly Trend (placeholder)
            Text('本周趋势', style: AppTypography.h3),
            const SizedBox(height: 12),
            Container(
              height: 200,
              decoration: BoxDecoration(
                color: AppColors.surface,
                borderRadius: AppSpacing.borderRadiusMd,
                border: Border.all(color: AppColors.borderLight),
              ),
              child: Center(
                child: Text('周核销趋势图 (fl_chart)',
                    style: AppTypography.bodySmall.copyWith(color: AppColors.textTertiary)),
              ),
            ),
            const SizedBox(height: 24),

            // Staff Ranking
            Text('核销员排行', style: AppTypography.h3),
            const SizedBox(height: 12),
            ...List.generate(3, (index) {
              final names = ['张三', '李四', '王五'];
              final counts = [12, 8, 3];
              return Container(
                margin: const EdgeInsets.only(bottom: 8),
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                decoration: BoxDecoration(
                  color: AppColors.surface,
                  borderRadius: AppSpacing.borderRadiusSm,
                  border: Border.all(color: AppColors.borderLight),
                ),
                child: Row(
                  children: [
                    Container(
                      width: 28, height: 28,
                      decoration: BoxDecoration(
                        color: index == 0
                            ? AppColors.primary
                            : AppColors.gray200,
                        shape: BoxShape.circle,
                      ),
                      child: Center(
                        child: Text('${index + 1}', style: TextStyle(
                          color: index == 0 ? Colors.white : AppColors.textSecondary,
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                        )),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Text(names[index], style: AppTypography.labelMedium),
                    const Spacer(),
                    Text('${counts[index]}笔', style: AppTypography.bodyMedium.copyWith(
                      color: AppColors.primary,
                    )),
                  ],
                ),
              );
            }),
          ],
        ),
      ),
    );
  }

  Widget _statCard(String label, String value, IconData icon, Color color) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppColors.surface,
          borderRadius: AppSpacing.borderRadiusMd,
          boxShadow: AppSpacing.shadowSm,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Icon(icon, color: color, size: 24),
            const SizedBox(height: 12),
            Text(value, style: AppTypography.h1.copyWith(color: color)),
            const SizedBox(height: 4),
            Text(label, style: AppTypography.caption),
          ],
        ),
      ),
    );
  }
}
