/* eslint-disable @typescript-eslint/no-misused-promises */
import { useState } from "react";
import { toast } from "react-toastify";
import "../../index.css";
import "../../tailwind.css";
import "./register.css";
import {
  register,
  verifyEmail,
  resendCode,
  getBotByApiKey,
  saveConfig,
  type RegisterData,
} from "./services/wordpress-api/shopinzen-integrator.service";
import { useIntl } from "react-intl";
import { window_SHOPINZEN_INTEGRATOR_object } from "@src/dev-env";

// Fonctions helper pour le loader
const showLoader = () => {
  const loader = document.getElementById("shopinzen-loader");
  if (loader) loader.classList.add("active");
};

const hideLoader = () => {
  const loader = document.getElementById("shopinzen-loader");
  if (loader) loader.classList.remove("active");
};

function App() {
  const [activeTab, setActiveTab] = useState<"register" | "api-key">(
    "register",
  );
  const [showEmailVerification, setShowEmailVerification] = useState(false);
  const [userEmail, setUserEmail] = useState("");

  return (
    <div className="shopinzen-integrator-wrap">
      {/* Hero Section */}
      <HeroSection />

      {/* Formulaire */}
      <div className="shopinzen-content">
        {/* Onglets */}
        <Tabs activeTab={activeTab} onTabChange={setActiveTab} />

        {/* Contenu onglet inscription */}
        {activeTab === "register" && (
          <RegisterTab
            showEmailVerification={showEmailVerification}
            setShowEmailVerification={setShowEmailVerification}
            userEmail={userEmail}
            setUserEmail={setUserEmail}
            setActiveTab={setActiveTab}
          />
        )}

        {/* Contenu onglet clé API */}
        {activeTab === "api-key" && <ApiKeyTab />}
      </div>

      {/* Loader */}
      <Loader />
    </div>
  );
}

// Hero Section
const HeroSection = () => {
  const intl = useIntl();

  return (
    <div className="shopinzen-hero">
      <div className="shopinzen-hero-overlay"></div>
      <div className="shopinzen-hero-content">
        <p className="shopinzen-hero-tag">
          {intl.formatMessage({
            defaultMessage: "100 % FREEMIUM – COMMENCEZ SANS PAYER",
            id: "hiPs8R",
          })}
        </p>
        <h1>
          {intl.formatMessage({
            defaultMessage:
              "Créez votre chatbot IA personnalisé pour votre site en quelques clics",
            id: "KEHqE0",
          })}
        </h1>
        <p className="shopinzen-hero-desc">
          {intl.formatMessage({
            defaultMessage:
              "ShopinZen rend votre site vivant : un chatbot intelligent qui guide vos visiteurs, booste vos conversions et révolutionne leur expérience, sans aucune ligne de code.",
            id: "aSMbeE",
          })}
        </p>
        <div className="shopinzen-hero-buttons">
          <a
            href={`${window_SHOPINZEN_INTEGRATOR_object.getKey("dashboard_url")}/auth/login`}
            className="shopinzen-btn-hero-primary"
            target="_blank"
            rel="noopener noreferrer"
          >
            {intl.formatMessage({
              defaultMessage: "Démarrer l'essai gratuit",
              id: "YDSE04",
            })}
          </a>

          <a
            href={window_SHOPINZEN_INTEGRATOR_object.getKey(
              "dashboard_url",
            )}
            className="shopinzen-btn-hero-secondary"
            target="_blank"
            rel="noopener noreferrer"
          >
            {intl.formatMessage({
              defaultMessage: "Essayer la démo",
              id: "q2E2cb",
            })}
          </a>
        </div>
      </div>
    </div>
  );
};

