import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';

import '../../../common/theme/theme.dart';
import '../../router/app_router.gr.dart';

// Models (simplified)
class DrawEvent {
  final String id;
  final String name;
  final String description;
  final int entryPoints;
  final String icon;
  final Color primaryColor;
  final String prize;
  final String prizeValue;
  final DateTime drawDate;
  final int totalParticipants;
  final int hadiah;
  final String status; // 'active', 'ended'
  final int minSpending;

  DrawEvent({
    required this.id,
    required this.name,
    required this.description,
    required this.entryPoints,
    required this.icon,
    required this.primaryColor,
    required this.prize,
    required this.prizeValue,
    required this.drawDate,
    required this.totalParticipants,
    required this.hadiah,
    required this.status,
    required this.minSpending,
  });

  bool get isActive => status == 'active';
}

class UserEntry {
  final String drawId;
  final DateTime entryDate;

  UserEntry({required this.drawId, required this.entryDate});
}

@RoutePage()
class DrawPage extends StatefulWidget {
  const DrawPage({super.key});

  @override
  State<DrawPage> createState() => _DrawPageState();
}

class _DrawPageState extends State<DrawPage> {
  String selectedTab = 'active'; // 'active' or 'finished'

  final List<UserEntry> userEntries = [
    UserEntry(
      drawId: "1",
      entryDate: DateTime.now().subtract(Duration(hours: 3)),
    ),
  ];

  final List<DrawEvent> drawEvents = [
    DrawEvent(
      id: "1",
      name: "Emas 3 Gram",
      description: "Gebyar Undian Enaklo\nMenangkan hadiah menarik",
      entryPoints: 0,
      icon: "👑",
      primaryColor: AppColor.primary,
      prize: "Emas 3 Gram",
      prizeValue: "Rp 2.500.000",
      drawDate: DateTime.now().add(Duration(hours: 1, minutes: 20)),
      totalParticipants: 0,
      hadiah: 2,
      status: 'active',
      minSpending: 50000,
    ),
    DrawEvent(
      id: "2",
      name: "iPhone 15 Pro",
      description: "Undian Smartphone Premium\nDapatkan iPhone terbaru",
      entryPoints: 0,
      icon: "📱",
      primaryColor: AppColor.info,
      prize: "iPhone 15 Pro",
      prizeValue: "Rp 18.000.000",
      drawDate: DateTime.now().subtract(Duration(days: 1)),
      totalParticipants: 156,
      hadiah: 1,
      status: 'ended',
      minSpending: 100000,
    ),
  ];

  List<DrawEvent> get filteredDraws {
    return drawEvents.where((draw) {
      if (selectedTab == 'active') {
        return draw.isActive;
      } else {
        return !draw.isActive;
      }
    }).toList();
  }

  String _getTimeRemaining(DateTime targetDate) {
    final now = DateTime.now();
    final difference = targetDate.difference(now);

    if (difference.isNegative) return "Berakhir";

    if (difference.inHours > 0) {
      return "${difference.inHours}h ${difference.inMinutes % 60}m";
    } else if (difference.inMinutes > 0) {
      return "${difference.inMinutes}m";
    } else {
      return "Sekarang!";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.background,
      appBar: AppBar(title: Text("Undian")),
      body: Column(
        children: [
          // Tab selector
          Container(
            margin: EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppColor.surface,
              borderRadius: BorderRadius.circular(25),
              boxShadow: [
                BoxShadow(
                  color: AppColor.black.withOpacity(0.05),
                  blurRadius: 8,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            child: Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () => setState(() => selectedTab = 'active'),
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 12),
                      decoration: BoxDecoration(
                        color: selectedTab == 'active'
                            ? AppColor.primary
                            : Colors.transparent,
                        borderRadius: BorderRadius.circular(25),
                      ),
                      child: Text(
                        "Aktif (${drawEvents.where((d) => d.isActive).length})",
                        textAlign: TextAlign.center,
                        style: AppStyle.md.copyWith(
                          color: selectedTab == 'active'
                              ? AppColor.textWhite
                              : AppColor.textSecondary,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: () => setState(() => selectedTab = 'finished'),
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 12),
                      decoration: BoxDecoration(
                        color: selectedTab == 'finished'
                            ? AppColor.primary
                            : Colors.transparent,
                        borderRadius: BorderRadius.circular(25),
                      ),
                      child: Text(
                        "Selesai (${drawEvents.where((d) => !d.isActive).length})",
                        textAlign: TextAlign.center,
                        style: AppStyle.md.copyWith(
                          color: selectedTab == 'finished'
                              ? AppColor.textWhite
                              : AppColor.textSecondary,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          // Draw list
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.symmetric(horizontal: 16),
              itemCount: filteredDraws.length,
              itemBuilder: (context, index) {
                final draw = filteredDraws[index];
                return _buildSimpleDrawCard(draw);
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSimpleDrawCard(DrawEvent draw) {
    final timeRemaining = _getTimeRemaining(draw.drawDate);

    return GestureDetector(
      onTap: () => context.router.push(DrawDetailRoute(drawEvent: draw)),
      child: Container(
        margin: EdgeInsets.only(bottom: 8),
        padding: EdgeInsets.all(12),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [draw.primaryColor, draw.primaryColor.withOpacity(0.8)],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          borderRadius: BorderRadius.circular(8),
          boxShadow: [
            BoxShadow(
              color: AppColor.black.withOpacity(0.08),
              blurRadius: 8,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Name
                  Text(
                    draw.name,
                    style: AppStyle.md.copyWith(
                      fontWeight: FontWeight.w600,
                      color: AppColor.textWhite,
                    ),
                  ),
                  SizedBox(height: 4),
                  // Description
                  Text(
                    draw.description,
                    style: AppStyle.sm.copyWith(
                      color: AppColor.textWhite.withOpacity(0.9),
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 6),
                  // Date
                  Text(
                    draw.isActive ? "Berakhir: $timeRemaining" : "Selesai",
                    style: AppStyle.xs.copyWith(
                      color: AppColor.textWhite.withOpacity(0.8),
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
            // Price
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(draw.icon, style: AppStyle.lg),
                SizedBox(height: 2),
                Text(
                  draw.prize,
                  style: AppStyle.sm.copyWith(
                    fontWeight: FontWeight.bold,
                    color: AppColor.textWhite,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
