import React, { useEffect, useState } from "react";
import TaleButton from "@components/TaleButton";
import { TaleInput } from "@components/TaleInput";
import { companyService } from "@/api/companies";
import { isValidPixelId } from "@/utils/metaPixel";
import { useTranslation } from "@/hooks/useTranslation";

/** The backend's own explanation when it gave one; Meta's reasons are specific and actionable. */
const errorMessage = (error, fallback) => error?.response?.data?.message || fallback;

/**
 * The company's own Meta Pixel: the id its surveys report views and completed responses to, and the
 * Conversions API token used to check that the id really works.
 *
 * The token is write-only. Once saved it is never sent back, so the field stays empty and only says
 * that one is configured; typing a new one replaces it.
 */
export const MetaPixelSettings = ({ company, onCompanyChange }) => {
  const { t } = useTranslation();

  const [pixelId, setPixelId] = useState(company?.metaPixelId ?? "");
  const [accessToken, setAccessToken] = useState("");
  const [testEventCode, setTestEventCode] = useState("");
  const [saving, setSaving] = useState(false);
  const [removing, setRemoving] = useState(false);
  const [savingCapi, setSavingCapi] = useState(false);
  const [testing, setTesting] = useState(false);
  const [notice, setNotice] = useState(null);
  const [testResult, setTestResult] = useState(null);

  useEffect(() => {
    setPixelId(company?.metaPixelId ?? "");
  }, [company?.metaPixelId]);

  const tokenConfigured = Boolean(company?.metaAccessTokenConfigured);
  const trimmedPixelId = pixelId.trim();
  const pixelIdError =
      trimmedPixelId && !isValidPixelId(trimmedPixelId) ? t("account.metaPixel.pixelIdInvalid") : null;
  // A test uses what is saved, so unsaved edits would test something other than what is shown.
  const hasUnsavedChanges =
      trimmedPixelId !== (company?.metaPixelId ?? "") || accessToken.trim() !== "";
  const canTest = Boolean(company?.metaPixelId) && tokenConfigured && !hasUnsavedChanges;

  const handleSave = async () => {
    if (!company?.id || pixelIdError || !trimmedPixelId) return;
    setSaving(true);
    setNotice(null);
    setTestResult(null);
    try {
      const updated = await companyService.saveMetaPixel(company.id, {
        metaPixelId: trimmedPixelId,
        metaAccessToken: accessToken.trim() || undefined,
      });
      setAccessToken("");
      onCompanyChange?.(updated);
      setNotice({ type: "success", text: t("account.metaPixel.saved") });
    } catch (error) {
      setNotice({ type: "error", text: errorMessage(error, t("account.metaPixel.genericError")) });
    } finally {
      setSaving(false);
    }
  };

  // Saved on its own, straight away: it is a switch, not part of the pixel id and token form.
  const handleCapiToggle = async (enabled) => {
    if (!company?.id) return;
    setSavingCapi(true);
    setNotice(null);
    try {
      const updated = await companyService.saveMetaPixel(company.id, { metaCapiEnabled: enabled });
      onCompanyChange?.(updated);
      setNotice({
        type: "success",
        text: enabled ? t("account.metaPixel.capiTurnedOn") : t("account.metaPixel.capiTurnedOff"),
      });
    } catch (error) {
      setNotice({ type: "error", text: errorMessage(error, t("account.metaPixel.genericError")) });
    } finally {
      setSavingCapi(false);
    }
  };

  const handleRemove = async () => {
    if (!company?.id || !window.confirm(t("account.metaPixel.removeConfirm"))) return;
    setRemoving(true);
    setNotice(null);
    setTestResult(null);
    try {
      const updated = await companyService.removeMetaPixel(company.id);
      setPixelId("");
      setAccessToken("");
      setTestEventCode("");
      onCompanyChange?.(updated);
      setNotice({ type: "success", text: t("account.metaPixel.removed") });
    } catch (error) {
      setNotice({ type: "error", text: errorMessage(error, t("account.metaPixel.genericError")) });
    } finally {
      setRemoving(false);
    }
  };

  const handleTest = async () => {
    if (!company?.id || !canTest || !testEventCode.trim()) return;
    setTesting(true);
    setTestResult(null);
    try {
      const result = await companyService.testMetaPixel(company.id, testEventCode.trim());
      setTestResult(result);
    } catch (error) {
      setTestResult({ received: false, message: errorMessage(error, t("account.metaPixel.genericError")) });
    } finally {
      setTesting(false);
    }
  };

  const configured = Boolean(company?.metaPixelId);

  return (
      <div className="flex flex-col gap-4">
        <div className="flex items-center justify-between gap-3 flex-wrap">
          <div className="!text-[#111111] text-2xl font-semibold">{t("account.metaPixel.title")}</div>
          <span
              className={`text-sm font-medium px-3 py-1 rounded-full ${
                  configured ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-600"
              }`}
          >
            {configured ? t("account.metaPixel.statusActive") : t("account.metaPixel.statusNotConfigured")}
          </span>
        </div>
        <p className="text-sm text-gray-600">{t("account.metaPixel.description")}</p>

        <TaleInput
            role="business"
            label={t("account.metaPixel.pixelIdLabel")}
            value={pixelId}
            onChange={(e) => setPixelId(e.target.value.replace(/\s/g, ""))}
            placeholder={t("account.metaPixel.pixelIdPlaceholder")}
            inputMode="numeric"
            autoComplete="off"
            errorText={pixelIdError}
        />

        <div className="flex flex-col gap-1">
          <TaleInput
              role="business"
              label={t("account.metaPixel.tokenLabel")}
              value={accessToken}
              onChange={(e) => setAccessToken(e.target.value)}
              placeholder={
                tokenConfigured
                    ? t("account.metaPixel.tokenConfiguredPlaceholder")
                    : t("account.metaPixel.tokenPlaceholder")
              }
              type="password"
              autoComplete="new-password"
          />
          <span className="text-xs text-gray-500">{t("account.metaPixel.tokenHelp")}</span>
        </div>

        <div className="flex gap-3 flex-wrap">
          <TaleButton
              type="button"
              role="business"
              className="min-w-[140px]"
              onClick={handleSave}
              loading={saving}
              disabled={saving || !trimmedPixelId || Boolean(pixelIdError)}
          >
            {t("account.metaPixel.save")}
          </TaleButton>
          {configured ? (
              <button
                  type="button"
                  onClick={handleRemove}
                  disabled={removing}
                  className="px-4 text-sm font-semibold text-red-600 hover:text-red-700 disabled:opacity-50"
              >
                {t("account.metaPixel.remove")}
              </button>
          ) : null}
        </div>

        {notice ? (
            <div
                role={notice.type === "error" ? "alert" : "status"}
                className={`text-sm rounded-md px-3 py-2 ${
                    notice.type === "error" ? "bg-red-50 text-red-700" : "bg-green-50 text-green-700"
                }`}
            >
              {notice.text}
            </div>
        ) : null}

        {configured ? (
            <div className="flex flex-col gap-2 border border-gray-200 rounded-lg p-4">
              <label className="flex items-start gap-3 cursor-pointer">
                <input
                    type="checkbox"
                    className="mt-1 size-4 accent-[#F9BC33]"
                    checked={Boolean(company?.metaCapiEnabled)}
                    disabled={savingCapi || !tokenConfigured}
                    onChange={(e) => handleCapiToggle(e.target.checked)}
                />
                <span className="flex flex-col gap-1">
                  <span className="font-semibold text-[#111111]">{t("account.metaPixel.capiLabel")}</span>
                  <span className="text-sm text-gray-600">{t("account.metaPixel.capiDescription")}</span>
                  {!tokenConfigured ? (
                      <span className="text-sm text-amber-700">{t("account.metaPixel.capiNeedsToken")}</span>
                  ) : null}
                </span>
              </label>
            </div>
        ) : null}

        {configured ? (
            <div className="flex flex-col gap-3 border border-gray-200 rounded-lg p-4">
              <div className="font-semibold text-[#111111]">{t("account.metaPixel.testTitle")}</div>
              <p className="text-sm text-gray-600">{t("account.metaPixel.testDescription")}</p>

              {!tokenConfigured ? (
                  <p className="text-sm text-amber-700">{t("account.metaPixel.testNeedsToken")}</p>
              ) : hasUnsavedChanges ? (
                  <p className="text-sm text-amber-700">{t("account.metaPixel.testNeedsSave")}</p>
              ) : null}

              <TaleInput
                  role="business"
                  label={t("account.metaPixel.testCodeLabel")}
                  value={testEventCode}
                  onChange={(e) => setTestEventCode(e.target.value.trim())}
                  placeholder={t("account.metaPixel.testCodePlaceholder")}
                  autoComplete="off"
                  disabled={!canTest}
              />
              <div>
                <TaleButton
                    type="button"
                    role="business"
                    className="min-w-[180px]"
                    onClick={handleTest}
                    loading={testing}
                    disabled={testing || !canTest || !testEventCode.trim()}
                >
                  {t("account.metaPixel.testButton")}
                </TaleButton>
              </div>

              {testResult ? (
                  <div
                      role={testResult.received ? "status" : "alert"}
                      className={`text-sm rounded-md px-3 py-2 ${
                          testResult.received ? "bg-green-50 text-green-700" : "bg-red-50 text-red-700"
                      }`}
                  >
                    <div className="font-semibold">
                      {testResult.received
                          ? t("account.metaPixel.testSuccess")
                          : t("account.metaPixel.testFailed")}
                    </div>
                    {testResult.message ? <div>{testResult.message}</div> : null}
                    {testResult.fbtraceId ? (
                        <div className="text-xs opacity-70 mt-1">fbtrace_id: {testResult.fbtraceId}</div>
                    ) : null}
                  </div>
              ) : null}
            </div>
        ) : null}
      </div>
  );
};
