import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';

import '../blocs/raise_ticket/raise_ticket_bloc.dart';
import '../blocs/support_details/support_details_bloc.dart';

class SupportFormPage extends StatefulWidget {
  const SupportFormPage({super.key});

  @override
  State<SupportFormPage> createState() => _SupportFormPageState();
}

class _SupportFormPageState extends State<SupportFormPage> {
  final TextEditingController _subjectController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();
  final ImagePicker _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    // Trigger the fetch event for support details once when the page is initialized
    context.read<SupportDetailsBloc>().add(FetchSupportDetailsEvent());
    
    // Listen to existing state if we are coming back or resuming (optional)
    final state = context.read<RaiseTicketBloc>().state;
    _subjectController.text = state.subject;
    _descriptionController.text = state.description;
  }

  @override
  void dispose() {
    _subjectController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<RaiseTicketBloc, RaiseTicketState>(
      listener: (context, state) {
        if (state.status == RaiseTicketStatus.success) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text("Ticket submitted successfully!")),
          );
          _subjectController.clear();
          _descriptionController.clear();
          context.read<RaiseTicketBloc>().add(const RaiseTicketReset());
          Navigator.pop(context);
        } else if (state.status == RaiseTicketStatus.failure &&
            state.errorMessage != null) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text("Error: ${state.errorMessage}")),
          );
        } else if (state.fileSizeExceeded && state.errorMessage != null) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text("Error: ${state.errorMessage}")),
          );
          // Auto-remove the invalid attachment
          // context.read<RaiseTicketBloc>().add(const RaiseTicketAttachmentRemoved());
        }
      },
      builder: (context, state) {
        final raiseTicketBloc = context.read<RaiseTicketBloc>();

        return Scaffold(
          backgroundColor: Colors.white,
          bottomNavigationBar: Visibility(
            visible: MediaQuery.of(context).viewInsets.bottom == 0.0,
            child: Padding(
              padding: EdgeInsets.all(16.w),
              child: SizedBox(
                width: double.infinity,
                height: 52.h,
                child: ElevatedButton(
                  onPressed: state.status == RaiseTicketStatus.loading ||
                          state.fileSizeExceeded ||
                          state.subject.isEmpty ||
                          state.description.isEmpty
                      ? null
                      : () => raiseTicketBloc.add(const RaiseTicketSubmitted()),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xffF95F62),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.r)),
                  ),
                  child: state.status == RaiseTicketStatus.loading
                      ? SizedBox(
                          width: 20.w,
                          height: 20.h,
                          child: const CircularProgressIndicator(
                              color: Colors.white, strokeWidth: 2),
                        )
                      : Text(
                          "Submit Ticket",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 20.sp,
                              fontWeight: FontWeight.w600),
                        ),
                ),
              ),
            ),
          ),
          appBar: AppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            leading: Padding(
              padding: EdgeInsets.symmetric(horizontal: 8.w),
              child: InkWell(
                onTap: () {
                  Navigator.pop(context);
                },
                child: Container(
                  width: 44.w,
                  height: 44.h,
                  decoration: const BoxDecoration(
                    color: Color(0xFFF95F62),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(Icons.arrow_back, color: Colors.white, size: 24.sp),
                ),
              ),
            ),
            forceMaterialTransparency: true,
            centerTitle: true,
            title: Text("Support",
                style: TextStyle(
                    fontWeight: FontWeight.w700,
                    color: Colors.black,
                    fontSize: 32.sp)),
          ),
          body: SingleChildScrollView(
            padding: EdgeInsets.all(20.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Align(
                  alignment: Alignment.center,
                  child: Text(
                    "Need help? We’re here for you. Raise a ticket and our support team will get back to you shortly",
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.black, fontSize: 13.sp),
                  ),
                ),
                SizedBox(height: 20.h),
                Text("Subject",
                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 14.sp)),
                SizedBox(height: 6.h),
                TextField(
                  controller: _subjectController,
                  onChanged: (v) => raiseTicketBloc.add(RaiseTicketSubjectChanged(v)),
                  decoration: InputDecoration(
                    fillColor: Colors.black.withOpacity(0.04),
                    hintText: "Enter Subject",
                    filled: true,
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                          color: Colors.black.withOpacity(0.24), width: 1.0.w),
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                          color: Colors.black.withOpacity(0.24), width: 1.0.w),
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                          color: Colors.black.withOpacity(0.24), width: 1.0.w),
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                  ),
                ),
                SizedBox(height: 20.h),
                Text("Description",
                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 14.sp)),
                SizedBox(height: 6.h),
                TextField(
                  controller: _descriptionController,
                  onChanged: (v) => raiseTicketBloc.add(RaiseTicketDescriptionChanged(v)),
                  maxLines: 4,
                  decoration: InputDecoration(
                    fillColor: Colors.black.withOpacity(0.04),
                    hintText: "Enter Description",
                    filled: true,
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                          color: Colors.black.withOpacity(0.24), width: 1.0.w),
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                          color: Colors.black.withOpacity(0.24), width: 1.0.w),
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                          color: Colors.black.withOpacity(0.24), width: 1.0.w),
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                  ),
                ),
                SizedBox(height: 20.h),
                Text("File upload",
                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 14.sp)),
                SizedBox(height: 6.h),
                GestureDetector(
                  onTap: () async {
                    // pickMedia allows both images and videos
                    final XFile? pickedFile = await _picker.pickMedia();
                    if (pickedFile != null) {
                      raiseTicketBloc.add(RaiseTicketAttachmentPicked(File(pickedFile.path)));
                    }
                  },
                  child: Container(
                    height: 45.h,
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.04),
                      border: Border.all(color: Colors.grey),
                      borderRadius: BorderRadius.circular(6.r),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Padding(
                            padding: EdgeInsets.symmetric(horizontal: 12.w),
                            child: Text(
                              state.attachment != null
                                  ? state.attachment!.path.split('/').last
                                  : (state.fileSizeExceeded ? "File too large (>5MB).Pick another" : "Upload File"),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: state.attachment != null
                                    ? Colors.black
                                    : (state.fileSizeExceeded ? Colors.red : Colors.black54),
                                fontSize: 13.sp,
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 8.w),
                          child: Image.asset(
                            "assets/support/icon/upload.png",
                            scale: 4,
                            width: 24.w,
                            height: 24.h,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                if (state.attachment != null)
                  Align(
                    alignment: Alignment.centerRight,
                    child: TextButton(
                      onPressed: () => raiseTicketBloc.add(const RaiseTicketAttachmentRemoved()),
                      child: Text(
                        "Remove File",
                        style: TextStyle(color: Colors.red, fontSize: 12.sp),
                      ),
                    ),
                  ),
                SizedBox(height: 30.h),
                Text("Contact Details",
                    style: TextStyle(fontWeight: FontWeight.w600, fontSize: 24.sp)),
                SizedBox(height: 12.h),
                const Divider(),
                BlocBuilder<SupportDetailsBloc, SupportDetailsState>(
                  builder: (context, supportState) {
                    String email = "Loading...";
                    String phone = "Loading...";

                    if (supportState is SupportDetailsLoaded) {
                      email = supportState.supportDetail.partner.emailAddress;
                      phone = supportState.supportDetail.partner.phoneNumber;
                    } else if (supportState is SupportDetailsError) {
                      email = "Error loading";
                      phone = "Error loading";
                    }

                    return Column(
                      children: [
                        Row(
                          children: [
                            Expanded(
                              flex: 1,
                              child: Row(
                                children: [
                                  Icon(Icons.email_outlined, color: Colors.black87, size: 20.sp),
                                  SizedBox(width: 12.w),
                                  Text("Email", style: TextStyle(fontSize: 13.sp)),
                                ],
                              ),
                            ),
                            Expanded(
                              flex: 2,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  SizedBox(width: 12.w),
                                  Text(email,
                                      style: TextStyle(
                                          fontSize: 13.sp, color: Colors.black)),
                                ],
                              ),
                            ),
                          ],
                        ),
                        const Divider(),
                        SizedBox(height: 12.h),
                        Row(
                          children: [
                            Expanded(
                              flex: 1,
                              child: Row(
                                children: [
                                  Icon(Icons.phone_outlined, color: Colors.black87, size: 20.sp),
                                  SizedBox(width: 12.w),
                                  Text("Phone", style: TextStyle(fontSize: 13.sp)),
                                ],
                              ),
                            ),
                            Expanded(
                              flex: 2,
                              child: Row(
                                children: [
                                  SizedBox(width: 12.w),
                                  Text(phone, style: TextStyle(fontSize: 13.sp)),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ],
                    );
                  },
                ),
                const Divider(),
                SizedBox(height: 80.h),
              ],
            ),
          ),
        );
      },
    );
  }
}
