import { StringCaser } from "@/utils/utils";
import { generateComponentId, getComponentViewBindingId } from "./helpers";
import { generateComponent } from "../translator/TranslatorFragmentXmlAndroid";
import { findComponentsWithNavigationProperty } from "./navigation";

export const generateViewHolderName = (recycler) => {
  return `holder_${StringCaser(recycler.props.name, {
    casetype: "lowercase",
    separator: "_",
  })}`;
};

export const generateStaticRecyclerDataClass = (recycler, config) => {
  let name = StringCaser(recycler.props.name, { casetype: "capitalize" });
  let api =
    StringCaser(
      config.api.filter((a) => a.id == recycler.dataSource)[0]?.name,
      { casetype: "camelCase" }
    ) ?? "";
  const apiField = config.api.find((apiItem) => {
    return StringCaser(apiItem?.name, { casetype: "camelCase" }) === api;
  });

  // const apiGroup = config.api.find((apiItem) => {
  //   return StringCaser(apiItem?.name, { casetype: "camelCase" }) === api;
  // });

  return `
package com.manaknight.app.data

import androidx.lifecycle.LifecycleOwner
import ${config.packageName}.adapters.${name}RecyclerAdapter
import ${config.packageName}.network.Status
import ${config.packageName}.viewmodels.BaasViewModel
import java.io.Serializable


data class ${name}Model(${recycler.props.fields
      .split(",")
      .map((f) => `val ${f}: String`)
      .join(", ")}): Serializable

fun load${name}Data(viewLifecycleOwner: LifecycleOwner, baasViewModel: BaasViewModel, adapter: ${name}RecyclerAdapter) {

    baasViewModel.${api}(${apiField?.group == "custom" ? "" : `"id,desc", "1,20", "", ""`}).observe(viewLifecycleOwner) {
      when (it.status) {
        Status.ERROR -> println(it.message ?: "Something went wrong")
        Status.LOADING -> {}

        Status.SUCCESS -> {
            val list: List<${name}Model> = it.data?.list!!.map { map ->
        ${recycler.props.fields.split(",").map((f) => {
        if (apiField?.columns) {
          // console.log("apiField?.columns: ", apiField?.columns)
          return `val ${f} = map["${f.trim()}"]${apiField?.columns[f.trim()] == "int"
            ? `.toString() as? String ?: ""`
            : `as? String ?: ""`
            }
                                `
        }
        else if (apiField?.response) {
          console.log("apiField?.response: ", apiField?.response)
          return `val ${f} = map["${f.trim()}"]${apiField?.response[f.trim()] == "int"
            ? `.toString() as? String ?: ""`
            : `as? String ?: ""`
            }
                                `
        }
      }).join("\n ")}
                   
                    ${name}Model( ${recycler.props.fields.split(",").map((f) => {
        if (apiField?.columns) {
          return `${f}${apiField?.columns[f.trim()] == "int" ? `.substringBefore(".")` : ``
            }`
        }
        else if (apiField?.response) {
          return `${f}${apiField?.response[f.trim()] == "int" ? `.substringBefore(".")` : ``
            }`
        }
      }).join(", ")})
                }

                adapter.updateData(list)

            }
        }
    }
}



    `;
};