// Composant Onglets
const Tabs = ({
  activeTab,
  onTabChange,
}: {
  activeTab: string;
  onTabChange: (tab: "register" | "api-key") => void;
}) => {
  const intl = useIntl();

  return (
    <div className="shopinzen-tabs">
      <button
        className={`shopinzen-tab ${activeTab === "register" ? "active" : ""}`}
        onClick={() => onTabChange("register")}
      >
        {intl.formatMessage({
          defaultMessage: "Créer un compte",
          id: "pXZVpi",
        })}
      </button>
      <button
        className={`shopinzen-tab ${activeTab === "api-key" ? "active" : ""}`}
        onClick={() => onTabChange("api-key")}
      >
        {intl.formatMessage({
          defaultMessage: "J'ai déjà un compte",
          id: "mc4CGv",
        })}
      </button>
    </div>
  );
};

// Onglet Inscription
const RegisterTab = ({
  showEmailVerification,
  setShowEmailVerification,
  userEmail,
  setUserEmail,
  setActiveTab,
}: any) => {
  const intl = useIntl();

  if (showEmailVerification) {
    return <EmailVerification email={userEmail} setActiveTab={setActiveTab} />;
  }

  return (
    <div className="shopinzen-tab-content active">
      <h2>
        {intl.formatMessage({
          defaultMessage: "Créer un compte ShopinZen",
          id: "/vl53g",
        })}
      </h2>
      <RegisterForm
        onSuccess={(email: string) => {
          setUserEmail(email);
          setShowEmailVerification(true);
        }}
      />
    </div>
  );
};

