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';

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();

  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;

          return Stack(
            children: [
              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: 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),
                                    ),
                                ],
                              )
                            : Column(
                                children: [
                                  Text(
                                    AppLocalizations.of(context).paymentFailed,
                                    style: 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),
                      ],
                    ),
                  ),
                ),
              ),
              // Buttons at the bottom
              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).primaryColor,
                      ),
                      label: Text(
                        AppLocalizations.of(context).share,
                        style: TextStyle(color: Theme.of(context).primaryColor),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Theme.of(
                          context,
                        ).scaffoldBackgroundColor,
                        padding: const EdgeInsets.symmetric(
                          horizontal: 32,
                          vertical: 12,
                        ),
                        shape: RoundedRectangleBorder(
                          side: BorderSide(
                            color: Theme.of(context).primaryColor,
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(30),
                        ),
                        textStyle: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    ElevatedButton.icon(
                      onPressed: () {
                        Navigator.of(
                          context,
                        ).popUntil((route) => route.isFirst);
                      },
                      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,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
