"use client";

import { useState, useEffect } from "react";
import type { ThemeId } from "@/types/theme";
import { SUPPORTED_THEMES, THEME_NAMES } from "@/types/theme";
import { getColorTheme } from "@/lib/color-theme";

interface ThemeTabProps {
  readonly onUpdate?: () => void;
}

export function ThemeTab({ onUpdate }: ThemeTabProps) {
  const [currentTheme, setCurrentTheme] = useState<ThemeId>("2");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  // Load current theme on mount
  useEffect(() => {
    const loadTheme = async () => {
      try {
        // Add cache-busting parameter to ensure fresh data
        const response = await fetch(`/api/theme?t=${Date.now()}`, {
          cache: 'no-store',
        });
        if (response.ok) {
          const data = await response.json();
          setCurrentTheme(data.theme || "2");
        }
      } catch (error) {
        console.error("Failed to load theme:", error);
      }
    };
    loadTheme();
  }, []);

  const handleThemeChange = async (theme: ThemeId) => {
    setLoading(true);
    setMessage(null);

    try {
      const response = await fetch("/api/theme", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ theme }),
      });

      if (response.ok) {
        setCurrentTheme(theme);
        setMessage({ type: "success", text: `Theme changed to ${THEME_NAMES[theme]}` });
        // Reload page to apply theme changes
        setTimeout(() => {
          window.location.reload();
        }, 1000);
      } else {
        setMessage({ type: "error", text: "Failed to change theme" });
      }
    } catch (error) {
      console.error("Error changing theme:", error);
      setMessage({ type: "error", text: "Failed to change theme" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">Theme Switch</h2>
          <p className="mt-1 text-sm text-slate-600">
            Select the color theme for the entire public site. Changes affect all colors (buttons, badges, backgrounds).
          </p>
        </div>
      </div>

      {message && (
        <div
          className={`rounded-lg border p-4 ${
            message.type === "success"
              ? "border-green-200 bg-green-50 text-green-800"
              : "border-red-200 bg-red-50 text-red-800"
          }`}
        >
          {message.text}
        </div>
      )}

      <div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-3">
              Current Theme
            </label>
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {SUPPORTED_THEMES.map((theme) => {
                const colorTheme = getColorTheme(theme);
                return (
                  <button
                    key={theme}
                    onClick={() => handleThemeChange(theme)}
                    disabled={loading || currentTheme === theme}
                    className={`rounded-lg border-2 p-4 text-left transition-all ${
                      currentTheme === theme
                        ? "border-blue-500 bg-blue-50"
                        : "border-slate-200 bg-white hover:border-blue-300 hover:bg-blue-50"
                    } ${loading ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}`}
                  >
                    <div className="flex items-center gap-3 mb-3">
                      <div className="flex gap-1.5">
                        <div
                          className="w-8 h-8 rounded"
                          style={{ backgroundColor: colorTheme.buttonBadge }}
                        />
                        <div
                          className="w-8 h-8 rounded"
                          style={{ backgroundColor: colorTheme.welcomeBonus }}
                        />
                        <div
                          className="w-8 h-8 rounded"
                          style={{ backgroundColor: colorTheme.cardBackground }}
                        />
                      </div>
                      <div>
                        <div className="font-semibold text-lg text-slate-900">{THEME_NAMES[theme]}</div>
                        <div className="text-xs text-slate-500">Theme {theme}</div>
                      </div>
                    </div>
                    <div className="text-xs text-slate-600 space-y-1">
                      <div>Button/Badge: <span className="font-mono">{colorTheme.buttonBadge}</span></div>
                      <div>Welcome Bonus: <span className="font-mono">{colorTheme.welcomeBonus}</span></div>
                      <div>Background: <span className="font-mono">{colorTheme.cardBackground}</span></div>
                    </div>
                    {currentTheme === theme && (
                      <div className="mt-2 text-xs font-medium text-blue-600">Active</div>
                    )}
                  </button>
                );
              })}
            </div>
          </div>

          <div className="mt-6 rounded-lg border border-amber-200 bg-amber-50 p-4">
            <h3 className="font-semibold text-amber-900 mb-2">Important Notes</h3>
            <ul className="space-y-1 text-sm text-amber-800">
              <li>• Theme change affects all colors on the public site (buttons, badges, backgrounds, borders)</li>
              <li>• Language and theme are independent - changing one does not affect the other</li>
              <li>• Page will reload after theme change to apply updates</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
}

