import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/i18n/app_localizations.dart';
import '../../../../core/services/issuer_store_service.dart';

/// 多门店管理页面
///
/// 门店层级：总部 → 区域 → 门店
/// 门店员工管理：收银员/店长/管理员
class StoreManagementPage extends StatelessWidget {
  const StoreManagementPage({super.key});

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: Text(context.t('store_title')),
          bottom: TabBar(
            tabs: [
              Tab(text: context.t('store_tab_list')),
              Tab(text: context.t('store_tab_employees')),
            ],
          ),
        ),
        body: const TabBarView(
          children: [
            _StoreListTab(),
            _EmployeeListTab(),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            // TODO: Show add store / add employee dialog
          },
          backgroundColor: AppColors.primary,
          child: const Icon(Icons.add_rounded, color: Colors.white),
        ),
      ),
    );
  }
}

class _StoreListTab extends StatefulWidget {
  const _StoreListTab();

  @override
  State<_StoreListTab> createState() => _StoreListTabState();
}

class _StoreListTabState extends State<_StoreListTab> {
  final _storeService = IssuerStoreService();

  bool _isLoading = true;
  String? _error;
  List<StoreModel> _stores = [];

  @override
  void initState() {
    super.initState();
    _loadStores();
  }

  Future<void> _loadStores() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final stores = await _storeService.listStores();
      if (!mounted) return;
      setState(() {
        _stores = stores;
        _isLoading = false;
      });
    } catch (e) {
      debugPrint('[StoreManagementPage] loadStores error: $e');
      if (!mounted) return;
      setState(() {
        _isLoading = false;
        _error = e.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 48, color: AppColors.textTertiary),
            const SizedBox(height: 16),
            Text(_error!, style: const TextStyle(color: AppColors.textSecondary)),
            const SizedBox(height: 16),
            ElevatedButton(onPressed: _loadStores, child: Text(context.t('retry'))),
          ],
        ),
      );
    }

    if (_stores.isEmpty) {
      return Center(
        child: Text(context.t('store_no_stores'), style: const TextStyle(color: AppColors.textSecondary)),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadStores,
      child: ListView.builder(
        padding: const EdgeInsets.all(20),
        itemCount: _stores.length,
        itemBuilder: (context, index) {
          final store = _stores[index];
          return Container(
            margin: EdgeInsets.only(
              left: store.level == 'regional' ? 20 : store.level == 'store' ? 40 : 0,
              bottom: 10,
            ),
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: AppColors.surface,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: AppColors.borderLight),
            ),
            child: Row(
              children: [
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: _levelColor(store.level).withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Icon(_levelIcon(store.level), color: _levelColor(store.level), size: 20),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(store.name, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
                          const SizedBox(width: 8),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
                            decoration: BoxDecoration(
                              color: store.status == 'active' ? AppColors.successLight : AppColors.gray100,
                              borderRadius: BorderRadius.circular(999),
                            ),
                            child: Text(
                              store.status == 'active' ? context.t('store_status_open') : context.t('store_status_closed'),
                              style: TextStyle(
                                fontSize: 10,
                                color: store.status == 'active' ? AppColors.success : AppColors.textTertiary,
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 2),
                      Text(
                        store.address ?? store.phone ?? '--',
                        style: const TextStyle(fontSize: 12, color: AppColors.textSecondary),
                      ),
                    ],
                  ),
                ),
                const Icon(Icons.chevron_right_rounded, size: 18, color: AppColors.textTertiary),
              ],
            ),
          );
        },
      ),
    );
  }

  Color _levelColor(String level) {
    switch (level) {
      case 'headquarters': return AppColors.primary;
      case 'regional': return AppColors.info;
      default: return AppColors.success;
    }
  }

  IconData _levelIcon(String level) {
    switch (level) {
      case 'headquarters': return Icons.business_rounded;
      case 'regional': return Icons.location_city_rounded;
      default: return Icons.store_rounded;
    }
  }
}

class _EmployeeListTab extends StatefulWidget {
  const _EmployeeListTab();

  @override
  State<_EmployeeListTab> createState() => _EmployeeListTabState();
}

class _EmployeeListTabState extends State<_EmployeeListTab> {
  final _storeService = IssuerStoreService();

  bool _isLoading = true;
  String? _error;
  List<EmployeeModel> _employees = [];

  @override
  void initState() {
    super.initState();
    _loadEmployees();
  }

  Future<void> _loadEmployees() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final employees = await _storeService.listEmployees();
      if (!mounted) return;
      setState(() {
        _employees = employees;
        _isLoading = false;
      });
    } catch (e) {
      debugPrint('[StoreManagementPage] loadEmployees error: $e');
      if (!mounted) return;
      setState(() {
        _isLoading = false;
        _error = e.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 48, color: AppColors.textTertiary),
            const SizedBox(height: 16),
            Text(_error!, style: const TextStyle(color: AppColors.textSecondary)),
            const SizedBox(height: 16),
            ElevatedButton(onPressed: _loadEmployees, child: Text(context.t('retry'))),
          ],
        ),
      );
    }

    if (_employees.isEmpty) {
      return Center(
        child: Text(context.t('store_no_employees'), style: const TextStyle(color: AppColors.textSecondary)),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadEmployees,
      child: ListView.separated(
        padding: const EdgeInsets.all(20),
        itemCount: _employees.length,
        separatorBuilder: (_, __) => const Divider(height: 1),
        itemBuilder: (context, index) {
          final emp = _employees[index];
          final (icon, color) = _roleIconColor(emp.role);
          return ListTile(
            contentPadding: const EdgeInsets.symmetric(vertical: 4),
            leading: Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: color.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Icon(icon, color: color, size: 20),
            ),
            title: Text(emp.name, style: const TextStyle(fontWeight: FontWeight.w500)),
            subtitle: Text(
              '${emp.role} · ${emp.storeId ?? '--'}',
              style: const TextStyle(fontSize: 12, color: AppColors.textSecondary),
            ),
            trailing: PopupMenuButton<String>(
              onSelected: (value) async {
                if (value == 'delete') {
                  try {
                    await _storeService.deleteEmployee(emp.id);
                    if (mounted) _loadEmployees();
                  } catch (e) {
                    debugPrint('[StoreManagementPage] deleteEmployee error: $e');
                  }
                }
              },
              itemBuilder: (ctx) => [
                PopupMenuItem(value: 'edit', child: Text(context.t('store_emp_edit'))),
                PopupMenuItem(value: 'delete', child: Text(context.t('store_emp_remove'))),
              ],
            ),
          );
        },
      ),
    );
  }

  (IconData, Color) _roleIconColor(String role) {
    switch (role) {
      case 'admin':
        return (Icons.admin_panel_settings_rounded, AppColors.primary);
      case 'manager':
        return (Icons.manage_accounts_rounded, AppColors.info);
      default:
        return (Icons.point_of_sale_rounded, AppColors.success);
    }
  }
}
