// ignore_for_file: deprecated_member_use, use_build_context_synchronously, unused_local_variable

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

import '../constants.dart';
import '../providers/customer_support_provider.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../widgets/common_functions.dart';

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

  @override
  State<CreateSupportTicketScreen> createState() =>
      _CreateSupportTicketScreenState();
}

class _CreateSupportTicketScreenState extends State<CreateSupportTicketScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  final TextEditingController _subjectController = TextEditingController();
  final TextEditingController _messageController = TextEditingController();

  int? _selectedCategoryId;
  int? _selectedStatusId;
  int? _selectedPriorityId;

  List<PlatformFile> _pickedFiles = [];

  bool _isSubmitting = false;

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

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

    provider.fetchTicketCategories();
    provider.fetchTicketStatuses();
    provider.fetchTicketPriorities();
  }

  InputDecoration getInputDecoration(String hintText) {
    return InputDecoration(
      enabledBorder: OutlineInputBorder(
        borderRadius: const BorderRadius.all(Radius.circular(16.0)),
        borderSide: BorderSide(color: kDefaultColor.withOpacity(0.1), width: 1),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: const BorderRadius.all(Radius.circular(16.0)),
        borderSide: BorderSide(color: kDefaultColor.withOpacity(0.1), width: 1),
      ),
      border: OutlineInputBorder(
        borderRadius: const BorderRadius.all(Radius.circular(16.0)),
        borderSide: BorderSide(color: kDefaultColor.withOpacity(0.1), width: 1),
      ),
      filled: true,
      hintText: hintText,
      hintStyle: const TextStyle(color: Colors.black54, fontSize: 16),
      fillColor: kInputBoxBackGroundColor,

      contentPadding: const EdgeInsets.symmetric(vertical: 15, horizontal: 15),
    );
  }

  void _submitForm() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isSubmitting = true);

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

      final url = Uri.parse('$baseUrl/api/support_ticket_store');

      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString('access_token') ?? '';

      var request = http.MultipartRequest('POST', url);

      request.headers['Authorization'] = 'Bearer $token';
      request.headers['Accept'] = 'application/json';

      // Text fields
      request.fields['subject'] = _subjectController.text;
      request.fields['category_id'] = _selectedCategoryId.toString();
      request.fields['status_id'] = _selectedStatusId.toString();
      request.fields['priority_id'] = _selectedPriorityId.toString();
      request.fields['message'] = _messageController.text;

      // Files
      for (var file in _pickedFiles) {
        if (file.path != null) {
          request.files.add(
            await http.MultipartFile.fromPath(
              'file[]', // backend expects array
              file.path!,
            ),
          );
        }
      }

      var response = await request.send();
      var responseData = json.decode(await response.stream.bytesToString());

      if (responseData['code'] == 200) {
        CommonFunctions.showSuccessToast('Ticket Created Successfully');
        Navigator.pop(context, true);
      } else {
        throw Exception(responseData['message']);
      }
    } catch (e) {
      CommonFunctions.showErrorDialog(e.toString(), context);
    }

    setState(() => _isSubmitting = false);
  }

  void _pickFiles() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        allowMultiple: true,
      );

      if (result != null) {
        setState(() {
          _pickedFiles = result.files;
        });
      }
    } catch (e) {
      CommonFunctions.showErrorDialog('Failed to pick files: $e', context);
    }
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<CustomerSupportProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Create Support Ticket',
          style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
        ),
      ),

      backgroundColor: kBackGroundColor,
      body: provider.isLoading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    const SizedBox(height: 15),

                    /// Subject
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 10,
                      ),
                      child: TextFormField(
                        controller: _subjectController,
                        validator: (val) => val == null || val.isEmpty
                            ? 'Subject required'
                            : null,
                        decoration: getInputDecoration('Subject'),
                      ),
                    ),

                    /// Category
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 10,
                      ),
                      child: DropdownButtonFormField<int>(
                        value: _selectedCategoryId,
                        elevation: 1,
                        decoration: getInputDecoration('Category'),
                        items: provider.categories
                            .map(
                              (cat) => DropdownMenuItem<int>(
                                value: cat.id,
                                child: Text(cat.title ?? ''),
                              ),
                            )
                            .toList(),
                        onChanged: (val) =>
                            setState(() => _selectedCategoryId = val),
                        validator: (val) =>
                            val == null ? 'Please select a category' : null,
                      ),
                    ),

                    /// Status
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 10,
                      ),
                      child: DropdownButtonFormField<int>(
                        value: _selectedStatusId,
                        elevation: 1,
                        decoration: getInputDecoration('Status'),
                        items: provider.statuses
                            .map(
                              (sta) => DropdownMenuItem<int>(
                                value: sta.id,
                                child: Text(sta.title ?? ''),
                              ),
                            )
                            .toList(),
                        onChanged: (val) =>
                            setState(() => _selectedStatusId = val),
                        validator: (val) =>
                            val == null ? 'Please select status' : null,
                      ),
                    ),

                    /// Priority
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 10,
                      ),
                      child: DropdownButtonFormField<int>(
                        value: _selectedPriorityId,
                        elevation: 1,
                        decoration: getInputDecoration('Priority'),
                        items: provider.priorities
                            .map(
                              (pri) => DropdownMenuItem<int>(
                                value: pri.id,
                                child: Text(pri.title ?? ''),
                              ),
                            )
                            .toList(),
                        onChanged: (val) =>
                            setState(() => _selectedPriorityId = val),
                        validator: (val) =>
                            val == null ? 'Please select priority' : null,
                      ),
                    ),

                    /// Message
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 10,
                      ),
                      child: TextFormField(
                        controller: _messageController,
                        maxLines: 6,
                        validator: (val) => val == null || val.isEmpty
                            ? 'Message required'
                            : null,
                        decoration: getInputDecoration('Message'),
                      ),
                    ),

                    /// Attachments
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 5,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            'Attachments',
                            style: TextStyle(
                              fontWeight: FontWeight.w500,
                              fontSize: 16,
                            ),
                          ),
                          const SizedBox(height: 8),
                          Wrap(
                            spacing: 8,
                            children: _pickedFiles.map((f) {
                              return Chip(
                                label: Text(f.name),
                                onDeleted: () {
                                  setState(() {
                                    _pickedFiles.remove(f);
                                  });
                                },
                              );
                            }).toList(),
                          ),
                          const SizedBox(height: 8),
                          SizedBox(
                            width: double.infinity,
                            child: MaterialButton(
                              elevation: 0,
                              color: kDefaultColor,
                              onPressed: _pickFiles,
                              padding: const EdgeInsets.symmetric(vertical: 16),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(16),
                              ),
                              child: const Text(
                                'Upload Files',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    const SizedBox(height: 25),

                    /// Submit Button
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 20),
                      child: SizedBox(
                        width: double.infinity,
                        child: _isSubmitting
                            ? const Center(child: CircularProgressIndicator())
                            : MaterialButton(
                                elevation: 0,
                                color: kDefaultColor,
                                onPressed: _submitForm,
                                padding: const EdgeInsets.symmetric(
                                  vertical: 16,
                                ),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: const Text(
                                  'Create Ticket',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.w500,
                                    fontSize: 16,
                                  ),
                                ),
                              ),
                      ),
                    ),

                    const SizedBox(height: 25),
                  ],
                ),
              ),
            ),
    );
  }
}
