/// Page: Design Request Detail Page
///
/// Displays design request details from API following html/design-request-detail.html.
library;

import 'package:cached_network_image/cached_network_image.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/router/app_router.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/showrooms/domain/entities/design_request.dart';
import 'package:worker/features/showrooms/domain/entities/sample_project.dart';
import 'package:worker/features/showrooms/presentation/providers/design_request_provider.dart';
import 'package:worker/features/showrooms/presentation/widgets/description_item.dart';
import 'package:worker/features/showrooms/presentation/widgets/file_item.dart';
import 'package:worker/features/showrooms/presentation/widgets/image_viewer_dialog.dart';

/// Design Request Detail Page
///
/// Shows complete details of a design request including:
/// - Request header with ID, date, and status
/// - Design information (subject, description)
/// - Completion highlight for completed requests
/// - Attached files/images
class DesignRequestDetailPage extends ConsumerWidget {
  const DesignRequestDetailPage({required this.requestId, super.key});

  final String requestId;

  Color _getStatusColor(DesignRequestStatus status) {
    switch (status) {
      case DesignRequestStatus.pending:
        return const Color(0xFFd97706);
      case DesignRequestStatus.designing:
        return const Color(0xFF3730a3);
      case DesignRequestStatus.completed:
        return const Color(0xFF065f46);
      case DesignRequestStatus.rejected:
        return const Color(0xFFdc2626);
    }
  }

  Color _getStatusBackgroundColor(DesignRequestStatus status) {
    switch (status) {
      case DesignRequestStatus.pending:
        return const Color(0xFFfef3c7);
      case DesignRequestStatus.designing:
        return const Color(0xFFe0e7ff);
      case DesignRequestStatus.completed:
        return const Color(0xFFd1fae5);
      case DesignRequestStatus.rejected:
        return const Color(0xFFfee2e2);
    }
  }

  IconData _getFileIcon(String fileUrl) {
    final extension = fileUrl.split('.').last.toLowerCase();

    if (['jpg', 'jpeg', 'png', 'gif', 'webp'].contains(extension)) {
      return Icons.image;
    } else if (extension == 'pdf') {
      return Icons.picture_as_pdf;
    } else if (extension == 'dwg') {
      return Icons.architecture;
    } else if (['doc', 'docx'].contains(extension)) {
      return Icons.description;
    }
    return Icons.insert_drive_file;
  }

  bool _isImageFile(String fileUrl) {
    final extension = fileUrl.split('.').last.toLowerCase();
    return ['jpg', 'jpeg', 'png', 'gif', 'webp'].contains(extension);
  }

