#include "smartconfig.h"

#include <WiFi.h>
#include <Preferences.h>

WebServer server(80);
DNSServer dnsServer;
Preferences preferences;

IPAddress apIP(192, 168, 4, 1);

bool should_reboot = false;
bool smartconfig_done = false;

const char *HTML_FORM = R"rawliteral(
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Helios Charge Point 配网</title>
  <style>
    :root { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #1f2a37; }
    body { margin: 0; background: #f4f6fb; display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 16px; }
    .card { width: min(360px, 100%); background: #fff; border-radius: 16px; padding: 24px; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.12); }
    h2 { margin: 0 0 16px; font-size: 1.4rem; text-align: center; }
    label { display: block; margin-bottom: 6px; font-weight: 600; }
    input[type="text"], input[type="password"] {
      width: 100%; padding: 12px; margin-bottom: 16px; border: 1px solid #d0d7e2; border-radius: 10px;
      font-size: 1rem; transition: border 0.2s, box-shadow 0.2s;
    }
    input:focus { outline: none; border-color: #2563eb; box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15); }
    input[type="submit"] {
      width: 100%; padding: 12px; border: none; border-radius: 10px; background: #2563eb; color: #fff;
      font-size: 1rem; font-weight: 600; cursor: pointer; transition: background 0.2s;
    }
    input[type="submit"]:hover { background: #1d4ed8; }
  </style>
</head>
<body>
  <div class="card">
    <h2>配置 WiFi</h2>
    <form action="/save" method="POST">
      <label for="ssid">SSID</label>
      <input type="text" id="ssid" name="ssid" required>
      <label for="password">密码</label>
      <input type="password" id="password" name="password" required>
      <input type="submit" value="保存并连接">
    </form>
  </div>
</body>
</html>
)rawliteral";

void handleCaptivePortal()
{
  String host = server.hostHeader();
  server.sendHeader("Location", String("http://") + apIP.toString(), true);
  server.send(302, "text/plain", "");
}

void handleRoot()
{
  server.send(200, "text/html", HTML_FORM);
}

void handleSave()
{
  if (server.hasArg("ssid") && server.hasArg("password"))
  {
    String ssid = server.arg("ssid");
    String password = server.arg("password");

    Serial.printf("Received SSID: %s, PASSWORD: %s\n", ssid.c_str(), password.c_str());

    // save to NVS
    preferences.begin("wifi", false);
    preferences.putString("ssid", ssid);
    preferences.putString("password", password);
    preferences.end();

    String response = "<html><head><meta charset=\"UTF-8\"></head><body><h3>配置已保存，设备正在尝试连接网络...</h3></body></html>";
    server.send(200, "text/html", response);

    // flag to reboot
    should_reboot = true;
  }
  else
  {
    server.send(400, "text/plain", "缺少 SSID 或密码");
  }
}

void startSmartConfig(char *ssid, char *psk)
{
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP(ssid, psk);

  dnsServer.start(53, "*", apIP);

  server.on("/", handleRoot);
  server.on("/save", handleSave);

  server.on("/generate_204", HTTP_GET, handleCaptivePortal);        // Android
  server.on("/ncsi.txt", HTTP_GET, handleCaptivePortal);            // Windows
  server.on("/hotspot-detect.html", HTTP_GET, handleCaptivePortal); // iOS
  server.onNotFound(handleCaptivePortal);

  server.begin();
  Serial.println("HTTP server started");
}

bool connectToSavedWiFi()
{
  preferences.begin("wifi", true);
  String ssid = preferences.getString("ssid", "");
  String password = preferences.getString("password", "");
  preferences.end();

  if (ssid == "")
  {
    Serial.println("No saved WiFi credentials");
    return false;
  }

  Serial.printf("Connecting to SSID: %s\n", ssid.c_str());
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid.c_str(), password.c_str());

  unsigned long start = millis();
  const unsigned long timeout = 15000; // 15 secs

  while (WiFi.status() != WL_CONNECTED && millis() - start < timeout)
  {
    Serial.print(".");
    delay(500);
  }

  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.println("\nWiFi connected!");
    Serial.printf("IP address: %s\n", WiFi.localIP().toString().c_str());
    smartconfig_done = true;
    return true;
  }
  else
  {
    Serial.println("\nWiFi connect failed.");
    return false;
  }
}
