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

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/presentation/pages/model_houses_page.dart';

/// Design Request Detail Page
///
/// Shows complete details of a design request including:
/// - Request header with ID, date, and status
/// - Project information grid (area, style, budget, status)
/// - Completion highlight (if completed) with 3D design link
/// - Project details (name, description, contact, files)
/// - Status timeline
/// - Action buttons (edit, contact)
class DesignRequestDetailPage extends ConsumerWidget {
  const DesignRequestDetailPage({required this.requestId, super.key});

  final String requestId;

  // Mock data - in real app, this would come from a provider
  Map<String, dynamic> _getRequestData() {
    final mockData = {
      'YC001': {
        'id': 'YC001',
        'name': 'Thiết kế nhà phố 3 tầng - Anh Minh (Quận 7)',
        'area': '120m²',
        'style': 'Hiện đại',
        'budget': '300-500 triệu',
        'status': DesignRequestStatus.completed,
        'statusText': 'Đã hoàn thành',
        'description':
            'Thiết kế nhà phố 3 tầng phong cách hiện đại với 4 phòng ngủ, 3 phòng tắm, phòng khách rộng rãi và khu bếp mở. '
            'Ưu tiên sử dụng gạch men màu sáng để tạo cảm giác thoáng đãng. '
            'Tầng 1: garage, phòng khách, bếp. '
            'Tầng 2: 2 phòng ngủ, 2 phòng tắm. '
            'Tầng 3: phòng ngủ master, phòng làm việc, sân thượng.',
        'contact': 'SĐT: 0901234567 | Email: minh.nguyen@email.com',
        'createdDate': '20/10/2024',
        'files': ['mat-bang-hien-tai.jpg', 'ban-ve-kien-truc.dwg'],
        'designLink': 'https://example.com/3d-design/YC001',
        'timeline': [
          {
            'title': 'Thiết kế hoàn thành',
            'description': 'File thiết kế 3D đã được gửi đến khách hàng',
            'date': '25/10/2024 - 14:30',
            'status': DesignRequestStatus.completed,
          },
          {
            'title': 'Bắt đầu thiết kế',
            'description': 'KTS Nguyễn Văn An đã nhận và bắt đầu thiết kế',
            'date': '22/10/2024 - 09:00',
            'status': DesignRequestStatus.designing,
          },
          {
            'title': 'Tiếp nhận yêu cầu',
            'description': 'Yêu cầu thiết kế đã được tiếp nhận và xem xét',
            'date': '20/10/2024 - 16:45',
            'status': DesignRequestStatus.pending,
          },
          {
            'title': 'Gửi yêu cầu',
            'description': 'Yêu cầu thiết kế đã được gửi thành công',
            'date': '20/10/2024 - 16:30',
            'status': DesignRequestStatus.pending,
          },
        ],
      },
      'YC002': {
        'id': 'YC002',
        'name': 'Cải tạo căn hộ chung cư - Chị Lan (Quận 2)',
        'area': '85m²',
        'style': 'Scandinavian',
        'budget': '100-300 triệu',
        'status': DesignRequestStatus.designing,
        'statusText': 'Đang thiết kế',
        'description':
            'Cải tạo căn hộ chung cư 3PN theo phong cách Scandinavian. '
            'Tối ưu không gian lưu trữ, sử dụng gạch men màu sáng và gỗ tự nhiên.',
        'contact': 'SĐT: 0987654321',
        'createdDate': '25/10/2024',
        'files': ['hinh-anh-hien-trang.jpg'],
        'designLink': null,
        'timeline': [
          {
            'title': 'Bắt đầu thiết kế',
            'description': 'KTS đã nhận và đang tiến hành thiết kế',
            'date': '26/10/2024 - 10:00',
            'status': DesignRequestStatus.designing,
          },
          {
            'title': 'Tiếp nhận yêu cầu',
            'description': 'Yêu cầu thiết kế đã được tiếp nhận',
            'date': '25/10/2024 - 14:30',
            'status': DesignRequestStatus.pending,
          },
          {
            'title': 'Gửi yêu cầu',
            'description': 'Yêu cầu thiết kế đã được gửi thành công',
            'date': '25/10/2024 - 14:15',
            'status': DesignRequestStatus.pending,
          },
        ],
      },
      'YC003': {
        'id': 'YC003',
        'name': 'Thiết kế biệt thự 2 tầng - Anh Đức (Bình Dương)',
        'area': '200m²',
        'style': 'Luxury',
        'budget': 'Trên 1 tỷ',
        'status': DesignRequestStatus.pending,
        'statusText': 'Chờ tiếp nhận',
        'description':
            'Thiết kế biệt thự 2 tầng phong cách luxury với hồ bơi và sân vườn. '
            '5 phòng ngủ, 4 phòng tắm, phòng giải trí và garage 2 xe.',
        'contact': 'SĐT: 0923456789 | Email: duc.le@gmail.com',
        'createdDate': '28/10/2024',
        'files': ['mat-bang-dat.pdf', 'y-tuong-thiet-ke.jpg'],
        'designLink': null,
        'timeline': [
          {
            'title': 'Gửi yêu cầu',
            'description': 'Yêu cầu thiết kế đã được gửi thành công',
            'date': '28/10/2024 - 11:20',
            'status': DesignRequestStatus.pending,
          },
        ],
      },
    };

    return mockData[requestId] ?? mockData['YC001']!;
  }

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

  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);
    }
  }

  IconData _getTimelineIcon(DesignRequestStatus status, int index) {
    if (status == DesignRequestStatus.completed) {
      return Icons.check;
    } else if (status == DesignRequestStatus.designing) {
      return Icons.architecture;
    } else {
      return index == 0 ? Icons.send : Icons.access_time;
    }
  }

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

    if (['jpg', 'jpeg', 'png', 'gif'].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;
  }

  Future<void> _viewDesign3D(BuildContext context, String? designLink) async {
    if (designLink != null) {
      final uri = Uri.parse(designLink);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      } else {
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Không thể mở link thiết kế 3D'),
              backgroundColor: AppColors.danger,
            ),
          );
        }
      }
    } else {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Link thiết kế 3D chưa có sẵn'),
            backgroundColor: AppColors.warning,
          ),
        );
      }
    }
  }

  void _editRequest(BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text(
          'Chức năng chỉnh sửa yêu cầu sẽ được triển khai trong phiên bản tiếp theo',
        ),
      ),
    );
  }

  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,
    String requestId,
    String name,
  ) async {
    try {
      await Share.share(
        'Yêu cầu thiết kế #$requestId\n$name',
        subject: 'Chia sẻ yêu cầu thiết kế',
      );
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Lỗi khi chia sẻ: $e'),
            backgroundColor: AppColors.danger,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final request = _getRequestData();
    final status = request['status'] as DesignRequestStatus;
    final timeline = request['timeline'] as List<Map<String, dynamic>>;
    final files = request['files'] as List<String>;

    return Scaffold(
      backgroundColor: AppColors.grey50,
      appBar: AppBar(
        backgroundColor: AppColors.white,
        elevation: AppBarSpecs.elevation,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        centerTitle: false,
        title: const Text(
          'Chi tiết Yêu cầu',
          style: TextStyle(
            color: Colors.black,
            fontSize: 20,
            fontWeight: FontWeight.w600,
          ),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.share, color: Colors.black),
            onPressed: () => _shareRequest(
              context,
              request['id'] as String,
              request['name'] as String,
            ),
          ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            // Request Header Card
            Card(
              elevation: 2,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              child: Padding(
                padding: const EdgeInsets.all(24),
                child: Column(
                  children: [
                    // Request ID and Date
                    Text(
                      '#${request['id']}',
                      style: const TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.w700,
                        color: AppColors.grey900,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      'Ngày gửi: ${request['createdDate']}',
                      style: const TextStyle(
                        fontSize: 14,
                        color: AppColors.grey500,
                      ),
                    ),
                    const SizedBox(height: 16),

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

                    const SizedBox(height: 24),

                    // Info Grid
                    _InfoGrid(
                      area: request['area'] as String,
                      style: request['style'] as String,
                      budget: request['budget'] as String,
                      statusText: request['statusText'] as String,
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 20),

            // Completion Highlight (only if completed)
            if (status == DesignRequestStatus.completed)
              Container(
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [Color(0xFFd1fae5), Color(0xFFa7f3d0)],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  border: Border.all(color: const Color(0xFF10b981), width: 2),
                  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,
                        request['designLink'] as String?,
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF10b981),
                        padding: const EdgeInsets.symmetric(
                          horizontal: 24,
                          vertical: 12,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      icon: const Icon(Icons.view_in_ar, color: Colors.white),
                      label: const Text(
                        'Xem Link Thiết kế 3D',
                        style: TextStyle(
                          fontWeight: FontWeight.w600,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ],
                ),
              ),

            if (status == DesignRequestStatus.completed)
              const SizedBox(height: 20),

            // Project Details Card
            Card(
              elevation: 2,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              child: Padding(
                padding: const EdgeInsets.all(24),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Project Name
                    _SectionHeader(icon: Icons.info, title: 'Thông tin dự án'),
                    const SizedBox(height: 12),
                    RichText(
                      text: TextSpan(
                        style: const TextStyle(
                          fontSize: 14,
                          color: AppColors.grey500,
                          height: 1.6,
                        ),
                        children: [
                          const TextSpan(
                            text: 'Tên dự án: ',
                            style: TextStyle(fontWeight: FontWeight.w600),
                          ),
                          TextSpan(text: request['name'] as String),
                        ],
                      ),
                    ),

                    const SizedBox(height: 24),

                    // Description
                    _SectionHeader(icon: Icons.edit, title: 'Mô tả yêu cầu'),
                    const SizedBox(height: 12),
                    Text(
                      request['description'] as String,
                      style: const TextStyle(
                        fontSize: 14,
                        color: AppColors.grey500,
                        height: 1.6,
                      ),
                    ),

                    const SizedBox(height: 24),

                    // Contact Info
                    _SectionHeader(
                      icon: Icons.phone,
                      title: 'Thông tin liên hệ',
                    ),
                    const SizedBox(height: 12),
                    Text(
                      request['contact'] as String,
                      style: const TextStyle(
                        fontSize: 14,
                        color: AppColors.grey500,
                        height: 1.6,
                      ),
                    ),

                    const SizedBox(height: 24),

                    // Files
                    _SectionHeader(
                      icon: Icons.attach_file,
                      title: 'Tài liệu đính kèm',
                    ),
                    const SizedBox(height: 16),
                    if (files.isEmpty)
                      const Text(
                        'Không có tài liệu đính kèm',
                        style: TextStyle(
                          color: AppColors.grey500,
                          fontStyle: FontStyle.italic,
                        ),
                      )
                    else
                      ...files.map(
                        (file) =>
                            _FileItem(fileName: file, icon: _getFileIcon(file)),
                      ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 20),

            // Timeline Card
            Card(
              elevation: 2,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              child: Padding(
                padding: const EdgeInsets.all(24),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _SectionHeader(
                      icon: Icons.history,
                      title: 'Lịch sử trạng thái',
                    ),
                    const SizedBox(height: 16),
                    ...List.generate(timeline.length, (index) {
                      final item = timeline[index];
                      return _TimelineItem(
                        title: item['title'] as String,
                        description: item['description'] as String,
                        date: item['date'] as String,
                        status: item['status'] as DesignRequestStatus,
                        icon: _getTimelineIcon(
                          item['status'] as DesignRequestStatus,
                          timeline.length - index - 1,
                        ),
                        isLast: index == timeline.length - 1,
                        getStatusColor: _getStatusColor,
                        getStatusBackgroundColor: _getStatusBackgroundColor,
                      );
                    }),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 20),

            // Action Buttons
            Row(
              children: [
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () => _editRequest(context),
                    style: OutlinedButton.styleFrom(
                      foregroundColor: AppColors.grey900,
                      side: const BorderSide(
                        color: AppColors.grey100,
                        width: 2,
                      ),
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    icon: const Icon(Icons.edit),
                    label: const Text(
                      'Chỉnh sửa',
                      style: TextStyle(fontWeight: FontWeight.w600),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: () => _contactSupport(context),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColors.primaryBlue,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    icon: const Icon(Icons.chat_bubble),
                    label: const Text(
                      'Liên hệ',
                      style: TextStyle(fontWeight: FontWeight.w600),
                    ),
                  ),
                ),
              ],
            ),

            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }
}

/// Info Grid Widget
class _InfoGrid extends StatelessWidget {
  const _InfoGrid({
    required this.area,
    required this.style,
    required this.budget,
    required this.statusText,
  });

  final String area;
  final String style;
  final String budget;
  final String statusText;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
              child: _InfoItem(label: 'Diện tích', value: area),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: _InfoItem(label: 'Phong cách', value: style),
            ),
          ],
        ),
        const SizedBox(height: 16),
        Row(
          children: [
            Expanded(
              child: _InfoItem(label: 'Ngân sách', value: budget),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: _InfoItem(label: 'Trạng thái', value: statusText),
            ),
          ],
        ),
      ],
    );
  }
}

/// Info Item Widget
class _InfoItem extends StatelessWidget {
  const _InfoItem({required this.label, required this.value});

  final String label;
  final String value;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
      decoration: BoxDecoration(
        color: AppColors.grey50,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Text(
            label,
            style: const TextStyle(
              fontSize: 12,
              color: AppColors.grey500,
              fontWeight: FontWeight.w600,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 4),
          Text(
            value,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w700,
              color: AppColors.grey900,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}

/// Section Header Widget
class _SectionHeader extends StatelessWidget {
  const _SectionHeader({required this.icon, required this.title});

  final IconData icon;
  final String title;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Icon(icon, color: AppColors.primaryBlue, size: 20),
        const SizedBox(width: 8),
        Text(
          title,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w700,
            color: AppColors.grey900,
          ),
        ),
      ],
    );
  }
}

/// File Item Widget
class _FileItem extends StatelessWidget {
  const _FileItem({required this.fileName, required this.icon});

  final String fileName;
  final IconData icon;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppColors.grey50,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: AppColors.primaryBlue,
              borderRadius: BorderRadius.circular(6),
            ),
            child: Icon(icon, color: Colors.white, size: 16),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              fileName,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: AppColors.grey900,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// Timeline Item Widget
class _TimelineItem extends StatelessWidget {
  const _TimelineItem({
    required this.title,
    required this.description,
    required this.date,
    required this.status,
    required this.icon,
    required this.isLast,
    required this.getStatusColor,
    required this.getStatusBackgroundColor,
  });

  final String title;
  final String description;
  final String date;
  final DesignRequestStatus status;
  final IconData icon;
  final bool isLast;
  final Color Function(DesignRequestStatus) getStatusColor;
  final Color Function(DesignRequestStatus) getStatusBackgroundColor;

  @override
  Widget build(BuildContext context) {
    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Icon and line
          Column(
            children: [
              Container(
                width: 40,
                height: 40,
                decoration: BoxDecoration(
                  color: getStatusBackgroundColor(status),
                  shape: BoxShape.circle,
                ),
                child: Icon(icon, color: getStatusColor(status), size: 20),
              ),
              if (!isLast)
                Expanded(
                  child: Container(
                    width: 2,
                    margin: const EdgeInsets.symmetric(vertical: 4),
                    color: AppColors.grey100,
                  ),
                ),
            ],
          ),

          const SizedBox(width: 16),

          // Content
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(bottom: isLast ? 0 : 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontWeight: FontWeight.w600,
                      color: AppColors.grey900,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    description,
                    style: const TextStyle(
                      fontSize: 14,
                      color: AppColors.grey500,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    date,
                    style: const TextStyle(
                      fontSize: 12,
                      color: AppColors.grey500,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