  void _contactSupport(BuildContext context) {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Liên hệ hỗ trợ'),
        content: const Text(
          'Bạn có muốn liên hệ hỗ trợ về yêu cầu thiết kế này?',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Hủy'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              context.push(RouteNames.chat);
            },
            child: const Text('Liên hệ'),
          ),
        ],
      ),
    );
  }

  Future<void> _shareRequest(
    BuildContext context,
    DesignRequest request,
  ) async {
    try {
      await SharePlus.instance.share(
        ShareParams(text: 'Yêu cầu thiết kế #${request.id}\n${request.subject}'),
      );
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Lỗi khi chia sẻ: $e'),
            backgroundColor: AppColors.danger,
          ),
        );
      }
    }
  }

  Future<void> _viewDesign3D(BuildContext context) async {
    // TODO: Replace with actual design link from API when available
    const designUrl = 'https://example.com/3d-design';

    try {
      final uri = Uri.parse(designUrl);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      } else {
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Link thiết kế 3D chưa sẵn sàng'),
              backgroundColor: AppColors.warning,
            ),
          );
        }
      }
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Lỗi khi mở link: $e'),
            backgroundColor: AppColors.danger,
          ),
        );
      }
    }
  }

  void _showImageViewer(
    BuildContext context,
    List<ProjectFile> files,
    int initialIndex,
  ) {
    // Filter only image files
    final images = files.where((f) => _isImageFile(f.fileUrl)).toList();
    if (images.isEmpty) return;

    showDialog<void>(
      context: context,
      barrierColor: Colors.black87,
      builder: (context) => ImageViewerDialog(
        images: images,
        initialIndex: initialIndex,
      ),
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final detailAsync = ref.watch(designRequestDetailProvider(requestId));
    final colorScheme = Theme.of(context).colorScheme;

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        backgroundColor: colorScheme.surface,
        elevation: AppBarSpecs.elevation,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: colorScheme.onSurface),
          onPressed: () => Navigator.of(context).pop(),
        ),
        centerTitle: false,
        title: Text(
          'Chi tiết Yêu cầu',
          style: TextStyle(
            color: colorScheme.onSurface,
            fontSize: 20,
            fontWeight: FontWeight.w600,
          ),
        ),
        actions: [
          detailAsync.maybeWhen(
            data: (request) => IconButton(
              icon: Icon(Icons.share, color: colorScheme.onSurface),
              onPressed: () => _shareRequest(context, request),
            ),
            orElse: () => const SizedBox.shrink(),
          ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: detailAsync.when(
        data: (request) => SingleChildScrollView(
          padding: const EdgeInsets.all(20),
          child: Column(
            children: [
              // Request Header & Design Info Card
              Card(
                elevation: 2,
                margin: EdgeInsets.zero,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Header Section (centered)
                      Center(
                        child: Column(
                          children: [
                            // Request ID
                            Text(
                              '#${request.id}',
                              style: TextStyle(
                                fontSize: 24,
                                fontWeight: FontWeight.w700,
                                color: colorScheme.onSurface,
                              ),
                            ),
                            const SizedBox(height: 8),

                            // Date
                            if (request.dateline != null)
                              Text(
                                'Ngày gửi: ${request.dateline}',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: colorScheme.onSurfaceVariant,
                                ),
                              ),
                            const SizedBox(height: 16),

                            // Status Badge
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 8,
                              ),
                              decoration: BoxDecoration(
                                color: _getStatusBackgroundColor(request.status),
                                borderRadius: BorderRadius.circular(20),
                              ),
                              child: Text(
                                request.statusText.toUpperCase(),
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  color: _getStatusColor(request.status),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      const SizedBox(height: 24),
                      Divider(height: 1, color: colorScheme.surfaceContainerHighest),
                      const SizedBox(height: 24),

                      // Design Information Section
                      Row(
                        children: [
                          Icon(
                            Icons.info_outline,
                            color: colorScheme.primary,
                            size: 20,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            'Thông tin thiết kế',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w700,
                              color: colorScheme.onSurface,
                            ),
                          ),
                        ],
                      ),

                      const SizedBox(height: 16),

                      // Description List
                      DescriptionItem(
                        label: 'Tên công trình:',
                        value: request.subject,
                      ),

                      if (request.description != null &&
                          request.description!.isNotEmpty) ...[
                        const SizedBox(height: 12),
                        DescriptionItem(
                          label: 'Mô tả chi tiết:',
                          value: request.description!,
                          isMultiLine: true,
                          isHtml: true,
                        ),
                      ],
                    ],
                  ),
                ),
              ),

              const SizedBox(height: 20),

              // Completion Highlight (only if completed)
              if (request.isCompleted)
                Card(
                  elevation: 2,
                  margin: EdgeInsets.zero,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                    side: const BorderSide(color: Color(0xFF10b981), width: 2),
                  ),
                  child: Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      gradient: const LinearGradient(
                        colors: [Color(0xFFd1fae5), Color(0xFFa7f3d0)],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    padding: const EdgeInsets.all(20),
                    child: Column(
                      children: [
                        const Text(
                          '🎉 Thiết kế đã hoàn thành!',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                            color: Color(0xFF065f46),
                          ),
                        ),
                        const SizedBox(height: 12),
                        const Text(
                          'Thiết kế 3D của bạn đã sẵn sàng để xem',
                          style: TextStyle(color: Color(0xFF065f46)),
                          textAlign: TextAlign.center,
                        ),
                        const SizedBox(height: 16),
                        ElevatedButton.icon(
                          onPressed: () => _viewDesign3D(context),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: const Color(0xFF10b981),
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(
                              horizontal: 24,
                              vertical: 12,
                            ),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                          ),
                          icon: const Icon(Icons.view_in_ar, size: 20),
                          label: const Text(
                            'Xem Link Thiết kế 3D',
                            style: TextStyle(fontWeight: FontWeight.w600),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

              if (request.isCompleted) const SizedBox(height: 20),

              // Rejected notice
              if (request.isRejected)
                Card(
                  elevation: 2,
                  margin: EdgeInsets.zero,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                    side: const BorderSide(color: Color(0xFFef4444), width: 2),
                  ),
                  child: Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      gradient: const LinearGradient(
                        colors: [Color(0xFFfee2e2), Color(0xFFfecaca)],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    padding: const EdgeInsets.all(20),
                    child: const Column(
                      children: [
                        Text(
                          '❌ Yêu cầu bị từ chối',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                            color: Color(0xFFdc2626),
                          ),
                        ),
                        SizedBox(height: 12),
                        Text(
                          'Vui lòng liên hệ hỗ trợ để biết thêm chi tiết',
                          style: TextStyle(color: Color(0xFFdc2626)),
                          textAlign: TextAlign.center,
                        ),
                      ],
                    ),
                  ),
                ),

              if (request.isRejected) const SizedBox(height: 20),

              // Attached Files Card
              if (request.filesList.isNotEmpty)
                Card(
                  elevation: 2,
                  margin: EdgeInsets.zero,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Container(
                    width: double.infinity,
                    padding: const EdgeInsets.all(24),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Icon(
                              Icons.attach_file,
                              color: colorScheme.primary,
                              size: 20,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              'Tài liệu đính kèm',
                              style: TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.w700,
                                color: colorScheme.onSurface,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 16),
                        _buildFilesSection(context, request.filesList),
                      ],
                    ),
                  ),
                ),

              if (request.filesList.isNotEmpty) const SizedBox(height: 20),

              // Action Button
              SizedBox(
                width: double.infinity,
                child: ElevatedButton.icon(
                  onPressed: () => _contactSupport(context),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: colorScheme.primary,
                    foregroundColor: colorScheme.onPrimary,
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  icon: const Icon(Icons.chat_bubble_outline),
                  label: const Text(
                    'Liên hệ',
                    style: TextStyle(fontWeight: FontWeight.w600),
                  ),
                ),
              ),

              const SizedBox(height: 20),
            ],
          ),
        ),
        loading: () => const CustomLoadingIndicator(),
        error: (error, stack) => Center(
          child: Padding(
            padding: const EdgeInsets.all(40),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(
                  Icons.error_outline,
                  size: 64,
                  color: AppColors.danger,
                ),
                const SizedBox(height: 16),
                Text(
                  'Lỗi tải dữ liệu: ${error.toString().replaceAll('Exception: ', '')}',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 14,
                    color: colorScheme.onSurfaceVariant,
                  ),
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () => ref.invalidate(designRequestDetailProvider(requestId)),
                  child: const Text('Thử lại'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildFilesSection(BuildContext context, List<ProjectFile> files) {
    final colorScheme = Theme.of(context).colorScheme;
    // Separate images and other files
    final images = files.where((f) => _isImageFile(f.fileUrl)).toList();
    final otherFiles = files.where((f) => !_isImageFile(f.fileUrl)).toList();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Image Gallery
        if (images.isNotEmpty) ...[
          SizedBox(
            height: 100,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: images.length,
              itemBuilder: (context, index) {
                final image = images[index];
                return Padding(
                  padding: const EdgeInsets.only(right: 12),
                  child: GestureDetector(
                    onTap: () => _showImageViewer(context, images, index),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: SizedBox(
                        width: 100,
                        height: 100,
                        child: CachedNetworkImage(
                          imageUrl: image.fileUrl,
                          fit: BoxFit.cover,
                          placeholder: (context, url) => Container(
                            color: colorScheme.surfaceContainerHighest,
                            child: Center(
                              child: CustomLoadingIndicator(color: colorScheme.primary, size: 20),
                            ),
                          ),
                          errorWidget: (context, url, error) => Container(
                            color: colorScheme.surfaceContainerHighest,
                            child: const Icon(Icons.error),
                          ),
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
          if (otherFiles.isNotEmpty) const SizedBox(height: 16),
        ],

        // Other Files as file items
        ...otherFiles.map(
          (file) => FileItem(
            fileUrl: file.fileUrl,
            icon: _getFileIcon(file.fileUrl),
          ),
        ),

        // Show image files as file items too (for download/naming)
        if (images.isNotEmpty && otherFiles.isEmpty)
          ...images.map(
            (file) => FileItem(
              fileUrl: file.fileUrl,
              icon: Icons.image,
            ),
          ),
      ],
    );
  }
}
