"use client";

import { faSave } from "@fortawesome/free-solid-svg-icons";
import { useEffect, useState } from "react";
import Toast from "@/components/ui/Toast";
import { useAdminToast } from "@/hooks/admin/useAdminToast";
import AdminPageHeader from "@/components/admin/AdminPageHeader";
import AdminCard from "@/components/admin/AdminCard";
import AdminForm from "@/components/admin/AdminForm";
import AdminSection from "@/components/admin/AdminSection";
import AdminInput from "@/components/admin/AdminInput";
import AdminButton from "@/components/admin/AdminButton";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import { adminFetch } from "@/lib/adminFetch";

interface GoogleSettings {
  id: number;
  recaptchaSiteKey: string;
  recaptchaSecretKey: string;
  googleAnalyticsId: string;
}

export default function AdminGoogle() {
  const [settings, setSettings] = useState<GoogleSettings>({
    id: 0,
    recaptchaSiteKey: "",
    recaptchaSecretKey: "",
    googleAnalyticsId: "",
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { toast, showSuccess, showError, hideToast } = useAdminToast();

  useEffect(() => {
    fetchSettings();
  }, []);

  const fetchSettings = async () => {
    try {
      const response = await fetch("/api/google-settings");
      const data = await response.json();
      setSettings(
        data || {
          id: 0,
          recaptchaSiteKey: "",
          recaptchaSecretKey: "",
          googleAnalyticsId: "",
        },
      );
    } catch {
      showError("Failed to load Google settings");
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const response = await adminFetch("/api/google-settings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(settings),
      });

      if (!response.ok) throw new Error("Failed to save settings");

      showSuccess("Settings saved successfully!");
    } catch {
      showError("Failed to save settings");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <>
        <AdminPageHeader title="Google" description="Configure Google services" />
        <AdminLoadingState message="Loading Google settings..." />
      </>
    );
  }

  return (
    <>
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
      <AdminPageHeader
        title="Google"
        description="reCAPTCHA protection and Google Analytics integration"
      />

      <AdminCard>
        <AdminForm onSubmit={handleSubmit}>
          <AdminSection
            title="reCAPTCHA"
            description="Protect forms from spam using Google reCAPTCHA. Get your keys from the reCAPTCHA admin console."
          >
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <AdminInput
                label="Site key"
                type="text"
                name="recaptchaSiteKey"
                value={settings.recaptchaSiteKey}
                onChange={(e) =>
                  setSettings({ ...settings, recaptchaSiteKey: e.target.value })
                }
                placeholder="6Lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                helperText="Publicly visible, used on the client"
              />
              <AdminInput
                label="Secret key"
                type="password"
                name="recaptchaSecretKey"
                value={settings.recaptchaSecretKey}
                onChange={(e) =>
                  setSettings({ ...settings, recaptchaSecretKey: e.target.value })
                }
                placeholder="6Lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                helperText="Keep secret — used server-side for verification"
              />
            </div>
          </AdminSection>

          <AdminSection
            title="Google Analytics"
            description="Google Analytics 4 measurement ID for site-wide tracking"
          >
            <AdminInput
              label="Measurement ID"
              type="text"
              name="googleAnalyticsId"
              value={settings.googleAnalyticsId}
              onChange={(e) =>
                setSettings({ ...settings, googleAnalyticsId: e.target.value })
              }
              placeholder="G-XXXXXXXXXX"
              helperText="Starts with G-"
            />
          </AdminSection>

          <div className="-mx-6 -mb-6 mt-8 flex justify-end border-t border-slate-800 bg-slate-900/50 px-6 py-4">
            <AdminButton
              type="submit"
              variant="primary"
              isLoading={saving}
              icon={faSave}
            >
              Save changes
            </AdminButton>
          </div>
        </AdminForm>
      </AdminCard>
    </>
  );
}