export const generateRecyclerAdapter = (recycler, config) => {
  let name = StringCaser(recycler.props.name, { casetype: "capitalize" });
  let _name = StringCaser(recycler.props.name, {
    casetype: "lowercase",
    separator: "_",
  });
  let currRecycler = findRecyclerViews(recycler)

  return `
    package com.manaknight.app.adapters

    import Manaknight.R
    import android.content.Context
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import android.widget.TextView
    import android.widget.ImageView
    import androidx.recyclerview.widget.RecyclerView
    import ${config.packageName}.data.${name}Model
    import com.manaknight.app.extensions.loadImageFromUrl
    import androidx.navigation.findNavController
    // import ${config.packageName}.ui.${name}FragmentDirections
    // import com.manaknight.app.adapters.VideoRecyclerAdapter
    // import ${config.packageName}.adapters.${StringCaser(getTextBetweenUnderscoreAndList(currRecycler[0]?.dataSource) || currRecycler[0]?.dataSourceName, {
    casetype: "capitalize",
  })}RecyclerAdapter

    
    class ${name}RecyclerAdapter(
                              private var dataset: List<${name}Model>
                                ): RecyclerView.Adapter<${name}RecyclerAdapter.ViewHolder>()    {
        class ViewHolder(private val view: View): RecyclerView.ViewHolder(view) {
            fun bind(model: ${name}Model) {
                ${recycler.props.fields
      .split(",")
      .map((f) => getItemBinding(_name, f))
      .join("\n ")}

                  ${getActionBinding(recycler, config.fragment)}
            }
        }
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val adapterLayout = LayoutInflater.from(parent.context)
                .inflate(R.layout.${generateViewHolderName(
        recycler
      )}, parent, false)
    
            return ViewHolder(adapterLayout)
        }
    
        override fun getItemCount(): Int {
            return dataset.size;
        }
    
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = dataset[position]
            holder.bind(item)
        }

        fun updateData(newData: List<${name}Model>) {
            dataset = newData
            notifyDataSetChanged()
        }
    }
    
    
    `;
};

function getTextBetweenUnderscoreAndList(inputString) {
  const regex = /_(.*?)List/g;
  const matches = regex.exec(inputString);
  if (matches && matches.length > 1) {
    return matches[1];
  } else {
    return null; // or any other value indicating no match found
  }
}

export const getRecyclerViewFields = (fragment) => {
  const content = [];
  const recyclerViews = findRecyclerViews(fragment, []);
  for (const view of recyclerViews) {
    let name = StringCaser(view.props.name, { casetype: "capitalize" });
    content.push(
      ` private lateinit var adapter${name}: ${name}RecyclerAdapter`
    );
  }

  return content.join("\n");
};
export const generateRecyclerViewFragmentBinding = (
  fragment,
  configuration
) => {
  // This would be generated in the fragment
  const content = [];
  const recyclerViews = findRecyclerViews(fragment, []);
  for (const view of recyclerViews) {
    let name = StringCaser(view.props.name, { casetype: "capitalize" });
    content.push(`
            val ${getComponentViewBindingId(
      view
    )} = binding.${getComponentViewBindingId(view)}
             adapter${name} = ${name}RecyclerAdapter(emptyList())
            ${getComponentViewBindingId(view)}.layoutManager = ${view.props.layout_manager == "linear"
        ? "LinearLayoutManager(requireContext())"
        : `GridLayoutManager(requireContext(), ${view.props.columns})`
      }
    
            load${name}Data(viewLifecycleOwner, baasViewModel, adapter${name})
            ${getComponentViewBindingId(view)}.adapter = adapter${name}
        `);
  }
  return content.join("\n");
};

export const generateRecyclerViewImport = (fragment, configuration) => {
  const uniqueLines = new Set();
  const carouselViews = findRecyclerViews(fragment, []);
  const content = [];


  for (const view of carouselViews) {
    let name = StringCaser(view.props.name, { casetype: "capitalize" });
    // let name = StringCaser(getTextBetweenUnderscoreAndList(view?.dataSource), {
    //   casetype: "capitalize",
    // })
    const imports = [
      ` ${configuration.packageName}.adapters.${name}RecyclerAdapter`,
      ` ${configuration.packageName}.data.load${name}Data`,
      " androidx.recyclerview.widget.GridLayoutManager",
      " androidx.recyclerview.widget.LinearLayoutManager",

    ];

    for (const line of imports) {
      if (!uniqueLines.has(line)) {
        uniqueLines.add(line);
        content.push(`import ${line}`);
      }
    }
  }
  return content.join("\n");
};

export function findRecyclerViews(data, result = []) {
  if (!Array.isArray(data)) data = [data];
  for (const item of data) {
    if ("components" in item) {
      findRecyclerViews(item.components, result);
    }
    if ("children" in item) {
      findRecyclerViews(item.children, result);
    }
    if (item.name === "RecyclerView") {
      result.push(item);
    }
  }
  return result;
}

