import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/models/overview_data.dart';
import 'package:didvan/models/requests/news.dart';
import 'package:didvan/models/requests/radar.dart';
import 'package:didvan/models/requests/studio.dart';
import 'package:didvan/providers/user.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/services/media/media.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/utils/date_time.dart';
import 'package:didvan/views/podcasts/studio_details/studio_details_state.dart';
import 'package:didvan/views/widgets/bookmark_button.dart';
import 'package:didvan/views/widgets/didvan/card.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/didvan/text_field.dart';
import 'package:didvan/views/widgets/shimmer_placeholder.dart';
import 'package:didvan/views/widgets/skeleton_image.dart';
import 'package:flutter/material.dart';
import 'package:persian_number_utility/persian_number_utility.dart';
import 'package:provider/provider.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:url_launcher/url_launcher_string.dart';

class MultitypeOverview extends StatelessWidget {
  final OverviewData item;
  final bool hasUnmarkConfirmation;
  final void Function(int id, bool value) onMarkChanged;
  final bool enableCaption;
  final bool enableBookmark;

  const MultitypeOverview({
    Key? key,
    required this.item,
    required this.onMarkChanged,
    this.hasUnmarkConfirmation = false,
    this.enableCaption = false,
    this.enableBookmark = false,
  }) : super(key: key);

  get _targetPageArgs {
    if (item.type == 'radar') {
      return const RadarRequestArgs(page: 0);
    }
    if (item.type == 'news') {
      return const NewsRequestArgs(page: 0);
    }
    return StudioRequestArgs(page: 0, type: item.type);
  }

  String? get _targetPageRouteName {
    if (item.type == 'radar') {
      return Routes.radarDetails;
    }
    if (item.type == 'news') {
      return Routes.newsDetails;
    }
    if (item.type == 'podcast') {
      return Routes.podcasts;
    }
    if (item.type == 'video') {
      return Routes.videocasts;
    }
    return null;
  }

  IconData get _icon {
    switch (item.type) {
      case 'radar':
        return DidvanIcons.scanning_light;
      case 'news':
        return DidvanIcons.foolad_light;
      case 'video':
        return DidvanIcons.video_light;
      case 'podcast':
        return DidvanIcons.podcast_light;
      case 'delphi':
      case 'survey':
        return DidvanIcons.saha_light;
      case 'infography':
        return DidvanIcons.infography_regular;
      default:
        return DidvanIcons.radar_light;
    }
  }

  @override
  Widget build(BuildContext context) {
    return DidvanCard(
      onTap: () async {
        if (item.type == 'infography') {
          return;
        }
        if (item.type == 'podcast') {
          final state = context.read<StudioDetailsState>();
          await state.getStudioDetails(
            item.id,
            args: const StudioRequestArgs(page: 0, type: 'podcast'),
          );
          MediaService.currentPodcast = state.studio;
          MediaService.handleAudioPlayback(
            audioSource: item.link,
            id: item.id,
            isNetworkAudio: true,
            isVoiceMessage: false,
          );
          return;
        }
        if (_targetPageRouteName == null && item.link != null) {
          AppInitializer.openWebLink(
            context,
            '${item.link!}?accessToken=${RequestService.token}',
            mode: LaunchMode.inAppWebView,
          );
          return;
        }
        Navigator.of(context).pushNamed(
          _targetPageRouteName!,
          arguments: {
            'onMarkChanged': onMarkChanged,
            'id': item.id,
            'args': _targetPageArgs,
            'hasUnmarkConfirmation': hasUnmarkConfirmation,
          },
        );
      },
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Stack(
                children: [
                  SkeletonImage(imageUrl: item.image, height: 80, width: 80),
                  Container(
                    padding:
                        const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.secondary,
                      borderRadius: const BorderRadius.horizontal(
                        left: Radius.circular(10),
                      ),
                    ),
                    child: Icon(
                      _icon,
                      color: Theme.of(context).colorScheme.white,
                      size: 18,
                    ),
                  ),
                ],
              ),
              const SizedBox(width: 8),
              Expanded(
                child: SizedBox(
                  height: 80,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      DidvanText(
                        item.title,
                        style: Theme.of(context).textTheme.bodyLarge,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      Flexible(
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Icon(
                                  DidvanIcons.calendar_day_light,
                                  size: 16,
                                ),
                                const SizedBox(width: 4),
                                DidvanText(
                                  DateTime.parse(item.createdAt)
                                      .toPersianDateStr(),
                                  style: Theme.of(context).textTheme.labelSmall,
                                ),
                              ],
                            ),
                            const Spacer(),
                            if ((item.timeToRead ?? item.duration) != null)
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Icon(
                                    DidvanIcons.timer_light,
                                    size: 16,
                                  ),
                                  const SizedBox(width: 4),
                                  DidvanText(
                                    item.timeToRead != null
                                        ? '${item.timeToRead} دقیقه'
                                        : DateTimeUtils.normalizeTimeDuration(
                                            Duration(seconds: item.duration!),
                                          ),
                                    style:
                                        Theme.of(context).textTheme.labelSmall,
                                  ),
                                ],
                              ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              if (enableCaption)
                Expanded(
                  child: Column(
                    children: [
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          Icon(
                            Icons.edit_outlined,
                            size: 16,
                            color: Theme.of(context).colorScheme.caption,
                          ),
                          const SizedBox(width: 4),
                          DidvanText(
                            'یادداشت‌های من',
                            style: Theme.of(context).textTheme.labelSmall,
                            color: Theme.of(context).colorScheme.caption,
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Flexible(
                            child: Container(
                              height: 1,
                              color: Theme.of(context).colorScheme.primary,
                            ),
                          ),
                          Flexible(
                            flex: 2,
                            child: Container(
                              height: 1,
                              color: Theme.of(context).colorScheme.border,
                            ),
                          )
                        ],
                      ),
                      DidvanTextField(
                        disableBorders: true,
                        initialValue: item.description,
                        hintText: 'برای اضافه کردن یادداشت لمس کنید.',
                        onChanged: (value) => UserProvider.changeItemMark(
                          item.type,
                          item.id,
                          null,
                          description: value,
                        ),
                        isSmall: true,
                      ),
                    ],
                  ),
                ),
              if (!enableCaption) const Spacer(),
              if (enableBookmark) ...[
                const SizedBox(
                  width: 12,
                ),
                BookmarkButton(
                  value: item.marked,
                  onMarkChanged: (value) => onMarkChanged(item.id, value),
                  gestureSize: 32,
                  type: item.type,
                  itemId: item.id,
                  askForConfirmation: true,
                ),
              ],
            ],
          ),
        ],
      ),
    );
  }

  static Widget get placeholder => const DidvanCard(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ShimmerPlaceholder(height: 80, width: 80),
            SizedBox(width: 8),
            SizedBox(
              height: 80,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ShimmerPlaceholder(height: 18, width: 150),
                  SizedBox(height: 8),
                  ShimmerPlaceholder(height: 18, width: 100),
                  Spacer(),
                  ShimmerPlaceholder(height: 14, width: 80),
                ],
              ),
            ),
          ],
        ),
      );
}
