// SubmitTimesheetFragment.kt
package com.b2lmobitech.fieldcloudhrms

import android.app.Activity
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.b2lmobitech.fieldcloudhrms.databinding.FragmentSubmitTimesheetBinding
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.io.FileOutputStream
import java.util.Calendar

class SubmitTimesheetFragment : AppCompatActivity() {

    private lateinit var binding: FragmentSubmitTimesheetBinding
    private val selectedFileUris = mutableListOf<Uri>()
    private val tempFiles = mutableListOf<File>()

    companion object {
        const val PICK_FILE = 101
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentSubmitTimesheetBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setupTimePickers()
        setupClicks()
    }

    private fun setupTimePickers() {
        binding.edtStartTime.setOnClickListener { showTimePicker(binding.edtStartTime) }
        binding.edtEndTime.setOnClickListener { showTimePicker(binding.edtEndTime) }
    }

    private fun showTimePicker(target: android.widget.EditText) {
        val cal = Calendar.getInstance()
        val hour = cal.get(Calendar.HOUR_OF_DAY)
        val min = cal.get(Calendar.MINUTE)

        TimePickerDialog(this, { _, h, m ->
            target.setText(String.format("%02d:%02d", h, m))
        }, hour, min, true).show()
    }

    private val filePickerLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {

                val data = result.data

                when {
                    data?.clipData != null -> {
                        val clip = data.clipData!!
                        for (i in 0 until clip.itemCount) {
                            val uri = clip.getItemAt(i).uri
                            selectedFileUris.add(uri)
                            createTempFileFromUri(uri)?.let { tempFiles.add(it) }
                        }
                    }
                    data?.data != null -> {
                        val uri = data.data!!
                        selectedFileUris.add(uri)
                        createTempFileFromUri(uri)?.let { tempFiles.add(it) }
                    }
                }

                if (tempFiles.isNotEmpty()) {
                    val names = tempFiles.joinToString("\n") { it.name }
                    binding.txtAttachmentName.text = names
                    binding.txtAttachmentName.visibility = android.view.View.VISIBLE
                }
            }
        }

    private fun setupClicks() {

        binding.addAttachmentLayout.setOnClickListener {
            pickFile()
        }

        binding.btnCancel.setOnClickListener {
            cleanupTemp()
            finish()
        }

        binding.btnBack.setOnClickListener {
            cleanupTemp()
            finish()
        }

        binding.btnSubmit.setOnClickListener {
            submitTimesheet()
        }
    }

    private fun pickFile() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "*/*"
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        filePickerLauncher.launch(intent)
    }

    private fun createTempFileFromUri(uri: Uri): File? {
        return try {
            val input = contentResolver.openInputStream(uri) ?: return null
            val name = queryFileName(uri) ?: "file_${System.currentTimeMillis()}.bin"
            val temp = File(cacheDir, name)
            val output = FileOutputStream(temp)
            input.copyTo(output)
            input.close()
            output.close()
            temp
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    private fun queryFileName(uri: Uri): String? {
        var name: String? = null
        val cursor = contentResolver.query(uri, null, null, null, null)
        cursor?.use {
            if (it.moveToFirst()) {
                val idx = it.getColumnIndex("_display_name")
                if (idx >= 0) name = it.getString(idx)
            }
        }
        if (name == null) {
            // fallback from uri path
            name = uri.path?.let {
                val last = it.lastIndexOf('/')
                if (last >= 0) it.substring(last + 1) else it
            }
        }
        return name
    }

//    private fun submitTimesheet() {
//
//        val activityName = binding.edtActivity.text.toString().trim()
//        val start = binding.edtStartTime.text.toString().trim()
//        val end = binding.edtEndTime.text.toString().trim()
//        val desc = binding.edtDescription.text.toString().trim()
//
//        if (activityName.isEmpty() || start.isEmpty() || end.isEmpty()) {
//            Toast.makeText(this, "Please fill required fields", Toast.LENGTH_SHORT).show()
//            return
//        }
//
//        val api = RetrofitClient.instance
//
//        // If no files => submit directly with empty attachments array
//        if (tempFiles.isEmpty()) {
//            submitData(activityName, start, end, desc, emptyList())
//            return
//        }
//
//        // Build multipart list
//        val multipartList = mutableListOf<MultipartBody.Part>()
//        for (file in tempFiles) {
//            val reqFile = file.asRequestBody("*/*".toMediaTypeOrNull())
//            val part = MultipartBody.Part.createFormData("attachments[]", file.name, reqFile)
//            multipartList.add(part)
//        }
//        Log.d("multipartList","$multipartList")
//
//        val sharedPref = getSharedPreferences("login_pref", Context.MODE_PRIVATE)
//        val userId = sharedPref.getString("user_id", "") ?: ""
//        val orgId = sharedPref.getString("org_id", "") ?: ""
//
//        // Show some basic progress UI
//        binding.btnSubmit.isEnabled = false
//        binding.btnSubmit.text = "Uploading..."
//
//        api.uploadMultipleAttachments(orgId, multipartList)
//            .enqueue(object : Callback<FileResponse> {
//                override fun onResponse(call: Call<FileResponse>, response: Response<FileResponse>) {
//                    binding.btnSubmit.isEnabled = true
//                    binding.btnSubmit.text = "Submit"
//
//                    val uploaded = response.body()
//                    Log.d("res",response.toString())
//                    if (uploaded != null && uploaded.success) {
//
//                        // Pass uploaded.fileUrls to submitData
//                        submitData(
//                            activityName, start, end, desc,
//                            uploaded.fileUrls ?: emptyList()
//                        )
//
//                    } else {
//                        Toast.makeText(this@SubmitTimesheetFragment, "Upload failed!", Toast.LENGTH_SHORT).show()
//                    }
//                }
//
//                override fun onFailure(call: Call<FileResponse>, t: Throwable) {
//                    binding.btnSubmit.isEnabled = true
//                    binding.btnSubmit.text = "Submit"
//                    Toast.makeText(this@SubmitTimesheetFragment, "Upload Failed: ${t.message}", Toast.LENGTH_SHORT).show()
//                }
//            })
//
//    }

//    private fun submitData(
//        activityName: String,
//        start: String,
//        end: String,
//        desc: String,
//        fileResponses: List<String>
//    ) {
//        val api = RetrofitClient.instance
//
//        // convert list to JSON string (Gson)
//        val attachmentsJson = com.google.gson.Gson().toJson(fileResponses)
//
//        val sharedPref = getSharedPreferences("login_pref", Context.MODE_PRIVATE)
//        val userId = sharedPref.getString("user_id", "") ?: ""
//        val orgId = sharedPref.getString("org_id", "") ?: ""
//
//        binding.btnSubmit.isEnabled = false
//        binding.btnSubmit.text = "Submitting..."
//
//        api.submitTimesheet(
//            userId,
//            orgId,
//            activityName,
//            start,
//            end,
//            desc,
//            attachmentsJson
//        ).enqueue(object : Callback<ServerResponse> {
//            override fun onResponse(call: Call<ServerResponse>, response: Response<ServerResponse>) {
//                binding.btnSubmit.isEnabled = true
//                binding.btnSubmit.text = "Submit"
//
//                if (response.isSuccessful && response.body()?.status == "success") {
//                    cleanupTemp()
//                    Toast.makeText(this@SubmitTimesheetFragment, "Timesheet submitted!", Toast.LENGTH_SHORT).show()
//                    finish()
//                } else {
//                    Toast.makeText(this@SubmitTimesheetFragment, "Failed: ${response.body()?.message ?: response.message()}", Toast.LENGTH_SHORT).show()
//                }
//            }
//
//            override fun onFailure(call: Call<ServerResponse>, t: Throwable) {
//                binding.btnSubmit.isEnabled = true
//                binding.btnSubmit.text = "Submit"
//                Toast.makeText(this@SubmitTimesheetFragment, "Failed: ${t.message}", Toast.LENGTH_SHORT).show()
//            }
//        })
//    }

    private fun submitTimesheet() {

        val activityName = binding.edtActivity.text.toString().trim()
        val start = binding.edtStartTime.text.toString().trim()
        val end = binding.edtEndTime.text.toString().trim()
        val desc = binding.edtDescription.text.toString().trim()

        if (activityName.isEmpty() || start.isEmpty() || end.isEmpty()) {
            Toast.makeText(this, "Please fill required fields", Toast.LENGTH_SHORT).show()
            return
        }

        val sharedPref = getSharedPreferences("login_pref", Context.MODE_PRIVATE)
        val userId = sharedPref.getString("user_id", "") ?: ""
        val orgId = sharedPref.getString("org_id", "") ?: ""

        binding.btnSubmit.isEnabled = false
        binding.btnSubmit.text = "Submitting..."

        val api = RetrofitClient.instance

        // STEP  Create timesheet FIRST
        api.addTimesheet(
            userId,
            orgId,
            activityName,
            start,
            end,
            desc
        ).enqueue(object : Callback<TimesheetResponse> {

            override fun onResponse(
                call: Call<TimesheetResponse>,
                response: Response<TimesheetResponse>
            ) {

                if (!response.isSuccessful || response.body()?.status != "success") {
                    binding.btnSubmit.isEnabled = true
                    binding.btnSubmit.text = "Submit"
                    Toast.makeText(
                        this@SubmitTimesheetFragment,
                        "Failed to create timesheet",
                        Toast.LENGTH_SHORT
                    ).show()
                    return
                }

                val timesheetId = response.body()!!.timesheet_id

                // STEP  If no attachments → DONE
                if (tempFiles.isEmpty()) {
                    cleanupTemp()
                    Toast.makeText(
                        this@SubmitTimesheetFragment,
                        "Timesheet submitted!",
                        Toast.LENGTH_SHORT
                    ).show()
                    finish()
                    return
                }

                // STEP  Upload attachments using timesheet_id
                uploadAttachments(timesheetId.toString(), orgId, userId)
            }

            override fun onFailure(call: Call<TimesheetResponse>, t: Throwable) {
                binding.btnSubmit.isEnabled = true
                binding.btnSubmit.text = "Submit"
                Toast.makeText(
                    this@SubmitTimesheetFragment,
                    "Failed: ${t.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        })
    }

    private fun uploadAttachments(timesheetId: String, orgId: String, userId: String) {

        val api = RetrofitClient.instance

        val multipartList = mutableListOf<MultipartBody.Part>()
        for (file in tempFiles) {
            val reqFile = file.asRequestBody("*/*".toMediaTypeOrNull())
            multipartList.add(
                MultipartBody.Part.createFormData(
                    "attachments[]",
                    file.name,
                    reqFile
                )
            )
        }

        api.uploadMultipleAttachments(
            orgId.toRequestBody("text/plain".toMediaTypeOrNull()),
            userId.toRequestBody("text/plain".toMediaTypeOrNull()),
            timesheetId.toRequestBody("text/plain".toMediaTypeOrNull()),
            multipartList
        ).enqueue(object : Callback<FileResponse> {

            override fun onResponse(
                call: Call<FileResponse>,
                response: Response<FileResponse>
            ) {
                binding.btnSubmit.isEnabled = true
                binding.btnSubmit.text = "Submit"

                if (response.isSuccessful && response.body()?.success == true) {
                    cleanupTemp()
                    Toast.makeText(
                        this@SubmitTimesheetFragment,
                        "Timesheet submitted!",
                        Toast.LENGTH_SHORT
                    ).show()
                    finish()
                } else {
                    Toast.makeText(
                        this@SubmitTimesheetFragment,
                        "Attachment upload failed",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            override fun onFailure(call: Call<FileResponse>, t: Throwable) {
                binding.btnSubmit.isEnabled = true
                binding.btnSubmit.text = "Submit"
                Toast.makeText(
                    this@SubmitTimesheetFragment,
                    "Upload Failed: ${t.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        })
    }


    private fun cleanupTemp() {
        tempFiles.forEach { it.delete() }
        tempFiles.clear()
        selectedFileUris.clear()
    }

    override fun onDestroy() {
        cleanupTemp()
        super.onDestroy()
    }
}
