import 'dart:convert';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:nhance_partner/presentation/themes/indicators/mutli_FileUpload.dart';

import '../../../../core/config/env.dart';
import '../../../../core/services/api_service.dart';
import '../../../../data/services/auth_service.dart';
import '../../../../data/utils/toastNotification.dart';
import '../../../themes/indicators/multi_fileUploadService.dart';

class MultipleFileWidget extends ConsumerStatefulWidget {
  dynamic enqId;
  MultipleFileWidget({super.key, required this.enqId});

  @override
  ConsumerState<MultipleFileWidget> createState() => MultipleFileWidgetState();
}

class MultipleFileWidgetState extends ConsumerState<MultipleFileWidget> {
  List<PlatformFile> uploadedFiles = [];
  final fileService = MultiFileUploadService();
  late ApiService apiService;
  bool isLoading = false;
  dynamic _token;

  List<Map<String, dynamic>> getUploadedData = [];
  List<Map<String, dynamic>> originalData = [];
  List<Map<String, dynamic>> filteredData = [];

  @override
  void initState() {
    super.initState();
    fileService.clearAll();
    apiService = ApiService();
    _initializeToken();
    getList();
  }

  Future<void> _initializeToken() async {
    _token = await AuthService.getToken();
    print("APISERTOKEN - $_token");
  }

  Future<void> getList() async {
    setState(() {
      isLoading = true;
    });

    try {
      final response = await apiService.fetchUploadEnquiryFiles(widget.enqId);

      if (response['status'] == 'success') {
        print('E113 => getfetchUploadEnquiryFiles=');
        print('E113 => getfetchUploadEnquiryFiles=> ${response['data']}');
        setState(() {
          getUploadedData = List<Map<String, dynamic>>.from(response['data']);
          originalData = getUploadedData;
          filteredData = List.from(originalData);
          print('originalData - $originalData');
        });
      } else {
        getUploadedData = [];
        originalData = [];
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> handleSave() async {
    final request = http.MultipartRequest(
      'POST',
      Uri.parse('${Env.apiUrl}enquiry/uploadEnquiryFiles'),
    );

    if (_token == null) {
      throw Exception('Token not found. Please log in.');
    }
    request.headers['Authorization'] = 'Bearer $_token';
    request.headers['app-signature'] = Env.App_Signature;
    if (MultiFileUploadService().files.isEmpty) {
      setState(() {
        MultiFileUploadWidget.hasFiles = false;
      });
      ToastHelper.showErrorToast(
        context,
        'Please upload at least one document',
      );
      return;
    }

    // final id = int.tryParse(enqId.toString()) ?? 0;

    // get uploaded files
    final uploadedFiles = MultiFileUploadService().files;
    print("📁 Total uploaded files: ${uploadedFiles.length}");
    print(
      "📂 File list (original names): ${uploadedFiles.map((f) => f.file.name).toList()}",
    );

    // Validate all labels present (optional but recommended)
    for (final uf in uploadedFiles) {
      print(
        "📝 Checking label for file: ${uf.file.name}, current label: '${uf.label}'",
      );
      if ((uf.label ?? '').trim().isEmpty) {
        ToastHelper.showErrorToast(
          context,
          'Please enter name for all uploaded documents',
        );
        setState(() => isLoading = false);
        return;
      }
    }

    // Add files
    for (var uf in uploadedFiles) {
      final pf = uf.file;
      if (pf.bytes != null) {
        request.files.add(
          http.MultipartFile.fromBytes('files[]', pf.bytes!, filename: pf.name),
        );
      }
    }

    // ✅ Combine all names into a JSON array string
    final claimDocNames = uploadedFiles.map((uf) => uf.label.trim()).toList();
    final encodedNames = jsonEncode(claimDocNames);
    request.fields['files_doc_names'] = encodedNames;
    request.fields['enquiry_id'] = widget.enqId!;
    // ✅ Debug print
    print("Payload being sent:");
    print("Files: ${uploadedFiles.map((f) => f.file.name).toList()}");
    print("Names (JSON): $encodedNames");

    final response = await request.send();
    final responseBody = await response.stream.bytesToString();
    final decoded = jsonDecode(responseBody);
    if (decoded['status'] == 'success') {
      ToastHelper.showSuccessToast(context, 'File Uploaded');
      setState(() {
        isLoading = false;
      });
      print('Form data submitted successfully');
      fileService.clearAll();
      getList();
    } else {
      ToastHelper.showErrorToast(context, "Failed: ${decoded['message']}");
    }
  }

  Future<void> handleDelete(id) async {
    setState(() {
      isLoading = true;
    });

    final path = 'enquiry/deleteEnquiryFile?file_id=$id';
    print('path - $path');
    try {
      final response = await apiService.delete(id, path);

      print("response");
      print("response - $response");
      print("response - ${response['status']}");

      if (response['status'] == 'success') {
        ToastHelper.showSuccessToast(context, response['message']);
        getList();
      } else {
        ToastHelper.showSuccessToast(context, response['message']);
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return SelectionArea(
        child: Container(
      color: Color(0xFFFFFFFF),

      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('File Upload', style: GoogleFonts.poppins(fontSize: 11)),
          SizedBox(height: 3),
          MultiFileUploadWidget(),

          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              GestureDetector(
                onTap: () {
                  handleSave();
                },
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 6.0, vertical: 2),

                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.0),
                    color: Color(0xFF2E7D6E),
                    // color: Color(0xFF425B5B),
                  ),
                  child: Text(
                    'Save',
                    style: GoogleFonts.poppins(
                      color: Colors.white,
                      fontSize: 11,
                    ),
                  ),
                ),
              ),
            ],
          ),

          SizedBox(height: 5),
          Column(
            children: List.generate(originalData.length, (index) {
              final item = originalData[index];
              final fileName = item['file_name'] ?? '';
              final fileId = item['id'] ?? '';

              return Container(
                // margin: const EdgeInsets.only(bottom: 6),
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(2),
                  border: Border(
                    bottom: BorderSide(
                      width: 0.2,
                      color: Colors.blueGrey.shade100,
                    ),
                  ),
                ),
                child: Row(
                  children: [
                    Icon(
                      Icons.file_present_outlined,
                      size: 16,
                      color: Colors.grey[700],
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        fileName,
                        style: GoogleFonts.poppins(fontSize: 11),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),

                    GestureDetector(
                      onTap: () {
                        final path =
                            'enquiry/downloadEnquiryFiles?file_id=$fileId';
                        print("Uploadpath $path");
                        apiService.getPdfDownload(path, fileId);
                      },
                      child: Icon(Icons.download, size: 16, color: Colors.blue),
                    ),

                    // DELETE BUTTON (optional)
                    GestureDetector(
                      onTap: () {
                        handleDelete(fileId);
                      },
                      child: Icon(Icons.delete, size: 16, color: Colors.red),
                    ),
                  ],
                ),
              );
            }),
          ),
        ],
      ),
    ),);
  }
}
