package com.example.modifier.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.content.res.AppCompatResources
import androidx.recyclerview.widget.RecyclerView
import com.example.modifier.Global
import com.example.modifier.R
import com.example.modifier.Utils
import com.example.modifier.adapter.BackupAdapter.BackupViewHolder
import com.example.modifier.data.BackupItem
import com.example.modifier.data.BackupItemDao
import com.example.modifier.databinding.ItemBackupBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date


class BackupAdapter(
    private val context: Context,
    private val backups: MutableList<BackupItem>,
    private val backupItemDao: BackupItemDao
) :
    RecyclerView.Adapter<BackupViewHolder>() {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BackupViewHolder {
        val binding = ItemBackupBinding.inflate(
            LayoutInflater.from(
                context
            ), parent, false
        )
        return BackupViewHolder(binding)
    }

    @SuppressLint("DefaultLocale")
    override fun onBindViewHolder(holder: BackupViewHolder, position: Int) {
        val backup = backups[position]
        holder.binding.tvNumber.text = "+${backup.code} ${backup.number}"
        holder.binding.tvTime.text =
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(backup.createdAt))
        holder.binding.tvInfo.text = String.format(
            "MCC: %s, MNC: %s, Country: %s, SendCount: %d, Fresh: %b",
            backup.mcc, backup.mnc, backup.country.uppercase(), backup.sendCount, backup.fresh
        )
        holder.binding.btnRestore.setOnClickListener { v: View? ->
            MaterialAlertDialogBuilder(
                context
            )
                .setTitle("Restore backup")
                .setMessage("Are you sure you want to restore this backup?")
                .setPositiveButton("Yes") { dialog: DialogInterface?, which: Int ->
                    dialog?.dismiss()
                    Utils.makeLoadingButton(context, holder.binding.btnRestore)
                    CoroutineScope(Dispatchers.IO).launch {
                        try {
                            Global.restore(backup)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                        withContext(Dispatchers.Main) {
                            holder.binding.btnRestore.isEnabled = true
                            holder.binding.btnRestore.icon = AppCompatResources.getDrawable(
                                context,
                                R.drawable.ic_settings_backup_restore
                            )
                        }
                    }
                }
                .setNegativeButton("No", null)
                .show()
        }
        holder.binding.btnDel.setOnClickListener { v: View? ->
            MaterialAlertDialogBuilder(
                context
            )
                .setTitle("Delete backup")
                .setMessage("Are you sure you want to delete this backup?")
                .setPositiveButton("Yes") { dialog: DialogInterface?, which: Int ->
                    CoroutineScope(Dispatchers.IO).launch {
                        val file = File(backup.path)
                        if (file.exists()) {
                            try {
                                File(backup.path).deleteRecursively()

                            } catch (e: Exception) {
                                e.printStackTrace()
                                Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
                            }
                        } else {
                            Log.e("BackupAdapter", "File not found")
                        }
                        backups.remove(backup)
                        withContext(Dispatchers.Main) {
                            notifyItemRemoved(position)
                        }
                        backupItemDao.delete(backup)
                    }

                }
                .setNegativeButton("No", null)
                .show()
        }
    }

    override fun getItemCount(): Int {
        return backups.size
    }

    inner class BackupViewHolder(var binding: ItemBackupBinding) : RecyclerView.ViewHolder(
        binding.root
    )
}
