import 'dart:math';

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/routes/routes.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:didvan/services/media/media.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/views/podcasts/studio_details/studio_details_state.dart';
import 'package:didvan/views/widgets/didvan/card.dart';
import 'package:didvan/views/widgets/didvan/text.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:url_launcher/url_launcher_string.dart';

class SearchResultItem extends StatelessWidget {
  final OverviewData item;

  const SearchResultItem({
    Key? key,
    required this.item,
  }) : 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 {
    if (item.type == 'radar') {
      return DidvanIcons.scanning_light;
    }
    if (item.type == 'news') {
      return DidvanIcons.foolad_light;
    }
    if (item.type == 'video') {
      return DidvanIcons.video_light;
    }
    if (item.type == 'podcast') {
      return DidvanIcons.podcast_light;
    }
    if (item.type == 'delphi') {
      return DidvanIcons.saha_light;
    }
    if (item.type == 'infography') {
      return DidvanIcons.infography_regular;
    }
    return DidvanIcons.radar_light;
  }

  void _openInteractiveViewer(BuildContext context, String image) {
    showDialog(
      context: context,
      builder: (context) => Stack(
        children: [
          Positioned.fill(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: InteractiveViewer(
                child: Center(
                  child: SkeletonImage(
                    width: min(MediaQuery.of(context).size.width,
                        MediaQuery.of(context).size.height),
                    imageUrl: image,
                  ),
                ),
              ),
            ),
          ),
          Positioned(
            right: 24,
            top: 24,
            child: Container(
                decoration: const BoxDecoration(
                    color: Colors.white, shape: BoxShape.circle),
                child: const BackButton()),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return DidvanCard(
      onTap: () async {
        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 (item.type == "infography") {
          _openInteractiveViewer(context, item.image);
        } else if (_targetPageRouteName == null && item.link != null) {
          AppInitializer.openWebLink(
            context,
            '${item.link!}?accessToken=${RequestService.token}',
            mode: LaunchMode.inAppWebView,
          );
          return;
        }
        Navigator.of(context).pushNamed(
          _targetPageRouteName!,
          arguments: {
            'id': item.id,
            'args': _targetPageArgs,
          },
        );
      },
      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: 200,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      DidvanText(
                        item.title,
                        style: Theme.of(context).textTheme.bodyLarge,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      Row(
                        children: [
                          const Icon(
                            DidvanIcons.calendar_day_light,
                            size: 18,
                          ),
                          const SizedBox(width: 4),
                          DidvanText(
                            DateTime.parse(item.createdAt).toPersianDateStr(),
                            style: Theme.of(context).textTheme.labelSmall,
                          ),
                          const Spacer(),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  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),
                ],
              ),
            ),
          ],
        ),
      );
}