// Formulaire d'inscription COMPLET avec API
const RegisterForm = ({
  onSuccess,
}: {
  onSuccess: (email: string) => void;
}) => {
  const intl = useIntl(); // ← AJOUTER

  const [formData, setFormData] = useState({
    company: "",
    legal_form: "",
    first_name: "",
    last_name: "",
    url: typeof window !== "undefined" ? window.location.origin : "",
    activity_sector: "",
    email: "",
    phone: "",
    password: "",
    password_confirm: "",
  });

  const [passwordVisible, setPasswordVisible] = useState(false);
  const [confirmPasswordVisible, setConfirmPasswordVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [passwordValidation, setPasswordValidation] = useState({
    length: false,
    uppercase: false,
    lowercase: false,
    number: false,
    special: false,
  });

  // Validation mot de passe en temps réel
  const validatePassword = (password: string) => {
    setPasswordValidation({
      length: password.length >= 8,
      uppercase: /[A-Z]/.test(password),
      lowercase: /[a-z]/.test(password),
      number: /[0-9]/.test(password),
      special: /[!@#$%^&*(),.?":{}|<>]/.test(password),
    });
  };

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));

    if (name === "password") {
      validatePassword(value);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Vérifier que les mots de passe correspondent
    if (formData.password !== formData.password_confirm) {
      toast.error(
        intl.formatMessage({
          defaultMessage: "Les mots de passe ne correspondent pas",
          id: "AaK2rE",
        }),
      );
      return;
    }

    setIsLoading(true);
    showLoader();

    try {
      const registerData: RegisterData = {
        firstName: formData.first_name,
        lastName: formData.last_name,
        email: formData.email,
        company: formData.company,
        product: formData.legal_form,
        url: formData.url,
        country: "FR",
        password: formData.password,
        phone: formData.phone,
        phoneCode: "+33",
        lang: intl.locale, // ← Utilise la langue active
      };

      await register(registerData);

      hideLoader();
      setIsLoading(false);
      toast.success(
        intl.formatMessage({
          defaultMessage: "Compte créé avec succès ! Vérifiez votre email.",
          id: "z2Y6cQ",
        }),
      );
      onSuccess(formData.email);
    } catch (error: any) {
      hideLoader();
      setIsLoading(false);
      const errorMessage =
        error.response?.data?.message ||
        intl.formatMessage({
          defaultMessage: "Erreur lors de l'inscription",
          id: "yR5YrD",
        });
      toast.error(errorMessage);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div className="shopinzen-form-grid">
        {/* Nom de l'entreprise */}
        <div className="shopinzen-form-group">
          <label htmlFor="company">
            {intl.formatMessage({
              defaultMessage: "Nom de l'entreprise",
              id: "Jn5b+M",
            })}{" "}
            <span className="required">*</span>
          </label>
          <input
            type="text"
            id="company"
            name="company"
            value={formData.company}
            onChange={handleChange}
            disabled={isLoading}
            required
          />
        </div>

        {/* Forme juridique */}
        <div className="shopinzen-form-group">
          <label htmlFor="legal_form">
            {intl.formatMessage({
              defaultMessage: "Forme juridique",
              id: "yA5VCs",
            })}{" "}
            <span className="required">*</span>
          </label>
          <select
            id="legal_form"
            name="legal_form"
            value={formData.legal_form}
            onChange={handleChange}
            disabled={isLoading}
            required
            style={{ width: "100%" }}
          >
            <option value="">
              {intl.formatMessage({
                defaultMessage: "-- Sélectionner --",
                id: "9kMnwN",
              })}
            </option>
            <option value="SARL">SARL</option>
            <option value="SA">SA</option>
            <option value="SAS">SAS</option>
            <option value="EURL">EURL</option>
            <option value="SNC">SNC</option>
            <option value="Autre">
              {intl.formatMessage({ defaultMessage: "Autre", id: "1qF9e8" })}
            </option>
          </select>
        </div>

        {/* Prénom */}
        <div className="shopinzen-form-group">
          <label htmlFor="first_name">
            {intl.formatMessage({
              defaultMessage: "Votre prénom",
              id: "qSUgXl",
            })}{" "}
            <span className="required">*</span>
          </label>
          <input
            type="text"
            id="first_name"
            name="first_name"
            placeholder={intl.formatMessage({
              defaultMessage: "Votre prénom",
              id: "qSUgXl",
            })}
            value={formData.first_name}
            onChange={handleChange}
            disabled={isLoading}
            required
          />
        </div>

        {/* Nom */}
        <div className="shopinzen-form-group">
          <label htmlFor="last_name">
            {intl.formatMessage({ defaultMessage: "Votre nom", id: "KsDrkc" })}{" "}
            <span className="required">*</span>
          </label>
          <input
            type="text"
            id="last_name"
            name="last_name"
            placeholder={intl.formatMessage({
              defaultMessage: "Votre nom",
              id: "KsDrkc",
            })}
            value={formData.last_name}
            onChange={handleChange}
            disabled={isLoading}
            required
          />
        </div>

        {/* URL */}
        <div className="shopinzen-form-group">
          <label htmlFor="url">
            {intl.formatMessage({
              defaultMessage: "URL de votre site web",
              id: "UMsWYu",
            })}{" "}
            <span className="required">*</span>
          </label>
          <input
            type="url"
            id="url"
            name="url"
            placeholder="https://example.com"
            value={formData.url}
            onChange={handleChange}
            disabled={isLoading}
            required
          />
        </div>

        {/* Secteur d'activité */}
        <div className="shopinzen-form-group">
          <label htmlFor="activity_sector">
            {intl.formatMessage({
              defaultMessage: "Secteur d'activité",
              id: "aEHrsp",
            })}{" "}
            <span className="required">*</span>
          </label>
          <select
            id="activity_sector"
            name="activity_sector"
            value={formData.activity_sector}
            onChange={handleChange}
            disabled={isLoading}
            required
            style={{ width: "100%" }}
          >
            <option value="">
              {intl.formatMessage({
                defaultMessage: "-- Sélectionner --",
                id: "9kMnwN",
              })}
            </option>
            <option value="Activités juridiques et comptables">
              {intl.formatMessage({
                defaultMessage: "Activités juridiques et comptables",
                id: "/i7scH",
              })}
            </option>
            <option value="Agriculture et élevage">
              {intl.formatMessage({
                defaultMessage: "Agriculture et élevage",
                id: "ytlUIW",
              })}
            </option>
            <option value="Architecture, études et normes">
              {intl.formatMessage({
                defaultMessage: "Architecture, études et normes",
                id: "z979XZ",
              })}
            </option>
            <option value="Commerce et distribution">
              {intl.formatMessage({
                defaultMessage: "Commerce et distribution",
                id: "oLuijx",
              })}
            </option>
            <option value="Communication et marketing">
              {intl.formatMessage({
                defaultMessage: "Communication et marketing",
                id: "IJ5Z/7",
              })}
            </option>
            <option value="Finance, banque et assurance">
              {intl.formatMessage({
                defaultMessage: "Finance, banque et assurance",
                id: "eVrHPT",
              })}
            </option>
            <option value="Immobilier">
              {intl.formatMessage({
                defaultMessage: "Immobilier",
                id: "S7MSXY",
              })}
            </option>
            <option value="Informatique et télécommunication">
              {intl.formatMessage({
                defaultMessage: "Informatique et télécommunication",
                id: "INc6c1",
              })}
            </option>
            <option value="Santé">
              {intl.formatMessage({ defaultMessage: "Santé", id: "h4u8ls" })}
            </option>
            <option value="Tourisme">
              {intl.formatMessage({ defaultMessage: "Tourisme", id: "tJgNYF" })}
            </option>
            <option value="Autres">
              {intl.formatMessage({ defaultMessage: "Autres", id: "bc3RdV" })}
            </option>
          </select>
        </div>

        {/* Email */}
        <div className="shopinzen-form-group">
          <label htmlFor="email">
            {intl.formatMessage({ defaultMessage: "E-mail", id: "tkwCac" })}{" "}
            <span className="required">*</span>
          </label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            disabled={isLoading}
            required
          />
        </div>

        {/* Téléphone */}
        <div className="shopinzen-form-group">
          <label htmlFor="phone">
            {intl.formatMessage({ defaultMessage: "Téléphone", id: "RWxLzA" })}{" "}
            <span className="required">*</span>
          </label>
          <input
            type="tel"
            id="phone"
            name="phone"
            placeholder="+33 X XX XX XX XX"
            value={formData.phone}
            onChange={handleChange}
            disabled={isLoading}
            required
          />
        </div>

        {/* Mot de passe avec viewer */}
        <div className="shopinzen-form-group">
          <label htmlFor="password">
            {intl.formatMessage({
              defaultMessage: "Mot de passe",
              id: "ZVILrU",
            })}{" "}
            <span className="required">*</span>
          </label>
          <div className="shopinzen-password-wrapper">
            <input
              type={passwordVisible ? "text" : "password"}
              id="password"
              name="password"
              value={formData.password}
              onChange={handleChange}
              disabled={isLoading}
              required
            />
            <button
              type="button"
              className="shopinzen-toggle-password"
              onClick={() => setPasswordVisible(!passwordVisible)}
              disabled={isLoading}
            >
              {passwordVisible ? "🙈" : "👁️"}
            </button>
          </div>
          <ul className="shopinzen-password-requirements">
            <li className={passwordValidation.length ? "valid" : ""}>
              {intl.formatMessage({
                defaultMessage: "Au moins 8 caractères",
                id: "ztCLpL",
              })}
            </li>
            <li className={passwordValidation.uppercase ? "valid" : ""}>
              {intl.formatMessage({
                defaultMessage: "Au moins une lettre majuscule",
                id: "rDDCz/",
              })}
            </li>
            <li className={passwordValidation.lowercase ? "valid" : ""}>
              {intl.formatMessage({
                defaultMessage: "Au moins une lettre minuscule",
                id: "w5HjDs",
              })}
            </li>
            <li className={passwordValidation.number ? "valid" : ""}>
              {intl.formatMessage({
                defaultMessage: "Au moins un chiffre",
                id: "cwswVY",
              })}
            </li>
            <li className={passwordValidation.special ? "valid" : ""}>
              {intl.formatMessage({
                defaultMessage: "Au moins un caractère spécial",
                id: "FjmNcD",
              })}
            </li>
          </ul>
        </div>

        {/* Confirmer mot de passe avec viewer */}
        <div className="shopinzen-form-group">
          <label htmlFor="password_confirm">
            {intl.formatMessage({
              defaultMessage: "Confirmer le mot de passe",
              id: "lJVoKg",
            })}{" "}
            <span className="required">*</span>
          </label>
          <div className="shopinzen-password-wrapper">
            <input
              type={confirmPasswordVisible ? "text" : "password"}
              id="password_confirm"
              name="password_confirm"
              value={formData.password_confirm}
              onChange={handleChange}
              disabled={isLoading}
              required
            />
            <button
              type="button"
              className="shopinzen-toggle-password"
              onClick={() => setConfirmPasswordVisible(!confirmPasswordVisible)}
              disabled={isLoading}
            >
              {confirmPasswordVisible ? "🙈" : "👁️"}
            </button>
          </div>
        </div>
      </div>

      <button
        type="submit"
        className="shopinzen-btn-primary"
        disabled={isLoading}
      >
        {isLoading
          ? intl.formatMessage({
              defaultMessage: "Inscription en cours...",
              id: "9/zxBy",
            })
          : intl.formatMessage({ defaultMessage: "S'inscrire", id: "wzNBlT" })}
      </button>
    </form>
  );
};

// Verification email complet
const EmailVerification = ({
  email,
  setActiveTab,
}: {
  email: string;
  setActiveTab: (tab: "register" | "api-key") => void;
}) => {
  const intl = useIntl(); // ← AJOUTER

  const [code, setCode] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [isResending, setIsResending] = useState(false);

  const handleVerify = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!code) {
      toast.error(
        intl.formatMessage({
          defaultMessage: "Veuillez saisir le code de vérification",
          id: "Ah/zDq",
        }),
      );
      return;
    }

    setIsLoading(true);
    showLoader();

    try {
      await verifyEmail({ email, code });
      hideLoader();
      setIsLoading(false);
      toast.success(
        intl.formatMessage({
          defaultMessage:
            "Email vérifié avec succès ! Connectez-vous au dashboard pour récupérer votre clé API.",
          id: "9L0aAl",
        }),
      );

      // Basculer sur l'onglet "J'ai déjà un compte"
      setActiveTab("api-key");

      // Ouvrir le dashboard après 2 secondes
      setTimeout(() => {
        window.open(
          `${window_SHOPINZEN_INTEGRATOR_object.getKey("dashboard_url")}/auth/login`,
          "_blank",
        );
      }, 2000);
    } catch (error: any) {
      hideLoader();
      setIsLoading(false);
      const errorMessage =
        error.response?.data?.message ||
        intl.formatMessage({
          defaultMessage: "Code de vérification invalide",
          id: "YMKjHR",
        });
      toast.error(errorMessage);
    }
  };

  const handleResend = async () => {
    setIsResending(true);
    showLoader();

    try {
      await resendCode(email);
      hideLoader();
      setIsResending(false);
      toast.success(
        intl.formatMessage({
          defaultMessage: "Code renvoyé avec succès !",
          id: "HEkjO7",
        }),
      );
    } catch (error: any) {
      hideLoader();
      setIsResending(false);
      const errorMessage =
        error.response?.data?.message ||
        intl.formatMessage({
          defaultMessage: "Erreur lors de l'envoi du code",
          id: "FnnMhS",
        });
      toast.error(errorMessage);
    }
  };

  return (
    <div className="shopinzen-tab-content active">
      <h2>
        {intl.formatMessage({
          defaultMessage: "Vérification de votre email",
          id: "948Lr/",
        })}
      </h2>
      <p>
        {intl.formatMessage({
          defaultMessage: "Un code de vérification a été envoyé à",
          id: "ILvLhS",
        })}{" "}
        <strong>{email}</strong>
      </p>

      <form onSubmit={handleVerify}>
        <div className="shopinzen-form-group">
          <label htmlFor="verification_code">
            {intl.formatMessage({
              defaultMessage: "Code de vérification",
              id: "AESjLs",
            })}
          </label>
          <input
            type="text"
            id="verification_code"
            name="verification_code"
            value={code}
            onChange={(e) => setCode(e.target.value)}
            disabled={isLoading}
            required
          />
        </div>
        <div
          style={{ display: "flex", gap: "10px", justifyContent: "flex-end" }}
        >
          <button
            type="button"
            className="shopinzen-btn-secondary"
            onClick={handleResend}
            disabled={isResending}
          >
            {isResending
              ? intl.formatMessage({ defaultMessage: "Envoi...", id: "CVO54+" })
              : intl.formatMessage({
                  defaultMessage: "Renvoyer le code",
                  id: "U9P0o3",
                })}
          </button>
          <button
            type="submit"
            className="shopinzen-btn-primary"
            disabled={isLoading}
          >
            {isLoading
              ? intl.formatMessage({
                  defaultMessage: "Vérification...",
                  id: "IhD+Yx",
                })
              : intl.formatMessage({
                  defaultMessage: "Vérifier",
                  id: "OGPg5Z",
                })}
          </button>
        </div>
      </form>
    </div>
  );
};

