<template>
  <div>
    <h2>PlatformServiceMixin Test</h2>
    <div class="space-y-2">
      <button
        :class="
          activeTest === 'insert'
            ? 'bg-green-500 text-white'
            : 'bg-gray-200 hover:bg-gray-300'
        "
        class="px-4 py-2 rounded mr-2 transition-colors"
        @click="testInsert"
      >
        Test Contact Insert
      </button>
      <button
        :class="
          activeTest === 'update'
            ? 'bg-green-500 text-white'
            : 'bg-gray-200 hover:bg-gray-300'
        "
        class="px-4 py-2 rounded mr-2 transition-colors"
        @click="testUpdate"
      >
        Test Contact Update
      </button>
      <button
        :class="
          activeTest === 'searchBoxes'
            ? 'bg-green-500 text-white'
            : 'bg-gray-200 hover:bg-gray-300'
        "
        class="px-4 py-2 rounded mr-2 transition-colors"
        @click="testSearchBoxesConversion"
      >
        Test SearchBoxes Conversion
      </button>
      <button
        :class="
          activeTest === 'database'
            ? 'bg-green-500 text-white'
            : 'bg-gray-200 hover:bg-gray-300'
        "
        class="px-4 py-2 rounded mr-2 transition-colors"
        @click="testDatabaseStorage"
      >
        Test SearchBox Database Storage -- Beware: Changes Your Search Box
      </button>
      <button
        :class="
          activeTest === 'userZero'
            ? 'bg-green-500 text-white'
            : primaryButtonClasses
        "
        class="transition-colors"
        @click="testUserZeroSettings"
      >
        Test User #0 Settings
      </button>
    </div>

    <div
      v-if="userZeroTestResult"
      class="mt-4 p-4 border border-gray-300 rounded-md bg-gray-50"
    >
      <h4 class="font-semibold mb-2">User #0 Settings Test Result:</h4>
      <pre class="text-sm">{{
        JSON.stringify(userZeroTestResult, null, 2)
      }}</pre>
    </div>

    <div v-if="result" class="mt-4">
      <div class="p-4 border border-blue-300 rounded-md bg-blue-50">
        <h4 class="font-semibold mb-2 text-blue-800">Test Results:</h4>
        <div
          class="whitespace-pre-wrap text-sm font-mono bg-white p-3 rounded border"
        >
          {{ result }}
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";

@Component({
  mixins: [PlatformServiceMixin],
})
export default class PlatformServiceMixinTest extends Vue {
  result: string = "";
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  userZeroTestResult: any = null;
  activeTest: string = ""; // Track which test is currently active

  // Add the missing computed property
  get primaryButtonClasses() {
    return "bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded";
  }

  testInsert() {
    this.activeTest = "insert";
    const contact = {
      name: "Alice",
      age: 30,
      isActive: true,
      tags: ["friend"],
    };
    const { sql, params } = this.$generateInsertStatement(contact, "contacts");
    this.result = `SQL: ${sql}\nParams: ${JSON.stringify(params)}`;
  }

  testUpdate() {
    this.activeTest = "update";
    const changes = { name: "Bob", isActive: false };
    const { sql, params } = this.$generateUpdateStatement(
      changes,
      "contacts",
      "id = ?",
      [42],
    );
    this.result = `SQL: ${sql}\nParams: ${JSON.stringify(params)}`;
  }

  testSearchBoxesConversion() {
    this.activeTest = "searchBoxes";
    // Test the _convertSettingsForStorage helper method
    const testSettings = {
      firstName: "John",
      searchBoxes: [
        {
          name: "Test Area",
          bbox: {
            eastLong: 1.0,
            maxLat: 1.0,
            minLat: 0.0,
            westLong: 0.0,
          },
        },
      ],
    };

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const converted = (this as any)._convertSettingsForStorage(testSettings);

    this.result = `# 🔄 SearchBoxes Conversion Test (Helper Method)

## 📥 Input Settings
\`\`\`json
{
  "firstName": "John",
  "searchBoxes": ${JSON.stringify(testSettings.searchBoxes, null, 2)}
}
\`\`\`

## 🔧 After _convertSettingsForStorage()
\`\`\`json
{
  "firstName": "John",
  "searchBoxes": "${converted.searchBoxes}"
}
\`\`\`

## ✅ Conversion Results
- **Original Type**: \`${typeof testSettings.searchBoxes}\`
- **Converted Type**: \`${typeof converted.searchBoxes}\`
- **Conversion**: Array → JSON String ✅

## 📝 Note
This tests the helper method only - no database interaction`;
  }

  async testDatabaseStorage() {
    this.activeTest = "database";
    try {
      this.result = "🔄 Testing database storage format...";

      // Create test settings with searchBoxes array
      const testSettings = {
        searchBoxes: [
          {
            name: "Test Area",
            bbox: {
              eastLong: 1.0,
              maxLat: 1.0,
              minLat: 0.0,
              westLong: 0.0,
            },
          },
        ],
      };

      // Save to database using our fixed method
      const success = await this.$saveSettings(testSettings);

      if (success) {
        // Now query the raw database to see how it's actually stored.
        // Note that new users probably have settings with ID of 1 but old migrated users might skip to 2.
        const rawResult = await this.$dbQuery(
          "SELECT searchBoxes FROM settings limit 1",
        );

        if (rawResult?.values?.length) {
          const rawSearchBoxes = rawResult.values[0][0]; // First column of first row

          this.result = `# 🔧 Database Storage Format Test (Full Database Cycle)

## 📥 Input (JavaScript Array)
\`\`\`json
${JSON.stringify(testSettings.searchBoxes, null, 2)}
\`\`\`

## 💾 Database Storage (JSON String)
\`\`\`sql
"${rawSearchBoxes}"
\`\`\`

## ✅ Verification
- **Type**: \`${typeof rawSearchBoxes}\`
- **Is JSON String**: \`${typeof rawSearchBoxes === "string" && rawSearchBoxes.startsWith("[")}\`
- **Conversion Working**: ✅ **YES** - Array converted to JSON string for database storage

## 🔄 Process Flow
1. **Input**: JavaScript array with bounding box coordinates
2. **Conversion**: \`_convertSettingsForStorage()\` converts array to JSON string
3. **Storage**: JSON string saved to database using \`$saveSettings()\`
4. **Retrieval**: JSON string parsed back to array for application use

## 📝 Note
This tests the complete save → retrieve cycle with actual database interaction`;
        } else {
          this.result = "❌ No data found in database";
        }
      } else {
        this.result = "❌ Failed to save settings";
      }
    } catch (error) {
      this.result = `❌ Error: ${error}`;
    }
  }

  async testUserZeroSettings() {
    this.activeTest = "userZero";
    try {
      // User #0's DID
      const userZeroDid = "did:ethr:0x0000694B58C2cC69658993A90D3840C560f2F51F";

      this.result = "Testing User #0 settings...";

      // Test the debug methods
      await this.$debugMergedSettings(userZeroDid);

      // Get the actual settings
      const didSettings = await this.$debugDidSettings(userZeroDid);
      const accountSettings = await this.$accountSettings(userZeroDid);

      this.userZeroTestResult = {
        didSettings,
        accountSettings,
        isRegistered: accountSettings.isRegistered,
        firstName: accountSettings.firstName,
        timestamp: new Date().toISOString(),
      };

      this.result = `User #0 settings test completed. isRegistered: ${accountSettings.isRegistered}`;
    } catch (error) {
      this.result = `Error testing User #0 settings: ${error}`;
      // eslint-disable-next-line no-console
      console.error("Error testing User #0 settings:", error);
    }
  }
}
</script>
