import 'package:flutter/material.dart';
import 'package:tugas_akhir_supabase/screens/community/models/farming_guide_model.dart';
import 'package:tugas_akhir_supabase/screens/community/services/guide_service.dart';

class GuideDetailDialog extends StatelessWidget {
  final FarmingGuideModel guide;

  const GuideDetailDialog({super.key, required this.guide});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Container(
        width: double.infinity,
        constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height * 0.8,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildHeader(context),
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        guide.title,
                        style: const TextStyle(
                          fontSize: 22,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: guide.getCategoryColor().withOpacity(0.1),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          guide.category,
                          style: TextStyle(
                            color: guide.getCategoryColor(),
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      const SizedBox(height: 20),
                      Text(
                        guide.content,
                        style: const TextStyle(fontSize: 16, height: 1.5),
                      ),
                      const SizedBox(height: 20),
                      Align(
                        alignment: Alignment.centerRight,
                        child: Text(
                          'Dibuat: ${guide.getFormattedDate()}',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader(BuildContext context) {
    // Cek dan perbaiki URL gambar jika ada
    final String? fixedImageUrl =
        guide.imageUrl != null && guide.imageUrl!.isNotEmpty
            ? GuideService().fixImageUrl(guide.imageUrl)
            : null;

    debugPrint('Detail dialog for guide: ${guide.title}');
    debugPrint('Original image URL: ${guide.imageUrl}');
    debugPrint('Fixed image URL: $fixedImageUrl');

    return Stack(
      children: [
        // Header dengan gambar atau ikon
        ClipRRect(
          borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
          child:
              fixedImageUrl != null
                  ? Stack(
                    children: [
                      // Loading placeholder
                      Container(
                        height: 200,
                        width: double.infinity,
                        color: guide.getCategoryColor().withOpacity(0.1),
                        child: Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                width: 40,
                                height: 40,
                                child: CircularProgressIndicator(
                                  color: guide.getCategoryColor(),
                                  strokeWidth: 3,
                                ),
                              ),
                              const SizedBox(height: 12),
                              Text(
                                'Memuat gambar...',
                                style: TextStyle(
                                  color: guide.getCategoryColor(),
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      // Actual image with error handling
                      Image.network(
                        fixedImageUrl,
                        height: 200,
                        width: double.infinity,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          debugPrint('Error loading detail image: $error');
                          debugPrint('Failed URL: $fixedImageUrl');
                          return Container(
                            height: 200,
                            width: double.infinity,
                            color: guide.getCategoryColor().withOpacity(0.1),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.broken_image_rounded,
                                  size: 64,
                                  color: Colors.grey[400],
                                ),
                                const SizedBox(height: 16),
                                const Text(
                                  'Gambar tidak dapat dimuat',
                                  style: TextStyle(
                                    color: Colors.grey,
                                    fontSize: 16,
                                  ),
                                ),
                                const SizedBox(height: 8),
                                Padding(
                                  padding: const EdgeInsets.symmetric(
                                    horizontal: 20,
                                  ),
                                  child: Text(
                                    fixedImageUrl,
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.grey[500],
                                    ),
                                    textAlign: TextAlign.center,
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      ),
                    ],
                  )
                  : _buildDefaultHeader(),
        ),
        // Tombol tutup
        Positioned(
          top: 8,
          right: 8,
          child: GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              padding: const EdgeInsets.all(4),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.8),
                shape: BoxShape.circle,
              ),
              child: const Icon(Icons.close, color: Colors.black87),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildDefaultHeader() {
    return Container(
      height: 150,
      width: double.infinity,
      color: guide.getCategoryColor().withOpacity(0.2),
      child: Center(
        child: Icon(
          guide.getCategoryIcon(),
          size: 80,
          color: guide.getCategoryColor(),
        ),
      ),
    );
  }

  // Static method untuk menampilkan dialog
  static void show(BuildContext context, FarmingGuideModel guide) {
    showDialog(
      context: context,
      builder: (context) => GuideDetailDialog(guide: guide),
    );
  }
}
