"use client";

import Link from "next/link";
import { useState, useCallback, useEffect } from "react";
import { useTranslation } from "@/hooks/useTranslation";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { registerUser, clearError } from "@/store/slices/authSlice";
import { registerSchema } from "@/lib/validators/auth.validator";
import { isAuthenticatedClient } from "@/lib/utils/persistAuth";
import { useLocale } from "@/hooks/useLocale";

const STRENGTH_COLORS = ["", "#ef4444", "#f97316", "#eab308", "#22c55e"];

function getStrength(pw: string): number {
  if (!pw) return 0;
  let s = 0;
  if (pw.length >= 8) s++;
  if (/[A-Z]/.test(pw)) s++;
  if (/[0-9]/.test(pw)) s++;
  if (/[^A-Za-z0-9]/.test(pw)) s++;
  return s;
}

const COUNTRY_MAP: Record<string, string> = {
  "+91": "India",
  "+1": "United States",
  "+44": "United Kingdom",
  "+971": "UAE",
};

export default function SignupPage() {
  const { locale } = useLocale();
  const { t } = useTranslation("auth");
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { isLoading, error } = useAppSelector((s) => s.auth);

  const [showPw, setShowPw] = useState(false);
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [phone, setPhone] = useState("");
  const [countryCode, setCountryCode] = useState("+91");
  const [emailValid, setEmailValid] = useState(false);
  const [selectedInterests, setSelectedInterests] = useState<Set<string>>(
    new Set(["politics", "world", "tech"]),
  );
  const [newsletterDaily, setNewsletterDaily] = useState(true);
  const [newsletterWeekly, setNewsletterWeekly] = useState(false);
  const [termsAccepted, setTermsAccepted] = useState(false);
  const [validationError, setValidationError] = useState<string | null>(null);

  // Redirect if already logged in
  useEffect(() => {
    if (isAuthenticatedClient()) {
      router.replace(`/home`);
    }
  }, [locale, router]);

  // Clear Redux error when user edits any field
  useEffect(() => {
    if (error) dispatch(clearError());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [firstName, lastName, email, password, phone]);

  const strength = getStrength(password);

  const toggleInterest = useCallback((key: string) => {
    setSelectedInterests((prev) => {
      const next = new Set(prev);
      if (next.has(key)) {
        next.delete(key);
      } else {
        next.add(key);
      }
      return next;
    });
  }, []);

  const strengthLabels = [
    "",
    t("signup.strength_weak"),
    t("signup.strength_fair"),
    t("signup.strength_good"),
    t("signup.strength_strong"),
  ];

  const interests = [
    { key: "politics", label: t("signup.interest_politics") },
    { key: "world", label: t("signup.interest_world") },
    { key: "tech", label: t("signup.interest_tech") },
    { key: "sports", label: t("signup.interest_sports") },
    { key: "business", label: t("signup.interest_business") },
    { key: "science", label: t("signup.interest_science") },
    { key: "culture", label: t("signup.interest_culture") },
    { key: "cities", label: t("signup.interest_cities") },
    { key: "health", label: t("signup.interest_health") },
    { key: "markets", label: t("signup.interest_markets") },
    { key: "environment", label: t("signup.interest_environment") },
  ];

  const reqMet = {
    length: password.length >= 8,
    upper: /[A-Z]/.test(password),
    number: /[0-9]/.test(password),
    special: /[^A-Za-z0-9]/.test(password),
  };

  const handleSubmit = useCallback(
    async (e: React.SyntheticEvent) => {
      e.preventDefault();
      setValidationError(null);

      const full_name = `${firstName} ${lastName}`.trim();
      const parsed = registerSchema.safeParse({
        full_name,
        email,
        password,
        mobile_number: phone,
        country_code: countryCode,
        country_name: COUNTRY_MAP[countryCode] ?? countryCode,
      });

      if (!parsed.success) {
        setValidationError(parsed.error.issues[0].message);
        return;
      }

      const result = await dispatch(
        registerUser({
          full_name,
          email,
          password,
          mobile_number: phone,
          country_code: countryCode,
          country_name: COUNTRY_MAP[countryCode] ?? countryCode,
          device_type: 3,
          device_token: "",
        }),
      );

      if (registerUser.fulfilled.match(result)) {
        router.push(`/home`);
      }
    },
    [
      firstName,
      lastName,
      email,
      password,
      phone,
      countryCode,
      dispatch,
      locale,
      router,
    ],
  );

  const displayError = validationError ?? error;

  return (
    <main className="auth-shell">
      {/* ── Editorial art panel ── */}
      <aside className="auth-art">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src="https://images.unsplash.com/photo-1495020689067-958852a7765e?w=1600&q=80"
          alt="DTNews newsroom"
        />
        <div className="art-inner">
          <div className="top">
            <span className="badge-tag">FREE ACCOUNT</span>
            <span className="credit">Photo · Karthik Iyer / DTNews</span>
          </div>
          <div>
            <div className="kicker">The Daily Briefing</div>
            <blockquote className="quote">
              Six stories, one number, one chart. No fluff. From our newsroom to
              your inbox at 7 AM.
            </blockquote>
            <div className="byline">
              <span className="av">RK</span>
              <div className="meta">
                <b>Ravish Kumar &amp; Rohan Kapoor</b>
                <span className="role">
                  Editing the Daily Briefing · 1.8M readers
                </span>
              </div>
            </div>
            <div className="stats">
              <div className="stat">
                <div className="n">7 AM</div>
                <div className="l">Daily</div>
              </div>
              <div className="stat">
                <div className="n">5 min</div>
                <div className="l">Read time</div>
              </div>
              <div className="stat">
                <div className="n">1-click</div>
                <div className="l">Unsubscribe</div>
              </div>
              <div className="stat">
                <div className="n">₹0</div>
                <div className="l">Always free</div>
              </div>
            </div>
          </div>
        </div>
      </aside>

      {/* ── Form panel ── */}
      <section className="auth-form-side">
        <div className="auth-form">
          <Link href={`/home`} className="auth-mini-logo">
            <span className="dt">DT</span>
            <span className="news">News</span>
            <span className="dot" />
          </Link>

          <div className="auth-step-meta">{t("signup.step_meta")}</div>
          <div className="auth-steps">
            <div className="step active" />
            <div className="step" />
            <div className="step" />
          </div>

          <div className="auth-eyebrow">{t("signup.eyebrow")}</div>
          <h1 className="auth-h1">
            {t("signup.h1_prefix")} <em>{t("signup.h1_em")}</em>
          </h1>
          <p className="auth-sub">
            {t("signup.sub_signin")}{" "}
            <Link href={`/login`}>{t("signup.sub_signin_link")}</Link>{" "}
            {t("signup.sub_subscriber")}
          </p>

          {/* Social SSO */}
          <div className="auth-social-row">
            <button className="auth-social-btn" type="button">
              <svg viewBox="0 0 24 24">
                <path
                  fill="#4285F4"
                  d="M22 12.1c0-.7-.1-1.4-.2-2H12v3.8h5.6c-.2 1.3-1 2.4-2.1 3.2v2.6h3.4c2-1.8 3.1-4.5 3.1-7.6z"
                />
                <path
                  fill="#34A853"
                  d="M12 22c2.7 0 5-.9 6.7-2.4l-3.4-2.6c-.9.6-2 1-3.3 1-2.5 0-4.7-1.7-5.5-4H3v2.6C4.7 19.7 8 22 12 22z"
                />
                <path
                  fill="#FBBC05"
                  d="M6.5 14c-.2-.6-.3-1.3-.3-2s.1-1.4.3-2V7.3H3C2.4 8.7 2 10.3 2 12s.4 3.3 1 4.7L6.5 14z"
                />
                <path
                  fill="#EA4335"
                  d="M12 6c1.4 0 2.7.5 3.7 1.4l2.8-2.8C16.9 3.1 14.7 2 12 2 8 2 4.7 4.3 3 7.3L6.5 10c.8-2.3 3-4 5.5-4z"
                />
              </svg>
              {t("signup.google")}
            </button>
            <button className="auth-social-btn" type="button">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M17.5 12.5a4.5 4.5 0 0 1 2.2-3.8 4.6 4.6 0 0 0-3.6-2c-1.5-.2-3 .9-3.8.9-.8 0-2-.9-3.3-.9A4.8 4.8 0 0 0 5 9c-1.7 3-.4 7.4 1.2 9.8.8 1.2 1.7 2.5 3 2.5s1.7-.8 3.3-.8 2 .8 3.3.8 2.3-1.2 3.1-2.4a10 10 0 0 0 1.4-2.9 4.4 4.4 0 0 1-2.8-3.5zM15 5.4A4.5 4.5 0 0 0 16 2a4.5 4.5 0 0 0-3 1.5 4.2 4.2 0 0 0-1 3.3 3.7 3.7 0 0 0 3-1.4z" />
              </svg>
              {t("signup.apple")}
            </button>
            <button className="auth-social-btn" type="button">
              <svg viewBox="0 0 24 24" fill="#1877F2">
                <path d="M22 12c0-5.5-4.5-10-10-10S2 6.5 2 12c0 5 3.7 9.1 8.4 9.9V15h-2.5v-3h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.4 3h-2.3v6.9C18.3 21.1 22 17 22 12z" />
              </svg>
              {t("signup.facebook")}
            </button>
          </div>

          <div className="auth-divider">
            <span className="ln" />
            <span>{t("signup.or")}</span>
            <span className="ln" />
          </div>

          <form onSubmit={handleSubmit}>
            {/* Name fields */}
            <div className="fgrid">
              <div className="auth-field">
                <div className="auth-field-label">
                  <span>
                    {t("signup.first_name")}{" "}
                    <span className="req" style={{ color: "var(--brand)" }}>
                      *
                    </span>
                  </span>
                </div>
                <div className="auth-field-wrap">
                  <span className="auth-field-ico">
                    <svg viewBox="0 0 24 24">
                      <circle cx="12" cy="8" r="4" />
                      <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7" />
                    </svg>
                  </span>
                  <input
                    type="text"
                    placeholder={t("signup.first_name_placeholder")}
                    autoComplete="given-name"
                    required
                    value={firstName}
                    onChange={(e) => setFirstName(e.target.value)}
                  />
                </div>
              </div>
              <div className="auth-field">
                <div className="auth-field-label">
                  <span>
                    {t("signup.last_name")}{" "}
                    <span className="req" style={{ color: "var(--brand)" }}>
                      *
                    </span>
                  </span>
                </div>
                <div className="auth-field-wrap">
                  <span className="auth-field-ico">
                    <svg viewBox="0 0 24 24">
                      <circle cx="12" cy="8" r="4" />
                      <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7" />
                    </svg>
                  </span>
                  <input
                    type="text"
                    placeholder={t("signup.last_name_placeholder")}
                    autoComplete="family-name"
                    required
                    value={lastName}
                    onChange={(e) => setLastName(e.target.value)}
                  />
                </div>
              </div>
            </div>

            {/* Email */}
            <div className="auth-field">
              <div className="auth-field-label">
                <span>
                  {t("signup.email")}{" "}
                  <span className="req" style={{ color: "var(--brand)" }}>
                    *
                  </span>
                </span>
                {emailValid && (
                  <span
                    style={{
                      color: "#22c55e",
                      fontSize: "11.5px",
                      display: "inline-flex",
                      alignItems: "center",
                      gap: "4px",
                    }}
                  >
                    ✓ {t("signup.email_valid")}
                  </span>
                )}
              </div>
              <div className="auth-field-wrap">
                <span className="auth-field-ico">
                  <svg viewBox="0 0 24 24">
                    <rect x="3" y="5" width="18" height="14" rx="2" />
                    <path d="M3 7l9 7 9-7" />
                  </svg>
                </span>
                <input
                  type="email"
                  placeholder={t("signup.email_placeholder")}
                  autoComplete="email"
                  required
                  value={email}
                  style={
                    emailValid
                      ? {
                          borderColor: "#22c55e",
                          boxShadow: "0 0 0 4px rgba(34,197,94,0.10)",
                        }
                      : undefined
                  }
                  onChange={(e) => {
                    setEmail(e.target.value);
                    setEmailValid(
                      /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.target.value),
                    );
                  }}
                />
              </div>
            </div>

            {/* Phone */}
            <div className="auth-field">
              <div className="auth-field-label">
                <span>
                  {t("signup.phone")}{" "}
                  <span style={{ color: "var(--text-3)", fontWeight: 400 }}>
                    {t("signup.phone_optional")}
                  </span>
                </span>
              </div>
              <div className="phone-row">
                <select
                  aria-label="Country code"
                  value={countryCode}
                  onChange={(e) => setCountryCode(e.target.value)}
                >
                  <option value="+91">🇮🇳 +91</option>
                  <option value="+1">🇺🇸 +1</option>
                  <option value="+44">🇬🇧 +44</option>
                  <option value="+971">🇦🇪 +971</option>
                </select>
                <div className="auth-field-wrap">
                  <input
                    type="tel"
                    placeholder={t("signup.phone_placeholder")}
                    autoComplete="tel"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                  />
                </div>
              </div>
            </div>

            {/* Password */}
            <div className="auth-field">
              <div className="auth-field-label">
                <span>
                  {t("signup.password")}{" "}
                  <span className="req" style={{ color: "var(--brand)" }}>
                    *
                  </span>
                </span>
                {password && (
                  <span
                    style={{
                      fontSize: "11.5px",
                      color: STRENGTH_COLORS[strength],
                    }}
                  >
                    {strengthLabels[strength]}
                  </span>
                )}
              </div>
              <div className="auth-field-wrap auth-no-pad-right">
                <span className="auth-field-ico">
                  <svg viewBox="0 0 24 24">
                    <rect x="5" y="11" width="14" height="10" rx="2" />
                    <path d="M8 11V7a4 4 0 0 1 8 0v4" />
                  </svg>
                </span>
                <input
                  type={showPw ? "text" : "password"}
                  placeholder={t("signup.password_placeholder")}
                  autoComplete="new-password"
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
                <button
                  type="button"
                  className="auth-field-eye"
                  aria-label="Toggle password visibility"
                  onClick={() => setShowPw((v) => !v)}
                >
                  {showPw ? (
                    <svg
                      width="18"
                      height="18"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
                      <line x1="1" y1="1" x2="23" y2="23" />
                    </svg>
                  ) : (
                    <svg
                      width="18"
                      height="18"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <circle cx="12" cy="12" r="3" />
                      <path d="M2 12s4-8 10-8 10 8 10 8-4 8-10 8S2 12 2 12z" />
                    </svg>
                  )}
                </button>
              </div>
              {password && (
                <>
                  <div className="auth-strength">
                    {[1, 2, 3, 4].map((i) => (
                      <div
                        key={i}
                        className={`sbar${i <= strength ? ` s${strength}` : ""}`}
                      />
                    ))}
                  </div>
                  <ul className="auth-req-list">
                    <li className={reqMet.length ? "ok" : ""}>
                      {t("signup.req_length")}
                    </li>
                    <li className={reqMet.upper ? "ok" : ""}>
                      {t("signup.req_upper")}
                    </li>
                    <li className={reqMet.number ? "ok" : ""}>
                      {t("signup.req_number")}
                    </li>
                    <li className={reqMet.special ? "ok" : ""}>
                      {t("signup.req_special")}
                    </li>
                  </ul>
                </>
              )}
            </div>

            {/* Interests */}
            <div className="auth-interests-header">
              <span className="label">{t("signup.interests_label")}</span>
              <span className="sub">{t("signup.interests_sub")}</span>
            </div>
            <div className="interest-grid">
              {interests.map(({ key, label }) => (
                <button
                  key={key}
                  type="button"
                  className={`interest-chip${selectedInterests.has(key) ? " active" : ""}`}
                  onClick={() => toggleInterest(key)}
                >
                  {label}
                </button>
              ))}
            </div>

            {/* Newsletters */}
            <div className="auth-newsletter">
              <div className="auth-newsletter-title">
                {t("signup.newsletter_title")}
              </div>
              <label className="auth-check">
                <input
                  type="checkbox"
                  className="auth-check-box"
                  checked={newsletterDaily}
                  onChange={(e) => setNewsletterDaily(e.target.checked)}
                />
                <span>{t("signup.newsletter_daily")}</span>
              </label>
              <label className="auth-check">
                <input
                  type="checkbox"
                  className="auth-check-box"
                  checked={newsletterWeekly}
                  onChange={(e) => setNewsletterWeekly(e.target.checked)}
                />
                <span>{t("signup.newsletter_weekly")}</span>
              </label>
            </div>

            {/* Terms */}
            <div style={{ marginBottom: "24px" }}>
              <label className="auth-check">
                <input
                  type="checkbox"
                  className="auth-check-box"
                  checked={termsAccepted}
                  onChange={(e) => setTermsAccepted(e.target.checked)}
                  required
                />
                <span>
                  {t("signup.terms_prefix")}{" "}
                  <a href="#" className="auth-link-r">
                    {t("signup.terms_of_service")}
                  </a>{" "}
                  {t("signup.terms_and")}{" "}
                  <a href="#" className="auth-link-r">
                    {t("signup.privacy_policy")}
                  </a>
                </span>
              </label>
            </div>

            {displayError && (
              <p
                style={{
                  color: "var(--brand)",
                  fontSize: "13px",
                  marginBottom: "12px",
                  fontWeight: 500,
                }}
              >
                {displayError}
              </p>
            )}

            <button
              type="submit"
              className="auth-btn-primary"
              disabled={isLoading}
            >
              {isLoading ? "Creating account…" : t("signup.submit")}
              {!isLoading && (
                <svg viewBox="0 0 24 24">
                  <path d="M5 12h14M13 6l6 6-6 6" />
                </svg>
              )}
            </button>

            <div className="auth-foot-link">
              {t("signup.have_account")}{" "}
              <Link href={`/login`}>{t("signup.login_link_cta")}</Link>
            </div>

            <div className="trust-strip">
              <span className="item">
                <svg viewBox="0 0 24 24">
                  <rect x="5" y="11" width="14" height="10" rx="2" />
                  <path d="M8 11V7a4 4 0 0 1 8 0v4" />
                </svg>
                {t("signup.trust_no_card")}
              </span>
              <span className="item">
                <svg viewBox="0 0 24 24">
                  <circle cx="12" cy="12" r="9" />
                  <path d="M9 12l2 2 4-4" />
                </svg>
                {t("signup.trust_unsubscribe")}
              </span>
              <span className="item">
                <svg viewBox="0 0 24 24">
                  <path d="M12 2L4 5v7c0 5 4 9 8 10 4-1 8-5 8-10V5z" />
                  <path d="M9 12l2 2 4-4" />
                </svg>
                {t("signup.trust_no_sell")}
              </span>
            </div>

            <p className="auth-policy">
              {t("signup.policy_note")}{" "}
              <a href="#">{t("signup.policy_terms")}</a>{" "}
              {t("signup.policy_and")}{" "}
              <a href="#">{t("signup.policy_privacy")}</a>
              {t("signup.policy_suffix")}
            </p>
          </form>
        </div>
      </section>
    </main>
  );
}
