const {
  withAndroidManifest,
  withDangerousMod,
  withStringsXml,
} = require('expo/config-plugins');
const fs = require('fs');
const path = require('path');

const RECEIVER_NAME = '.QuickAddWidgetProvider';

const WIDGET_PROVIDER_XML = `<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="250dp"
    android:minHeight="40dp"
    android:targetCellWidth="4"
    android:targetCellHeight="1"
    android:updatePeriodMillis="0"
    android:initialLayout="@layout/widget_quick_add"
    android:resizeMode="horizontal"
    android:widgetCategory="home_screen"
    android:description="@string/widget_quick_add_description" />
`;

const WIDGET_LAYOUT_XML = `<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/widget_quick_add_bg"
    android:padding="14dp">

    <TextView
        android:id="@+id/widget_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="carry your live"
        android:textColor="#8E8E8E"
        android:textSize="12sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/quick_add_button"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:background="@drawable/widget_quick_add_button_bg"
        android:text="+ Add task"
        android:textColor="#FFFFFF"
        android:textSize="16sp"
        android:textStyle="bold" />
</LinearLayout>
`;

const WIDGET_BG_XML = `<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="#1E1E1E" />
    <corners android:radius="16dp" />
    <stroke android:width="1dp" android:color="#2A2A2A" />
</shape>
`;

const WIDGET_BUTTON_BG_XML = `<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="#EF5350" />
    <corners android:radius="12dp" />
</shape>
`;

function kotlinProvider(packageName) {
  return `package ${packageName}

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.RemoteViews

class QuickAddWidgetProvider : AppWidgetProvider() {

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        for (appWidgetId in appWidgetIds) {
            updateWidget(context, appWidgetManager, appWidgetId)
        }
    }

    private fun updateWidget(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetId: Int
    ) {
        val views = RemoteViews(context.packageName, R.layout.widget_quick_add)

        val openAppIntent = Intent(context, MainActivity::class.java).apply {
            action = Intent.ACTION_VIEW
            data = Uri.parse("exp+carry-your-live://quick-add")
        }
        val pendingIntent = PendingIntent.getActivity(
            context,
            0,
            openAppIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        views.setOnClickPendingIntent(R.id.quick_add_button, pendingIntent)

        appWidgetManager.updateAppWidget(appWidgetId, views)
    }
}
`;
}

function withQuickAddWidget(config) {
  const packageName = config.android?.package ?? 'com.anonymous.carryyourlive';

  config = withStringsXml(config, (config) => {
    const strings = config.modResults;
    if (!strings.resources.string) {
      strings.resources.string = [];
    }
    const existing = (strings.resources.string || []).find(
      (s) => s && s['$'] && s['$'].name === 'widget_quick_add_description'
    );
    if (!existing) {
      strings.resources.string.push({
        $: { name: 'widget_quick_add_description' },
        _: 'Quickly add a task',
      });
    }
    return config;
  });

  config = withAndroidManifest(config, (config) => {
    const manifest = config.modResults;
    const application = manifest.manifest.application?.[0];
    if (!application) return config;

    const receivers = application.receiver || [];
    const exists = receivers.some((r) => r && r['$'] && r['$']['android:name'] === RECEIVER_NAME);
    if (!exists) {
      application.receiver = [
        ...receivers,
        {
          $: {
            'android:name': RECEIVER_NAME,
            'android:exported': 'false',
            'android:label': 'Quick Add Task',
          },
          'intent-filter': [
            {
              action: [{ $: { 'android:name': 'android.appwidget.action.APPWIDGET_UPDATE' } }],
            },
          ],
          'meta-data': [
            {
              $: {
                'android:name': 'android.appwidget.provider',
                'android:resource': '@xml/quick_add_widget',
              },
            },
          ],
        },
      ];
    }
    return config;
  });

  config = withDangerousMod(config, [
    'android',
    async (config) => {
      const projectRoot = config.modRequest.projectRoot;
      const resDir = path.join(projectRoot, 'android', 'app', 'src', 'main', 'res');
      const javaDir = path.join(
        projectRoot,
        'android',
        'app',
        'src',
        'main',
        'java',
        ...packageName.split('.')
      );

      fs.mkdirSync(path.join(resDir, 'xml'), { recursive: true });
      fs.mkdirSync(path.join(resDir, 'layout'), { recursive: true });
      fs.mkdirSync(path.join(resDir, 'drawable'), { recursive: true });
      fs.mkdirSync(javaDir, { recursive: true });

      fs.writeFileSync(path.join(resDir, 'xml', 'quick_add_widget.xml'), WIDGET_PROVIDER_XML);
      fs.writeFileSync(path.join(resDir, 'layout', 'widget_quick_add.xml'), WIDGET_LAYOUT_XML);
      fs.writeFileSync(path.join(resDir, 'drawable', 'widget_quick_add_bg.xml'), WIDGET_BG_XML);
      fs.writeFileSync(
        path.join(resDir, 'drawable', 'widget_quick_add_button_bg.xml'),
        WIDGET_BUTTON_BG_XML
      );
      fs.writeFileSync(
        path.join(javaDir, 'QuickAddWidgetProvider.kt'),
        kotlinProvider(packageName)
      );

      return config;
    },
  ]);

  return config;
}

module.exports = withQuickAddWidget;
