// ignore_for_file: deprecated_member_use, use_build_context_synchronously, prefer_final_fields

import 'dart:convert';
import 'dart:io';

import 'package:academy_lms_app/constants.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:share_plus/share_plus.dart';
import 'package:file_picker/file_picker.dart';

import '../providers/customer_support_provider.dart';

class TicketDetailsScreen extends StatefulWidget {
  final String ticketCode;

  const TicketDetailsScreen({super.key, required this.ticketCode});

  @override
  State<TicketDetailsScreen> createState() => _TicketDetailsScreenState();
}

class _TicketDetailsScreenState extends State<TicketDetailsScreen> {
  ScrollController _scrollController = ScrollController();
  Map<String, dynamic>? ticketData;
  bool isLoading = true;
  bool _isSending = false;
  bool isReloading = false;
  List<XFile> selectedFiles = [];

  String? loggedInUserId;

  @override
  void initState() {
    super.initState();
    loadDetails();
  }

  Future<void> loadDetails() async {
    final provider = Provider.of<CustomerSupportProvider>(
      context,
      listen: false,
    );

    final data = await provider.fetchTicketDetails(widget.ticketCode);

    setState(() {
      ticketData = data;
      isLoading = false;
    });

    final prefs = await SharedPreferences.getInstance();
    final userString = prefs.getString('user');

    if (userString != null) {
      final userMap = jsonDecode(userString);

      setState(() {
        loggedInUserId = userMap['id'].toString();
      });
    }
    setState(() {
      ticketData = data;
      isLoading = false;
    });
  }

  final _messageController = TextEditingController();

  Future<void> pickFiles() async {
    final result = await FilePicker.platform.pickFiles(
      allowMultiple: true,
      type: FileType.any,
    );

    if (result != null && result.files.isNotEmpty) {
      setState(() {
        selectedFiles.addAll(result.files.map((f) => XFile(f.path!)));
      });
    }
  }

