import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:easy_refresh/easy_refresh.dart';
import '../../core/theme/app_colors.dart';
import '../shell/nav_bar_config.dart';
import '../../core/utils/date_utils.dart' as du;
import '../../shared/widgets/empty_state.dart';
import '../../shared/widgets/skeleton_list_card.dart';
import '../../shared/widgets/filter_bar.dart';
import '../../core/i18n/app_localizations.dart';
import 'vehicle_list_controller.dart';
import 'vehicle_model.dart';

class VehicleListPage extends ConsumerStatefulWidget {
  const VehicleListPage({super.key});
  @override
  ConsumerState<VehicleListPage> createState() => _VehicleListPageState();
}

class _VehicleListPageState extends ConsumerState<VehicleListPage>
    with TickerProviderStateMixin {
  static const _tabLabels = ['全部', '草稿', '审批中', '已通过', '已拒绝', '已还车'];
  static const _tabKeys = [
    '',
    'draft',
    'pending',
    'approved',
    'rejected',
    'returned',
  ];

  late final TabController _tabCtrl;

  @override
  void initState() {
    super.initState();
    _tabCtrl = TabController(length: _tabLabels.length, vsync: this);
    _tabCtrl.addListener(() {
      if (!_tabCtrl.indexIsChanging) {
        ref.read(vehicleStatusFilterProvider.notifier).state =
            _tabKeys[_tabCtrl.index];
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    final status = ref.watch(vehicleStatusFilterProvider);
    final dateStart = ref.watch(vehicleDateStartProvider);
    final dateEnd = ref.watch(vehicleDateEndProvider);
    ref.watch(vehiclePurposeFilterProvider);
    final l10n = AppLocalizations.of(context);

    // Sync TabController with external filter changes
    final targetIdx = _tabKeys.indexOf(status);
    if (targetIdx >= 0 &&
        _tabCtrl.index != targetIdx &&
        !_tabCtrl.indexIsChanging) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) _tabCtrl.animateTo(targetIdx);
      });
    }

    ref
        .read(navBarConfigProvider.notifier)
        .update(
          NavBarConfig(
            title: l10n.get('vehicleList'),
            showBack: true,
            onBack: () => context.pop(),
          ),
        );
    return Column(
      children: [
        Container(
          color: AppColors.bgCard,
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: TDTabBar(
            tabs: _tabLabels.map((l) => TDTab(text: l)).toList(),
            controller: _tabCtrl,
            isScrollable: true,
            labelColor: AppColors.primary,
            unselectedLabelColor: AppColors.textSecondary,
            outlineType: TDTabBarOutlineType.filled,
            showIndicator: true,
            indicatorColor: AppColors.primary,
            indicatorHeight: 3,
            dividerHeight: 0,
            labelPadding: const EdgeInsets.symmetric(horizontal: 12),
            onTap: (index) {
              ref.invalidate(vehicleListProvider);
              ref.read(vehicleStatusFilterProvider.notifier).state =
                  _tabKeys[index];
            },
          ),
        ),
        // 筛选栏（TDesign 组件）
        FilterBar(
          groups: [
            FilterGroup(title: '日期范围', type: FilterGroupType.dateRange, sections: [
              FilterSection(
                label: '起始日期',
                type: FilterSectionType.dateRange,
                startDate: dateStart,
                endDate: dateEnd,
                onStartChanged: (v) =>
                    ref.read(vehicleDateStartProvider.notifier).state = v,
                onEndChanged: (v) =>
                    ref.read(vehicleDateEndProvider.notifier).state = v,
              ),
              FilterSection(
                label: '结束日期',
                type: FilterSectionType.dateRange,
                startDate: dateStart,
                endDate: dateEnd,
                onStartChanged: (v) =>
                    ref.read(vehicleDateStartProvider.notifier).state = v,
                onEndChanged: (v) =>
                    ref.read(vehicleDateEndProvider.notifier).state = v,
              ),
            ]),
            FilterGroup(title: '其它', type: FilterGroupType.other, sections: [
              FilterSection(
                label: '用车目的',
                type: FilterSectionType.singleSelect,
                options: const [
                  FilterOption(value: 'reception', label: '客户接待'),
                  FilterOption(value: 'business', label: '商务出行'),
                  FilterOption(value: 'official', label: '公务'),
                ],
                onChanged: (v) =>
                    ref.read(vehiclePurposeFilterProvider.notifier).state = v,
              ),
            ]),
          ],
          onReset: () {
            ref.read(vehicleDateStartProvider.notifier).state = null;
            ref.read(vehicleDateEndProvider.notifier).state = null;
            ref.read(vehiclePurposeFilterProvider.notifier).state = null;
          },
          onConfirm: () {},
        ),
        Expanded(
          child: TabBarView(
            controller: _tabCtrl,
            children: List.generate(_tabKeys.length, (tabIdx) {
              return _buildTabContent(tabIdx);
            }),
          ),
        ),
      ],
    );
  }

  Widget _buildTabContent(int tabIdx) {
    return _VehicleTabContent(statusKey: _tabKeys[tabIdx]);
  }
}