// Onglet clé API (à compléter à l'étape suivante)
const ApiKeyTab = () => {
  const intl = useIntl(); // ← AJOUTER

  const [apiKey, setApiKey] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!apiKey.trim()) {
      toast.error(
        intl.formatMessage({
          defaultMessage: "Veuillez saisir une clé API",
          id: "/Y7UOU",
        }),
      );
      return;
    }

    setIsLoading(true);
    showLoader();

    try {
      // 1. Récupérer les données du bot
      const botData = await getBotByApiKey(apiKey);

      // 2. Enregistrer la config dans WordPress
      await saveConfig({
        public_key: apiKey,
        user: {},
        chatbot: botData.data,
      });

      hideLoader();
      setIsLoading(false);
      toast.success(
        intl.formatMessage({
          defaultMessage: "Configuration enregistrée ! Rechargement...",
          id: "/GhWqK",
        }),
      );

      setTimeout(() => {
        // Chemin relatif - fonctionne partout
        const currentPath = window.location.pathname.split("/wp-admin/")[0];
        window.location.href =
          currentPath +
          "/wp-admin/admin.php?page=shopinzen-integrator-home";
      }, 1000);
    } catch (error: any) {
      hideLoader();
      setIsLoading(false);
      const errorMessage =
        error.response?.status === 401
          ? intl.formatMessage({
              defaultMessage: "Clé API invalide ou expirée",
              id: "IzFpBU",
            })
          : error.response?.data?.message ||
            intl.formatMessage({
              defaultMessage: "Erreur lors de l'enregistrement",
              id: "VlzhWF",
            });
      toast.error(errorMessage);
    }
  };

  return (
    <div className="shopinzen-tab-content active">
      <h2>
        {intl.formatMessage({
          defaultMessage: "Connecter avec une clé API",
          id: "LcA/8q",
        })}
      </h2>
      <p>
        {intl.formatMessage({
          defaultMessage:
            "Si vous avez déjà un compte ShopinZen, collez votre clé API ci-dessous.",
          id: "T/eP2s",
        })}
      </p>

      <form onSubmit={handleSubmit}>
        <div className="shopinzen-form-group">
          <label htmlFor="api_key">
            {intl.formatMessage({
              defaultMessage: "Clé API",
              id: "WRfH2E",
            })}
          </label>
          <input
            type="text"
            id="api_key"
            name="api_key"
            placeholder={intl.formatMessage({
              defaultMessage: "Collez votre clé API ici",
              id: "g0Pv0O",
            })}
            value={apiKey}
            onChange={(e) => setApiKey(e.target.value)}
            disabled={isLoading}
            required
          />
        </div>
        <button
          type="submit"
          className="shopinzen-btn-primary"
          disabled={isLoading}
        >
          {isLoading
            ? intl.formatMessage({
                defaultMessage: "Validation...",
                id: "rC2pQe",
              })
            : intl.formatMessage({
                defaultMessage: "Valider la clé",
                id: "RJkTlH",
              })}
        </button>
      </form>
    </div>
  );
};

// Loader
const Loader = () => {
  return (
    <div className="shopinzen-loader" id="shopinzen-loader">
      <div className="shopinzen-spinner"></div>
    </div>
  );
};

export default App;
