import 'package:flutter/material.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/cleaner_module/models/one_time_task_data.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/views/widgets/images/files_list.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';
import 'package:test_sa/views/widgets/timer/app_timer.dart';
import 'package:test_sa/models/timer_model.dart';
import 'dart:convert';

class OneTimeTaskPreviewScreen extends StatelessWidget {
  static const String routeName = "/one_time_task_preview";

  final OneTimeTaskData taskData;
  final double totalWorkingHours;
  final VoidCallback onConfirm;

  const OneTimeTaskPreviewScreen({
    Key? key,
    required this.taskData,
    required this.totalWorkingHours,
    required this.onConfirm,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // Debug logging
    print('DEBUG Preview Screen:');
    print('imageRooms count: ${taskData.imageRooms?.length ?? 0}');
    print('attachments count: ${taskData.attachments?.length ?? 0}');

    // Determine which images to show: captured images (imageRooms) or API attachments
    final hasImageRooms = taskData.imageRooms != null && taskData.imageRooms!.isNotEmpty;
    final hasAttachments = taskData.attachments != null && taskData.attachments!.isNotEmpty;

    return Scaffold(
      appBar: const DefaultAppBar(
        title: 'Preview',
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Task Information Card
                    _buildTaskInfoCard(context),
                    16.height,

                    // Working Hours Card
                    if (totalWorkingHours > 0) ...[
                      _buildWorkingHoursCard(context),
                      16.height,
                    ],

                    // Checklist Card
                    _buildChecklistCard(context),
                    16.height,

                    // Captured Images Card
                    if (hasImageRooms) ...[
                      _buildImagesCard(context),
                      16.height,
                    ],

                    // Attachments Card (from API)
                    if (hasAttachments) ...[
                      _buildAttachmentsCard(context),
                      16.height,
                    ],
                  ],
                ),
              ),
            ),

            // Footer with Confirm Button
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(
                label: context.translation.confirm,
                buttonColor: AppColor.primary10,
                onPressed: onConfirm,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTaskInfoCard(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget(
          'Task Information',
        ),
        12.height,
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (taskData.oneTimeSetting?.taskTypeName != null) InfoTextWidget(label: 'Task Type', value: taskData.oneTimeSetting!.taskTypeName!),
            if (taskData.siteName != null) InfoTextWidget(label: 'Site', value: taskData.siteName!),
            if (taskData.buildingName != null) InfoTextWidget(label: 'Building', value: taskData.buildingName!),
            if (taskData.floorName != null) InfoTextWidget(label: 'Floor', value: taskData.floorName!),
            if (taskData.departmentName != null) InfoTextWidget(label: 'Department', value: taskData.departmentName!),
            if (taskData.roomName != null) InfoTextWidget(label: 'Room', value: taskData.roomName!),
            if (taskData.locationDescription != null) InfoTextWidget(label: 'Location', value: taskData.locationDescription!),
          ],
        ).paddingAll(16),
      ],
    ).toShadowContainer(context, padding: 16);
  }

  Widget _buildWorkingHoursCard(BuildContext context) {
    // Parse timer start time from taskData if available
    DateTime? timerStartTime;
    if (taskData.startTime != null) {
      try {
        timerStartTime = DateTime.parse(taskData.startTime!);
      } catch (e) {
        print('Error parsing start time: $e');
      }
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget(
          'Working Hours',
        ),
        12.height,
        if (timerStartTime != null)
          AppTimer(
            label: 'Working Time',
            timer: TimerModel(
              startAt: timerStartTime,
              endAt: null,
              durationInSecond: 0,
            ),
            enabled: false,
            // Disable controls, just show the timer
            showTimer: true,
            decoration: BoxDecoration(
              color: context.isDark ? AppColor.neutral20.withValues(alpha: 0.5) : AppColor.neutral10.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(8),
            ),
          )
        else
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: context.isDark ? AppColor.neutral20.withValues(alpha: 0.5) : AppColor.neutral10.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                InfoTextLabelWidget(
                  label: 'Total Working Hours',
                ),
                InfoHeader16Widget(
                  CMRequestUtils.formatTotalWorkingHours(totalWorkingHours),
                ),
              ],
            ),
          ),
      ],
    ).toShadowContainer(context, padding: 16);
  }

  Widget _buildChecklistCard(BuildContext context) {
    final completedInstructions = taskData.instructions?.where((i) => i.isDone == true).toList() ?? [];
    final totalInstructions = taskData.instructions?.length ?? 0;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            InfoHeader16Widget(
              'Checklist',
            ),
            InfoTextLabelWidget(
              label: '${completedInstructions.length}/$totalInstructions',
            ),
          ],
        ),
        12.height,
        ListView.separated(
          shrinkWrap: true,
          padding: EdgeInsets.zero,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: completedInstructions.length,
          separatorBuilder: (context, index) => const Divider(height: 1, color: AppColor.neutral30, thickness: 1).paddingOnly(top: 12, bottom: 12),
          itemBuilder: (context, index) {
            final instruction = completedInstructions[index];
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Icon(
                      Icons.check_circle,
                      color: AppColor.primary10,
                      size: 20,
                    ),
                    8.width,
                    Expanded(
                      child: InfoTextLabelWidget(
                        label: instruction.instructionText ?? '',
                      ),
                    ),
                  ],
                ),
                if (instruction.comment != null && instruction.comment!.isNotEmpty) ...[
                  8.height,
                  Container(
                    width: double.infinity, // Force full width
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: context.isDark ? AppColor.neutral20.withValues(alpha: 0.5) : AppColor.neutral10.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        InfoTextLabelWidget(
                          label: 'Comment:',
                        ),
                        4.height,
                        InfoTextLabelWidget(
                          label: instruction.comment!,
                        ),
                      ],
                    ),
                  ),
                ],
              ],
            );
          },
        ).paddingAll(16),
      ],
    ).toShadowContainer(context, padding: 16);
  }

  Widget _buildImagesCard(BuildContext context) {
    // Show captured images (base64 from camera)
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget('Captured Images'),
        12.height,
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: taskData.imageRooms!.map((imageString) {
            return GestureDetector(
              onTap: () {
                context.fullScreenImageViewer(_buildImage(imageString));
              },
              child: Container(
                width: 100,
                height: 100,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color: context.isDark ? AppColor.neutral20 : AppColor.neutral30,
                  ),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: _buildImage(imageString),
                ),
              ),
            );
          }).toList(),
        ),
      ],
    ).toShadowContainer(context, padding: 16);
  }

  Widget _buildAttachmentsCard(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget(
          'Attachments',
        ),
        FilesList(
          images: taskData.attachments!.map((attachment) => URLs.getFileUrl(attachment.name ?? '') ?? '').toList(),
          showAsListView: true,
        ),
      ],
    ).toShadowContainer(context, padding: 16);
  }

  Widget _buildImage(String imageString) {
    try {
      // imageString format: "filename|base64data"
      final parts = imageString.split('|');
      final base64Data = parts.length > 1 ? parts[1] : imageString;
      return Image.memory(
        base64Decode(base64Data),
        fit: BoxFit.cover,
      );
    } catch (e) {
      return const Icon(Icons.broken_image, size: 48);
    }
  }

  Widget _buildInfoRow(BuildContext context, String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: InfoTextLabelWidget(
              label: '$label:',
            ),
          ),
          Expanded(
            child: InfoTextLabelWidget(
              label: value,
            ),
          ),
        ],
      ),
    );
  }
}