  Future<void> sendMessage() async {
    if (_isSending) return;

    final message = _messageController.text.trim();
    if (message.isEmpty && selectedFiles.isEmpty) return;

    setState(() {
      _isSending = true;
    });

    final provider = Provider.of<CustomerSupportProvider>(
      context,
      listen: false,
    );

    try {
      await provider.sendMessage(
        ticketCode: widget.ticketCode,
        message: message,
        files: selectedFiles,
      );

      _messageController.clear();
      selectedFiles.clear();

      await loadDetails();
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          0,
          duration: const Duration(milliseconds: 200),
          curve: Curves.easeOut,
        );
      }
    } catch (e) {
      debugPrint("Send failed: $e");
    }

    if (mounted) {
      setState(() {
        _isSending = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    final conversation = ticketData!['conversation'];

    return Scaffold(
      appBar: AppBar(
        title: Text(ticketData!['ticket_details']['subject']),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            tooltip: 'Reload',
            onPressed: () async {
              setState(() {
                isReloading = true;
              });

              try {
                await loadDetails();
              } finally {
                if (mounted) {
                  setState(() {
                    isReloading = false;
                  });
                }
              }
            },
          ),
        ],
      ),
      backgroundColor: kRemoveIconColor,

      body: Stack(
        children: [
          Column(
            children: [
              /// Messages
              Expanded(
                child: ListView.builder(
                  controller: _scrollController,
                  reverse: true,
                  itemCount: conversation.length,
                  itemBuilder: (context, index) {
                    final msg = conversation[conversation.length - 1 - index];
                    final isMe = msg['sender_id'].toString() == loggedInUserId;
                    final files = msg['file'] ?? [];

                    return Column(
                      crossAxisAlignment: isMe
                          ? CrossAxisAlignment.end
                          : CrossAxisAlignment.start,

                      children: [
                        /// TEXT BUBBLE
                        if (msg['message'] != null &&
                            msg['message'].toString().isNotEmpty)
                          Align(
                            alignment: isMe
                                ? Alignment.centerRight
                                : Alignment.centerLeft,
                            child: Container(
                              margin: const EdgeInsets.symmetric(
                                horizontal: 8,
                                vertical: 4,
                              ),
                              constraints: BoxConstraints(
                                maxWidth:
                                    MediaQuery.of(context).size.width * 0.80,
                              ),
                              padding: const EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                color: isMe ? Colors.blue : Colors.white,
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(14),
                                  topRight: Radius.circular(14),
                                  bottomLeft: isMe
                                      ? Radius.circular(14)
                                      : Radius.circular(0),
                                  bottomRight: isMe
                                      ? Radius.circular(0)
                                      : Radius.circular(14),
                                ),
                              ),
                              child: SelectableText(
                                msg['message'],
                                style: TextStyle(
                                  color: isMe ? Colors.white : Colors.black,
                                ),
                                toolbarOptions: ToolbarOptions(
                                  copy: true,
                                  cut: true,
                                  selectAll: true,
                                ),
                              ),
                            ),
                          ),

                        /// IMAGE BUBBLE (NO BACKGROUND COLOR)
                        if (files.isNotEmpty)
                          ...files.map<Widget>(
                            (fileUrl) => Align(
                              alignment: isMe
                                  ? Alignment.centerRight
                                  : Alignment.centerLeft,
                              child: Padding(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 8,
                                  vertical: 4,
                                ),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(10),
                                  child: GestureDetector(
                                    onLongPress: () async {
                                      showModalBottomSheet(
                                        context: context,
                                        builder: (context) => SafeArea(
                                          child: Column(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              ListTile(
                                                leading: const Icon(
                                                  Icons.share,
                                                ),
                                                title: const Text('Share'),
                                                onTap: () async {
                                                  Navigator.pop(
                                                    context,
                                                  ); // close bottom sheet
                                                  try {
                                                    await Share.share(fileUrl);
                                                  } catch (e) {
                                                    if (!mounted) return;
                                                    ScaffoldMessenger.of(
                                                      context,
                                                    ).showSnackBar(
                                                      SnackBar(
                                                        content: Text(
                                                          'Share failed: $e',
                                                        ),
                                                      ),
                                                    );
                                                  }
                                                },
                                              ),
                                            ],
                                          ),
                                        ),
                                      );
                                    },
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.circular(10),
                                      child: Image.network(
                                        fileUrl,
                                        width:
                                            MediaQuery.of(context).size.width *
                                            0.5,
                                        height: 200,
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                      ],
                    );
                  },
                ),
              ),

              /// Message input area
              Container(
                color: kWhiteColor,
                padding: const EdgeInsets.only(
                  left: 8,
                  right: 8,
                  bottom: 16,
                  top: 12,
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    /// Preview selected files
                    if (selectedFiles.isNotEmpty)
                      SizedBox(
                        height: 80,
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: selectedFiles.length,
                          itemBuilder: (context, index) {
                            final file = selectedFiles[index];
                            return Stack(
                              children: [
                                Container(
                                  margin: const EdgeInsets.symmetric(
                                    horizontal: 4,
                                  ),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(8),
                                    child:
                                        file.path.endsWith('.png') ||
                                            file.path.endsWith('.jpg') ||
                                            file.path.endsWith('.jpeg') ||
                                            file.path.endsWith('.gif')
                                        ? Image.file(
                                            File(file.path),
                                            width: 70,
                                            height: 70,
                                            fit: BoxFit.cover,
                                          )
                                        : Container(
                                            width: 70,
                                            height: 70,
                                            color: Colors.grey.shade300,
                                            child: const Icon(
                                              Icons.insert_drive_file,
                                            ),
                                          ),
                                  ),
                                ),
                                Positioned(
                                  right: 0,
                                  top: 0,
                                  child: GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        selectedFiles.removeAt(index);
                                      });
                                    },
                                    child: const CircleAvatar(
                                      radius: 10,
                                      backgroundColor: Colors.red,
                                      child: Icon(
                                        Icons.close,
                                        size: 12,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            );
                          },
                        ),
                      ),

                    /// Input Row
                    Row(
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            color: kRemoveIconColor,
                            shape: BoxShape.circle,
                          ),
                          child: IconButton(
                            icon: const Icon(Icons.add),
                            color: kDarkGreyColor,
                            onPressed: pickFiles,
                            padding: const EdgeInsets.all(8),
                            iconSize: 24,
                          ),
                        ),
                        const SizedBox(width: 6),
                        Expanded(
                          child: TextField(
                            controller: _messageController,
                            keyboardType: TextInputType.multiline,
                            minLines: 1,
                            maxLines: 2,
                            decoration: InputDecoration(
                              hintText: "Type a message...",
                              hintStyle: TextStyle(color: kDarkGreyColor),
                              filled: true,
                              fillColor: kRemoveIconColor,
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.all(
                                  Radius.circular(25),
                                ),
                                borderSide: BorderSide(
                                  color: Colors.transparent,
                                ), // border color
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(25),
                                borderSide: BorderSide(
                                  color: Colors.transparent,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(25),
                                borderSide: BorderSide(
                                  color: Colors.transparent,
                                ),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 12,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 6),
                        Container(
                          decoration: BoxDecoration(
                            color: kRemoveIconColor,
                            shape: BoxShape.circle,
                          ),
                          child: IconButton(
                            icon: const Icon(Icons.send),
                            color: kDarkGreyColor,
                            onPressed: sendMessage,

                            padding: const EdgeInsets.all(8),
                            iconSize: 24,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),

          /// FULLSCREEN LOADER ONLY FOR RELOAD
          if (isReloading)
            SizedBox(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: const Center(
                child: CupertinoActivityIndicator(color: kDefaultColor),
              ),
            ),
        ],
      ),
    );
  }
}