class _VehicleTabContent extends ConsumerWidget {
  final String statusKey;

  const _VehicleTabContent({required this.statusKey});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final itemsAsync = ref.watch(vehicleListProvider(statusKey));

    if (itemsAsync.isLoading && !itemsAsync.hasValue) {
      return SkeletonLoadingList(
        cardBuilder: () => const SkeletonVehicleCard(),
      );
    }

    return EasyRefresh(
      header: TDRefreshHeader(),
      onRefresh: () async {
        ref.read(vehicleRefreshProvider.notifier).state++;
      },
      child: _buildContent(itemsAsync, context, ref),
    );
  }

  Widget _buildContent(
    AsyncValue<List<VehicleModel>> itemsAsync,
    
    BuildContext context,
    WidgetRef ref,
  ) {
    if (itemsAsync.isReloading) {
      final oldItems = itemsAsync.valueOrNull ?? [];
      if (oldItems.isEmpty) {
        return SkeletonLoadingList(
          cardBuilder: () => const SkeletonVehicleCard(),
        );
      }
      return ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: oldItems.length,
        itemBuilder: (_, i) => Padding(
          padding: const EdgeInsets.only(bottom: 16),
          child: _buildVehicleListItem(context, oldItems[i]),
        ),
      );
    }

    if (itemsAsync.hasError) {
      return ListView(
        children: const [
          SizedBox(height: 120),
          EmptyState(message: '加载失败'),
        ],
      );
    }

    final items = itemsAsync.requireValue;
    if (items.isEmpty) {
      return ListView(
        children: const [
          SizedBox(height: 120),
          EmptyState(message: '暂无用车记录'),
        ],
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: items.length,
      itemBuilder: (_, i) => Padding(
        padding: const EdgeInsets.only(bottom: 16),
        child: _buildVehicleListItem(context, items[i]),
      ),
    );
  }

  Widget _buildVehicleListItem(BuildContext context, VehicleModel item) {
    Color bg, fg;
    String label;

    switch (item.status) {
      case 'pending':
        bg = AppColors.warningBg;
        fg = AppColors.warning;
        label = '审批中';
      case 'approved':
        bg = AppColors.successBg;
        fg = AppColors.success;
        label = '已通过';
      case 'rejected':
        bg = AppColors.dangerBg;
        fg = AppColors.danger;
        label = '已拒绝';
      case 'draft':
        bg = AppColors.bgPage;
        fg = AppColors.statusGray;
        label = '草稿';
      case 'revoked':
        bg = AppColors.revokedBg;
        fg = AppColors.revokedText;
        label = '已撤回';
      case 'returned':
        bg = const Color(0xFFEDF2FC);
        fg = const Color(0xFF5A8CDB);
        label = '已还车';
      default:
        bg = AppColors.bgPage;
        fg = AppColors.statusGray;
        label = item.status;
    }

    return GestureDetector(
      onTap: () => context.push('/vehicle/detail/${item.id}'),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: AppColors.bgCard,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          children: [
            // R1: 车牌号 + 状态标签
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  item.licensePlate.isNotEmpty ? item.licensePlate : '未指定车辆',
                  style: const TextStyle(
                    fontSize: AppFontSizes.subtitle,
                    fontWeight: FontWeight.w700,
                    color: AppColors.textPrimary,
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 2,
                  ),
                  decoration: BoxDecoration(
                    color: bg,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    label,
                    style: TextStyle(
                      fontSize: AppFontSizes.caption,
                      fontWeight: FontWeight.w500,
                      color: fg,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 6),
            // R2: 申请单号 + 用途标签
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  item.applicationNo,
                  style: const TextStyle(
                    fontSize: AppFontSizes.caption,
                    color: AppColors.textSecondary,
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 6,
                    vertical: 1,
                  ),
                  decoration: BoxDecoration(
                    color: AppColors.primaryLight,
                    borderRadius: BorderRadius.circular(3),
                  ),
                  child: Text(
                    item.purpose.isNotEmpty ? item.purpose : '公务',
                    style: const TextStyle(
                      fontSize: 10,
                      color: AppColors.primary,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 6),
            // R3: 路线 + 时间
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Flexible(
                  child: Text(
                    '${item.origin.isNotEmpty ? item.origin : '未知'} → ${item.destination.isNotEmpty ? item.destination : '未知'}',
                    style: const TextStyle(
                      fontSize: 13,
                      color: AppColors.textSecondary,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                const SizedBox(width: 8),
                Text(
                  '${du.DateUtils.formatMonthDay(item.startTime)} ${du.DateUtils.formatTime(item.startTime)}',
                  style: const TextStyle(
                    fontSize: AppFontSizes.caption,
                    color: AppColors.textPlaceholder,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
