import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ln_jq_app/common/login_util.dart';
import 'package:ln_jq_app/pages/c_page/message/view.dart';
import 'package:ln_jq_app/storage_service.dart';
import 'package:photo_view/photo_view.dart';

import '../../../common/styles/theme.dart';
import 'controller.dart';

class CarInfoPage extends GetView<CarInfoController> {
  const CarInfoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CarInfoController>(
      init: CarInfoController(),
      id: 'car_info',
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color.fromRGBO(240, 244, 247, 0.4),
          body: SingleChildScrollView(
            child: Column(
              children: [
                _buildUserInfoCard(),
                Padding(
                  padding: EdgeInsets.only(left: 20.w, right: 20.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      const SizedBox(height: 16),
                      _buildCarInfoCard(),
                      _buildCertificatesCard(context),
                      const SizedBox(height: 12),
                      _buildSafetyReminderCard(),
                      SizedBox(height: 95.h),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildUserInfoCard() {
    return Card(
      elevation: 1,
      color: Colors.white,
      margin: EdgeInsets.zero,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(20),
          bottomRight: Radius.circular(20),
        ),
      ),
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.only(left: 20.w, right: 20.w, bottom: 16, top: 50),
            child: Row(
              children: [
                Stack(
                  children: [
                    CircleAvatar(
                      radius: 25,
                      backgroundColor: Colors.white,
                      child: LoginUtil.getAssImg('ic_user_logo@2x'),
                    ),
                    Positioned(
                      right: 0,
                      bottom: 0,
                      child: SizedBox(
                        height: 16.h,
                        width: 16.w,
                        child: LoginUtil.getAssImg('ic_logo@2x'),
                      ),
                    ),
                  ],
                ),
                SizedBox(width: 8.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            "${StorageService.to.name}",
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          SizedBox(width: 8.w),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: const Color.fromRGBO(236, 255, 234, 1),
                              border: Border.all(color: const Color(0xFFB7E19F)),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: const Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(Icons.eco, size: 12, color: Color(0xFF52C41A)),
                                SizedBox(width: 4),
                                Text(
                                  "绿色先锋",
                                  style: TextStyle(
                                    color: Color(0xFF52C41A),
                                    fontSize: 10,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 4),
                      Text(
                        "羚牛ID：${StorageService.to.phone}",
                        style: const TextStyle(color: Colors.grey, fontSize: 11),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  onPressed: () async {
                    var scanResult = await Get.to(() => const MessagePage());
                    if (scanResult == null) {
                      controller.msgNotice();
                    }
                  },
                  style: IconButton.styleFrom(
                    backgroundColor: Colors.grey[100],
                    padding: const EdgeInsets.all(8),
                  ),
                  icon: Badge(
                    smallSize: 8,
                    backgroundColor: controller.isNotice
                        ? Colors.red
                        : Colors.transparent,
                    child: const Icon(
                      Icons.notifications_outlined,
                      color: Colors.black87,
                      size: 30,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 20.w, right: 20.w, bottom: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildModernStatItem(
                  '本月里程数',
                  'Accumulated',
                  StorageService.to.hasVehicleInfo ? '2,852km' : '-',
                  '',
                ),
                const SizedBox(width: 8),
                _buildModernStatItem(
                  '总里程',
                  'Refuel Count',
                  StorageService.to.hasVehicleInfo ? "2.5W km" : '-',
                  '',
                ),
                const SizedBox(width: 8),
                _buildModernStatItem(
                  '服务评分',
                  'Driver rating',
                  StorageService.to.hasVehicleInfo ? "4.9分" : '-',
                  '',
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildModernStatItem(String title, String subtitle, String value, String unit) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: const Color(0xFFF8F9FA),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            Text(subtitle, style: const TextStyle(fontSize: 9, color: Colors.grey)),
            const SizedBox(height: 8),
            Row(
              crossAxisAlignment: CrossAxisAlignment.baseline,
              textBaseline: TextBaseline.alphabetic,
              children: [
                Text(
                  value,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                  ),
                ),
                Text(unit, style: const TextStyle(fontSize: 10, color: Colors.black54)),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCarInfoCard() {
    return Card(
      elevation: 2,
      color: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            _buildDetailRow('车牌号', controller.plateNumber, isPlate: true),
            const SizedBox(height: 11),
            _buildDetailRow('车架号', controller.vin),
            const SizedBox(height: 11),
            _buildDetailRow('车辆型号', controller.modelName),
            const SizedBox(height: 11),
            _buildDetailRow('车辆品牌', controller.brandName),
            const SizedBox(height: 10),
            _buildH2LevelProgress(),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailRow(String label, String value, {bool isPlate = false}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(label, style: const TextStyle(fontSize: 13, color: Colors.grey)),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (isPlate)
              GestureDetector(
                onTap: () => controller.doQrCode(),
                child: Container(
                  margin: const EdgeInsets.only(right: 10),
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                  decoration: BoxDecoration(
                    border: Border.all(color: const Color.fromRGBO(71, 174, 208, 1)),
                    borderRadius: BorderRadius.circular(12),
                    color: const Color.fromRGBO(235, 250, 255, 1),
                  ),
                  child: Row(
                    children: [
                      const Icon(
                        Icons.sync,
                        size: 12,
                        color: Color.fromRGBO(71, 174, 208, 1),
                      ),
                      const SizedBox(width: 4),
                      Text(
                        StorageService.to.hasVehicleInfo ? "换车牌" : "扫码绑定",
                        style: const TextStyle(
                          color: Color.fromRGBO(71, 174, 208, 1),
                          fontSize: 10,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            Text(
              value,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildH2LevelProgress() {
    return Column(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: LinearProgressIndicator(
            value: StorageService.to.hasVehicleInfo ? 0.75 : 0,
            minHeight: 8,
            backgroundColor: Color(0xFFF0F2F5),
            valueColor: AlwaysStoppedAnimation<Color>(Color.fromRGBO(16, 185, 129, 1)),
          ),
        ),
        const SizedBox(height: 8),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("H2 Level", style: TextStyle(fontSize: 11, color: Colors.grey)),
            Text(
              StorageService.to.hasVehicleInfo ? "75%" : "0%",
              style: TextStyle(
                fontSize: 11,
                color: Color.fromRGBO(16, 185, 129, 1),
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 3. 构建车辆证件卡片 (重构为 TabView 样式)
  Widget _buildCertificatesCard(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: Column(
        children: [
          TabBar(
            isScrollable: false,
            indicatorColor: Color.fromRGBO(16, 185, 129, 1),
            labelColor: Color.fromRGBO(16, 185, 129, 1),
            unselectedLabelColor: Colors.grey,
            labelStyle: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
            indicatorSize: TabBarIndicatorSize.label,
            tabs: const [
              Tab(text: '行驶证'),
              Tab(text: '营运证'),
              Tab(text: '加氢证'),
              Tab(text: '登记证'),
            ],
          ),
          const SizedBox(height: 9),
          SizedBox(
            height: 356.h, // 给定一个高度，或者使用别的方式布局
            child: TabBarView(
              children: [
                _buildCertificateContent('行驶证', controller.drivingAttachments),
                _buildCertificateContent('营运证', controller.operationAttachments),
                _buildCertificateContent('加氢证', controller.hydrogenationAttachments),
                _buildCertificateContent('登记证', controller.registerAttachments),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建单个证件的展示内容
  Widget _buildCertificateContent(String title, RxList<String> attachments) {
    return Obx(() {
      return Card(
        elevation: 0,
        color: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: attachments.isEmpty
              ? _buildEmptyCertificateState(title)
              : Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    //证件文字
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        _buildCertDetailItem(
                          '所属公司',
                          controller.rentFromCompany,
                          isFull: false,
                        ),
                        _buildCertDetailItem('运营城市', controller.address),
                      ],
                    ),
                    const SizedBox(height: 16),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        _buildCertDetailItem(
                          '车辆颜色',
                          controller.color,
                          valueColor: const Color(0xFF52C41A),
                        ),
                        _buildCertDetailItem('氢瓶容量', controller.hydrogenCapacity),
                      ],
                    ),
                    const SizedBox(height: 16),
                    // 附件预览部分
                    GestureDetector(
                      onTap: () {
                        controller.navigateToCertificateViewer(title, attachments);
                      },
                      child: Container(
                        height: 184.h,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(16),
                          border: Border.all(color: Color.fromRGBO(226, 232, 240, 1)),
                          color: Color.fromRGBO(248, 250, 252, 1),
                        ),
                        child: Center(child: _buildAttachmentPreview(attachments[0])),
                      ),
                    ),
                  ],
                ),
        ),
      );
    });
  }

  Widget _buildEmptyCertificateState(String title) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Image.asset(
          'assets/images/ic_attention@2x.png', // 请替换为您的实际图片路径
          width: 120,
          height: 120,
        ),
        const SizedBox(height: 16),
        Text(
          '您未上传“$title”',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w600,
            color: Color.fromRGBO(51, 51, 51, 1),
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '上传后可提前通知加氢站报备\n大幅减少加氢站等待时间',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 12.sp,
            color: Color.fromRGBO(156, 163, 175, 1),
            height: 1.5,
          ),
        ),
        const SizedBox(height: 24),
        SizedBox(
          width: 200,
          height: 44,
          child: ElevatedButton.icon(
            onPressed: () {
              _showUploadDialog(title);
            },
            icon: const Text(
              '立即上传',
              style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
            ),
            label: Image.asset(
              'assets/images/ic_upload@2x.png',
              height: 20.h,
              width: 20.w,
            ),
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF017137),
              foregroundColor: Colors.white,
              shape: StadiumBorder(),
              elevation: 0,
            ),
          ),
        ),
      ],
    );
  }

  void _showUploadDialog(String title) {
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        child: Container(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '上传$title',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              ),
              const SizedBox(height: 12),
              Text(
                '请确保拍摄证件清晰可见，关键文字无反光遮挡，这将有助于快速通过审核',
                style: TextStyle(fontSize: 13, color: Colors.grey[400], height: 1.5),
              ),
              const SizedBox(height: 24),
              Row(
                children: [
                  Expanded(
                    child: _buildUploadOption(
                      icon: Icons.camera_alt_outlined,
                      label: '拍照上传',
                      onTap: () {
                        controller.pickImage(title, ImageSource.camera);
                        Get.back();
                      },
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: _buildUploadOption(
                      icon: Icons.image_outlined,
                      label: '相册上传',
                      onTap: () {
                        controller.pickImage(title, ImageSource.gallery);
                        Get.back();
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建弹窗内的选择按钮
  Widget _buildUploadOption({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 24),
        decoration: BoxDecoration(
          color: const Color(0xFFF2F9F7), // 浅绿色背景
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.all(12),
              decoration: const BoxDecoration(
                color: Color(0xFF017137), // 深绿色圆圈
                shape: BoxShape.circle,
              ),
              child: Icon(icon, color: Colors.white, size: 28),
            ),
            const SizedBox(height: 12),
            Text(
              label,
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF333333),
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCertDetailItem(
    String label,
    String value, {
    Color? valueColor,
    bool isFull = false,
  }) {
    return Container(
      width: isFull ? null : 140,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: const TextStyle(fontSize: 12, color: Colors.grey)),
          const SizedBox(height: 4),
          Text(
            value,
            style: TextStyle(
              fontSize: 13,
              fontWeight: FontWeight.bold,
              color: valueColor ?? Colors.black87,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }

  /// 附件预览组件 (智能判断 PDF 或图片)
  Widget _buildAttachmentPreview(String url) {
    return AspectRatio(
      aspectRatio: 4 / 3,
      child: controller.isPdf(url)
          ? Obx(() {
              final bool loading = controller.isLoading[url] ?? true;
              final String? localPath = controller.localPdfPaths[url];

              if (loading) {
                return _buildLoadingIndicator();
              } else if (localPath != null && localPath.isNotEmpty) {
                return IgnorePointer(
                  ignoring: true, // 设置为 true 来忽略所有指针事件
                  child: PDFView(
                    backgroundColor: Color.fromRGBO(248, 250, 252, 1),
                    fitEachPage: true,
                    filePath: localPath,
                    fitPolicy: FitPolicy.WIDTH,
                    // 适配宽度
                    enableSwipe: false,
                    swipeHorizontal: false,
                    autoSpacing: false,
                    pageFling: false,
                    preventLinkNavigation: true, // 顺便禁用PDF内部链接的跳转
                  ),
                );
              } else {
                // PDF加载失败
                return _buildErrorIndicator();
              }
            })
          : Image.network(
              url,
              fit: BoxFit.contain,
              // 图片加载时显示loading
              loadingBuilder: (context, child, loadingProgress) {
                if (loadingProgress == null) return child;
                return _buildLoadingIndicator();
              },
              // 图片加载失败时显示错误
              errorBuilder: (context, error, stackTrace) {
                return _buildErrorIndicator();
              },
            ),
    );
  }

  Widget _buildLoadingIndicator() {
    return const SizedBox(height: 200, child: Center(child: CircularProgressIndicator()));
  }

  Widget _buildErrorIndicator() {
    return const SizedBox(
      height: 200,
      child: Center(child: Icon(Icons.error_outline, color: Colors.red, size: 48)),
    );
  }

  /// 安全提醒卡片
  Widget _buildSafetyReminderCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(242, 249, 248, 1),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.info_outline, color: AppTheme.themeColor, size: 24),
              const SizedBox(width: 8),
              Text(
                "安全提醒",
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Color.fromRGBO(1, 113, 55, 1),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          const Text(
            "请确保车辆证件齐全有效，定期检查车辆状态和证件有效期，以确保运输作业合规安全。",
            style: TextStyle(
              fontSize: 13,
              color: Color.fromRGBO(1, 113, 55, 0.8),
              height: 1.5,
            ),
          ),
          const SizedBox(height: 8),
          const Text(
            "如有疑问请联系客服：400-021-1773",
            style: TextStyle(fontSize: 13, color: Color.fromRGBO(1, 113, 55, 0.8)),
          ),
        ],
      ),
    );
  }
}
