"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { WidgetPreview } from "@/components/shared/widget-preview";

export default function WidgetSettingsPage() {
  const [syncEnabled, setSyncEnabled] = useState(false);
  const [syncSupported, setSyncSupported] = useState(false);
  const [registering, setRegistering] = useState(false);
  const [statusMessage, setStatusMessage] = useState("");

  useEffect(() => {
    // Check if periodic sync is supported
    if ("serviceWorker" in navigator && "periodicSync" in (ServiceWorkerRegistration.prototype ?? {})) {
      setSyncSupported(true);
    }

    // Check existing registration
    checkExistingSync();
  }, []);

  async function checkExistingSync() {
    try {
      const registration = await navigator.serviceWorker?.ready;
      if (registration && "periodicSync" in registration) {
        const tags = await (registration as unknown as { periodicSync: { getTags: () => Promise<string[]> } }).periodicSync.getTags();
        if (tags.includes("widget-update")) {
          setSyncEnabled(true);
        }
      }
    } catch {
      // Periodic sync not available
    }
  }

  async function toggleSync() {
    // E.11: ignore re-entry while a previous toggle is still in flight.
    // The page has two controls (the switch + the button) that both call
    // this function, so a quick double-tap previously caused conflicting
    // status messages.
    if (registering) return;
    setRegistering(true);
    setStatusMessage("");

    try {
      const registration = await navigator.serviceWorker?.ready;
      if (!registration) {
        setStatusMessage("Service worker not available. Please reload the page.");
        return;
      }

      if (syncEnabled) {
        // Unregister periodic sync
        if ("periodicSync" in registration) {
          await (registration as unknown as { periodicSync: { unregister: (tag: string) => Promise<void> } }).periodicSync.unregister("widget-update");
        }
        setSyncEnabled(false);
        setStatusMessage("Widget updates disabled.");
      } else {
        // Request permission and register periodic sync
        if ("periodicSync" in registration) {
          const status = await navigator.permissions.query({
            name: "periodic-background-sync" as PermissionName,
          });

          if (status.state === "granted" || status.state === "prompt") {
            await (registration as unknown as { periodicSync: { register: (tag: string, options: { minInterval: number }) => Promise<void> } }).periodicSync.register("widget-update", {
              minInterval: 60 * 60 * 1000, // 1 hour
            });
            setSyncEnabled(true);
            setStatusMessage("Widget updates enabled! Your home screen widget will update hourly.");
          } else {
            setStatusMessage("Permission for background sync was denied. Try enabling it in your browser settings.");
          }
        } else {
          setStatusMessage("Periodic background sync is not supported in this browser.");
        }
      }
    } catch (error) {
      console.error("Failed to toggle periodic sync:", error);
      setStatusMessage("Failed to toggle widget updates. This feature requires Android Chrome.");
    } finally {
      setRegistering(false);
    }
  }

  return (
    <div className="max-w-2xl mx-auto">
      <div className="mb-6">
        <Link
          href="/settings"
          className="text-sm text-text-muted hover:text-text transition-colors"
        >
          &larr; Back to Settings
        </Link>
      </div>

      <h1 className="text-3xl font-bold text-text mb-2">Home Screen Widget</h1>
      <p className="text-text-muted mb-8">
        Get a quick glance at your stats right from your home screen.
      </p>

      {/* Widget Preview */}
      <div className="bg-surface rounded-xl border border-surface-light p-6 mb-6">
        <h2 className="text-lg font-semibold text-text mb-4">Widget Preview</h2>
        <div className="max-w-xs mx-auto">
          <WidgetPreview />
        </div>
        <p className="text-xs text-text-muted text-center mt-4">
          This is how your widget will appear on the home screen.
        </p>
      </div>

      {/* Enable/Disable Section */}
      <div className="bg-surface rounded-xl border border-surface-light p-6 mb-6">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-lg font-semibold text-text">Periodic Updates</h2>
            <p className="text-sm text-text-muted mt-1">
              Keep widget data fresh with hourly background syncs.
            </p>
          </div>
          <button
            onClick={toggleSync}
            disabled={registering}
            className={`relative inline-flex h-7 w-12 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 focus:ring-offset-background disabled:opacity-50 ${
              syncEnabled ? "bg-primary" : "bg-surface-light"
            }`}
          >
            <span
              className={`inline-block h-5 w-5 rounded-full bg-white transition-transform shadow-sm ${
                syncEnabled ? "translate-x-6" : "translate-x-1"
              }`}
            />
          </button>
        </div>

        {statusMessage && (
          <p
            className={`text-sm mt-2 ${
              statusMessage.includes("enabled") || statusMessage.includes("disabled")
                ? "text-green-400"
                : "text-yellow-400"
            }`}
          >
            {statusMessage}
          </p>
        )}

        <button
          onClick={toggleSync}
          disabled={registering}
          className={`mt-4 px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50 ${
            syncEnabled
              ? "bg-red-600/20 text-red-400 border border-red-600/30 hover:bg-red-600/30"
              : "bg-primary hover:bg-primary-dark text-white"
          }`}
        >
          {registering
            ? "Processing..."
            : syncEnabled
            ? "Disable Widget Updates"
            : "Enable Widget Updates"}
        </button>
      </div>

      {/* Compatibility Note */}
      <div className="bg-surface rounded-xl border border-surface-light p-6">
        <h2 className="text-sm font-semibold text-primary mb-3 uppercase tracking-wide">
          Compatibility
        </h2>
        <div className="space-y-3 text-sm">
          <div className="flex items-start gap-3">
            <span className="text-green-400 mt-0.5 shrink-0">
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path
                  fillRule="evenodd"
                  d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                  clipRule="evenodd"
                />
              </svg>
            </span>
            <p className="text-text">
              <strong>Android Chrome</strong> — Full widget support with periodic background sync.
            </p>
          </div>
          <div className="flex items-start gap-3">
            <span className="text-yellow-400 mt-0.5 shrink-0">
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path
                  fillRule="evenodd"
                  d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
                  clipRule="evenodd"
                />
              </svg>
            </span>
            <p className="text-text">
              <strong>iOS Safari</strong> — Use push notifications instead. Widgets are not yet
              supported for PWAs on iOS.
            </p>
          </div>
          <div className="flex items-start gap-3">
            <span className="text-blue-400 mt-0.5 shrink-0">
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path
                  fillRule="evenodd"
                  d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
                  clipRule="evenodd"
                />
              </svg>
            </span>
            <p className="text-text-muted">
              {!syncSupported
                ? "Your current browser does not support periodic background sync."
                : "Your browser supports periodic background sync."}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
