import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/widgets/custom_error_screen.dart';
import 'package:niogu_app/core/router/app_route.dart';
import 'package:niogu_app/core/widgets/custom_empty_screen.dart';
import 'package:niogu_app/features/online_store/domain/entities/online_store.dart';
import 'package:niogu_app/features/online_store/presentation/providers/online_store_provider.dart';
import 'package:sizer/sizer.dart';

class CampaignScreen extends ConsumerWidget {
  const CampaignScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final bool isTablet = 100.w >= 600;

        List<DisplayCampaign> campaigns = [];

        final campaignState = ref.watch(campaignStreamProvider);

        campaignState.whenData((c) => campaigns = c);

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: TopBackBarApp(
              title: "Daftar Campaign",
              onTap: () => context.pop(),
            ),
            body: campaignState.when(
              data: (campaigns) {
                if (campaigns.isEmpty) {
                  return CustomEmptyScreen(
                    title: "Tidak Ada Campaign",
                    body: "Kamu belum membuat campaign",
                    textButton: "Buat Campaign Baru",
                    onPressed: () {
                      context.pushNamed(AppRoute.addCampaignScreen);
                    },
                  );
                }
                return ListView.builder(
                  padding: EdgeInsets.all(5.w),
                  itemCount: campaigns.length,
                  itemBuilder: (context, index) {
                    final campaign = campaigns[index];

                    final startDate = campaign.startDate;

                    final endDate = campaign.endDate;

                    final bool imagePathAvailable =
                        campaign.imagePath.isNotEmpty;

                    final File imageFile = File(
                      imagePathAvailable
                          ? campaign.imagePath
                          : "image not found",
                    );

                    final bool imageFileExists = imageFile.existsSync();

                    return GestureDetector(
                      onTap: () {
                        context.pushNamed(
                          AppRoute.editCampaignScreen,
                          pathParameters: {"id": campaign.id},
                        );
                      },
                      child: Container(
                        margin: EdgeInsets.only(bottom: 2.5.h),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(3.w),
                          border: Border.all(color: Colors.grey.shade200),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.02),
                              blurRadius: 10,
                            ),
                          ],
                        ),
                        child: Column(
                          children: [
                            Container(
                              height: 18.h,
                              decoration: BoxDecoration(
                                color: Colors.grey[100],
                                borderRadius: BorderRadius.vertical(
                                  top: Radius.circular(3.w),
                                ),
                              ),
                              child: Center(
                                child: imageFileExists
                                    ? ClipRRect(
                                        borderRadius: BorderRadius.circular(
                                          2.5.w,
                                        ),
                                        child: Image.file(
                                          imageFile,
                                          fit: BoxFit.cover,
                                          width: double.infinity,
                                          height: double.infinity,
                                          errorBuilder:
                                              (context, error, stackTrace) {
                                                return Icon(
                                                  Icons.error,
                                                  color: Colors.grey[400],
                                                  size: 10.w,
                                                );
                                              },
                                        ),
                                      )
                                    : Icon(
                                        Icons.image_outlined,
                                        size: 10.w,
                                        color: Colors.grey[400],
                                      ),
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.all(4.w),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        campaign.name,
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: isTablet
                                              ? AppFontSize.medium.sp
                                              : AppFontSize.small.sp,
                                        ),
                                      ),

                                      SizedBox(height: 0.75.h),

                                      Text(
                                        startDate != null && endDate != null
                                            ? "${DateFormat('dd MMM').format(startDate)} - ${DateFormat('dd MMM yyyy').format(endDate)}"
                                            : "Selalu di tampilkan",
                                        style: TextStyle(
                                          color: Colors.grey.shade700,
                                          fontSize: isTablet
                                              ? (AppFontSize.medium - 1.25).sp
                                              : (AppFontSize.small - 1.25).sp,
                                        ),
                                      ),

                                      SizedBox(height: 0.75.h),

                                      Text(
                                        "${campaign.outletUseAmount} Outlet menampilkan",
                                        style: TextStyle(
                                          color: Colors.grey.shade700,
                                          fontSize: isTablet
                                              ? (AppFontSize.medium - 1.25).sp
                                              : (AppFontSize.small - 1.25).sp,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ],
                                  ),
                                  Container(
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 3.w,
                                      vertical: 0.5.h,
                                    ),
                                    decoration: BoxDecoration(
                                      color: campaign.isActive
                                          ? Colors.green.withOpacity(0.1)
                                          : Colors.grey.withOpacity(0.1),
                                      borderRadius: BorderRadius.circular(5.w),
                                    ),
                                    child: Text(
                                      campaign.isActive ? "Aktif" : "Berakhir",
                                      style: TextStyle(
                                        color: campaign.isActive
                                            ? Colors.green
                                            : Colors.grey,
                                        fontWeight: FontWeight.bold,
                                        fontSize: isTablet
                                            ? (AppFontSize.medium - 1.25).sp
                                            : (AppFontSize.small - 1.25).sp,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                );
              },
              error: (error, stackTrace) => CustomErrorScreen(
                message: "Ups, terjadi kesalahan",
                onRefresh: () {},
              ),
              loading: () => const SizedBox(),
            ),
            bottomNavigationBar: campaigns.isEmpty || campaignState.isLoading
                ? null
                : Container(
                    padding: EdgeInsets.all(5.w),
                    child: ElevatedButton(
                      onPressed: () {
                        context.pushNamed(AppRoute.addCampaignScreen);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColor.primaryColor,
                        minimumSize: Size(double.infinity, 6.5.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(3.w),
                        ),
                      ),
                      child: Text(
                        "Buat Campaign Baru",
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: AppFontSize.medium.sp,
                        ),
                      ),
                    ),
                  ),
          ),
        );
      },
    );
  }
}
