"use client";

import { useState, useEffect } from "react";
import type { LanguageCode } from "@/types/language";
import { SUPPORTED_LANGUAGES, LANGUAGE_NAMES } from "@/types/language";

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

export function LanguageTab({ onUpdate }: LanguageTabProps) {
  const [currentLanguage, setCurrentLanguage] = useState<LanguageCode>("pt");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

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

  const handleLanguageChange = async (language: LanguageCode) => {
    setLoading(true);
    setMessage(null);

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

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

  return (
    <div className="space-y-6">
      <div className="flex justify-between">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">Language Switch</h2>
          <p className="mt-1 text-sm text-slate-600">
            Select the language for the entire public site. Admin panel remains in English.
          </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 Language
            </label>
            <div className="grid gap-3 sm:grid-cols-3">
              {SUPPORTED_LANGUAGES.map((lang) => (
                <button
                  key={lang}
                  onClick={() => handleLanguageChange(lang)}
                  disabled={loading || currentLanguage === lang}
                  className={`rounded-lg border-2 p-4 text-center transition-all ${
                    currentLanguage === lang
                      ? "border-blue-500 bg-blue-50 text-blue-700"
                      : "border-slate-200 bg-white text-slate-700 hover:border-blue-300 hover:bg-blue-50"
                  } ${loading ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}`}
                >
                  <div className="font-semibold text-lg">{LANGUAGE_NAMES[lang]}</div>
                  <div className="text-xs text-slate-500 mt-1">({lang.toUpperCase()})</div>
                  {currentLanguage === lang && (
                    <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>• Language change affects the entire public site (UI, footer, metadata)</li>
              <li>• Admin panel always remains in English</li>
              <li>• SEO metadata (title, description, hreflang) updates automatically</li>
              <li>• Footer compliance blocks change per language</li>
              <li>• Page will reload after language change to apply updates</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
}