export const buildRecyclerViewHolder = (recyclerView) => {
  let uiTemplate = viewHolderXml(recyclerView);
  let _name = StringCaser(recyclerView.props.name, {
    casetype: "lowercase",
    separator: "_",
  });
  let content = recyclerView.props.fields
    .split(",")
    .map((f) => getItemTemplate(_name, f));

  let action = recyclerView?.children?.map((f) => getChildrenTemplate(_name, f));

  return uiTemplate
    .replace("{{{CONTENT}}}", content?.join("\n"))
    .replace("{{{ACTION}}}", action?.join("\n"));
};

const viewHolderXml = (recyclerView) => {
  return `<?xml version="1.0" encoding="utf-8"?>
  <androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="8dp"
    app:cardElevation="4dp"
    app:cardUseCompatPadding="true">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">
          {{{CONTENT}}}
          {{{ACTION}}}
    </LinearLayout>

    </androidx.cardview.widget.CardView>

  `;
};

const getChildrenTemplate = (name = "", field = "") => {
  return field ? generateComponent(field) : "";
};

const getItemTemplate = (name = "", field = "") => {
  field = field.trim();
  if (field.indexOf("image") > -1) {
    return `
        <ImageView
            android:id="@+id/${name}_${field}"
            android:layout_width="match_parent"
            android:scaleType="centerCrop"
            android:layout_height="231dp"
            android:layout_margin="2dp"
            android:src="@drawable/ic_loc_active"
             />
        `;
  }

  return `
    <TextView
        android:id="@+id/${name}_${field}"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="${field}"
        android:textSize="12sp"
        android:padding="2dp"
        android:layout_margin="2dp"
        android:textColor="@android:color/black" />
    `;
};

const getItemBinding = (name = "", field = "") => {
  field = field.trim();
  if (field.indexOf("image") > -1) {
    return ` view.findViewById<ImageView>(R.id.${name}_${field}).loadImageFromUrl(model.${field}) `;
  }
  return `view.findViewById<TextView>(R.id.${name}_${field}).text = model.${field}  `;
};

const getActionBinding = (recycler, fragment) => {
  if (findRecyclerViews(fragment).length == 0) return "";

  let navElements = findComponentsWithNavigationProperty(recycler);
  const content = [];

  let parentFragment = fragment.find((frag) => frag.id == recycler.pageId);
  const fragmentCapitalizedName = StringCaser(parentFragment?.name || "", {
    casetype: "capitalize",
  });

  for (const element of navElements) {
    if (["sign_up", "login"].includes(element.props.to)) continue;

    let destinationFragment = fragment.find(
      (frag) => frag.id == element.props.to
    );
    const destinationCapitalized = StringCaser(destinationFragment?.name, {
      casetype: "capitalize",
    });

    const elementId = generateComponentId(element);
    if (element.name === "ImageView") {
      content.push(` view.findViewById<ImageView>(R.id.${elementId}).setOnClickListener{
        ${recycler.props.pass_data
          ? `val action = ${fragmentCapitalizedName}FragmentDirections.action${fragmentCapitalizedName}FragmentTo${destinationCapitalized}Fragment(model)
                    view.findNavController().navigate(action)`
          : `view.findNavController().navigate(R.id.action_${fragmentCapitalizedName}Fragment_to_${destinationCapitalized}Fragment)`
        }
                } `);
    }
    content.push(`view.findViewById<TextView>(R.id.${elementId}).setOnClickListener{
        ${recycler.props.pass_data
        ? `val action = ${fragmentCapitalizedName}FragmentDirections.action${fragmentCapitalizedName}FragmentTo${destinationCapitalized}Fragment(model)
                 view.findNavController().navigate(action)`
        : `view.findNavController().navigate(R.id.action_${fragmentCapitalizedName}Fragment_to_${destinationCapitalized}Fragment)`
      }
        
                }  `);
  }
  return content.map((c) => c).join("\n");
};
