// ignore_for_file: use_build_context_synchronously
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:kmobile/data/models/payment_response.dart';
import 'package:lottie/lottie.dart';
import 'package:share_plus/share_plus.dart';
import 'package:path_provider/path_provider.dart';
import '../../../l10n/app_localizations.dart';
import 'package:confetti/confetti.dart';

class PaymentAnimationScreen extends StatefulWidget {
  final Future<PaymentResponse> paymentResponse;

  const PaymentAnimationScreen({super.key, required this.paymentResponse});

  @override
  State<PaymentAnimationScreen> createState() => _PaymentAnimationScreenState();
}

class _PaymentAnimationScreenState extends State<PaymentAnimationScreen> {
  final GlobalKey _shareKey = GlobalKey();
  late ConfettiController _confettiController;

  @override
  void initState() {
    super.initState();
    _confettiController =
        ConfettiController(duration: const Duration(seconds: 2));
  }

  @override
  void dispose() {
    _confettiController.dispose();
    super.dispose();
  }

  Future<void> _shareScreenshot() async {
    try {
      RenderRepaintBoundary boundary =
          _shareKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      ui.Image image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();

      final tempDir = await getTemporaryDirectory();
      final file = await File('${tempDir.path}/payment_result.png').create();
      await file.writeAsBytes(pngBytes);

      await Share.shareXFiles(
        [XFile(file.path)],
        text: AppLocalizations.of(context).paymentResult,
      );
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            '${AppLocalizations.of(context).failedToShareScreenshot}: $e',
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<PaymentResponse>(
        future: widget.paymentResponse,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: Lottie.asset(
                'assets/animations/rupee.json',
                width: 200,
                height: 200,
                repeat: true,
              ),
            );
          }

          final response = snapshot.data!;
          final isSuccess = response.isSuccess;

          if (isSuccess) _confettiController.play();

          return Stack(
            children: [
              Align(
                alignment: Alignment.topCenter,
                child: ConfettiWidget(
                  confettiController: _confettiController,
                  blastDirectionality: BlastDirectionality.explosive,
                  emissionFrequency: 0.2,
                  numberOfParticles: 40,
                  gravity: 0.3,
                  maxBlastForce: 25,
                  minBlastForce: 10,
                  shouldLoop: false,
                  colors: const [
                    Colors.green,
                    Colors.blue,
                    Colors.pink,
                    Colors.orange,
                  ],
                ),
              ),
              Center(
                child: RepaintBoundary(
                  key: _shareKey,
                  child: Container(
                    color: Theme.of(context).scaffoldBackgroundColor,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const SizedBox(height: 80),
                        Lottie.asset(
                          isSuccess
                              ? 'assets/animations/done.json'
                              : 'assets/animations/error.json',
                          width: 200,
                          height: 200,
                          repeat: false,
                        ),
                        const SizedBox(height: 10),
                        isSuccess
                            ? Column(
                                children: [
                                  Text(
                                    AppLocalizations.of(context)
                                        .paymentSuccessful,
                                    style: const TextStyle(
                                      fontSize: 22,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.green,
                                    ),
                                  ),
                                  const SizedBox(height: 16),
                                  if (response.amount != null)
                                    Text(
                                      '${AppLocalizations.of(context).amount}: ${response.amount} ${response.currency ?? ""}',
                                      style: const TextStyle(
                                        fontSize: 18,
                                        fontWeight: FontWeight.w700,
                                        fontFamily: 'Rubik',
                                      ),
                                    ),
                                  if (response.creditedAccount != null)
                                    Text(
                                      '${AppLocalizations.of(context).creditedAccount}: ${response.creditedAccount}',
                                      style: const TextStyle(
                                        fontSize: 18,
                                        fontWeight: FontWeight.w500,
                                        fontFamily: 'Rubik',
                                      ),
                                    ),
                                  if (response.date != null)
                                    Text(
                                      "Date: ${response.date!.toLocal().toIso8601String()}",
                                      style: const TextStyle(fontSize: 16),
                                    ),
                                  if (response.utr != null &&
                                      response.utr!.isNotEmpty)
                                    Padding(
                                      padding: const EdgeInsets.only(top: 8.0),
                                      child: Text(
                                        'UTR: ${response.utr}',
                                        style: const TextStyle(fontSize: 16),
                                      ),
                                    ),
                                ],
                              )
                            : Column(
                                children: [
                                  Text(
                                    AppLocalizations.of(context).paymentFailed,
                                    style: const TextStyle(
                                      fontSize: 22,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.red,
                                    ),
                                  ),
                                  const SizedBox(height: 16),
                                  if (response.errorMessage != null)
                                    Text(
                                      response.errorMessage ?? '',
                                      style: const TextStyle(fontSize: 16),
                                    ),
                                ],
                              ),
                        const SizedBox(height: 40),
                      ],
                    ),
                  ),
                ),
              ),
              Positioned(
                left: 0,
                right: 0,
                bottom: 80,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton.icon(
                      onPressed: _shareScreenshot,
                      icon: Icon(
                        Icons.share_rounded,
                        color: Theme.of(context).colorScheme.primary,
                      ),
                      label: Text(
                        AppLocalizations.of(context).share,
                        style: TextStyle(
                            color: Theme.of(context).colorScheme.primary),
                      ),
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 45, vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        textStyle: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                    ElevatedButton.icon(
                      onPressed: () {
                        Navigator.of(context)
                            .popUntil((route) => route.isFirst);
                      },
                      icon: const Icon(Icons.check),
                      label: Text(AppLocalizations.of(context).done),
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 45, vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        textStyle: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
