import React, { useEffect, useRef, useState } from "react";
import { useApp } from "../context/AppContext";
import { errorMessage } from "../api/client";

// Field wording follows how the portal is set to log customers in.
const LOGIN_FIELDS = {
    // User ID (the client's userid) and password, as the Blade login.
    default: {
        idLabel: "User ID", idPlaceholder: "Enter your user ID", idMode: "text", idName: "user ID",
        pwLabel: "Password", pwPlaceholder: "Enter your password", pwName: "password", isMobile: false,
    },
    // customer-login-by-cid-mobileNumber: CID and the mobile number on record, no password.
    cid_mobile: {
        idLabel: "Customer ID (CID)", idPlaceholder: "Enter your CID (e.g. 57344)", idMode: "numeric", idName: "CID",
        pwLabel: "Mobile number", pwPlaceholder: "Registered mobile number (e.g. 01711000000)", pwName: "mobile number", isMobile: true,
    },
    // login_customer_code_and_password
    customer_code: {
        idLabel: "Customer code", idPlaceholder: "Enter your customer code", idMode: "text", idName: "customer code",
        pwLabel: "Password", pwPlaceholder: "Enter your password", pwName: "password", isMobile: false,
    },
};

const EYE = (
    <>
        <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
        <circle cx="12" cy="12" r="3" />
    </>
);
const EYE_OFF = (
    <>
        <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.94" />
        <path d="M9.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.19" />
        <line x1="1" y1="1" x2="23" y2="23" />
    </>
);

export default function Login() {
    const { config, login } = useApp();
    const company = (config && config.company) || {};
    const links = (config && config.links) || {};
    const fields = LOGIN_FIELDS[(config && config.login_mode) || "default"] || LOGIN_FIELDS.default;

    const [cid, setCid] = useState("");
    const [password, setPassword] = useState("");
    const [remember, setRemember] = useState(false);
    const [showPw, setShowPw] = useState(false);
    const [busy, setBusy] = useState(false);
    const [logoFailed, setLogoFailed] = useState(!company.logo);
    const [toast, setToast] = useState({ text: "Done", show: false });
    const toastTimer = useRef(null);

    useEffect(() => setLogoFailed(!company.logo), [company.logo]);
    useEffect(() => () => clearTimeout(toastTimer.current), []);

    const showToast = (text) => {
        setToast({ text, show: true });
        clearTimeout(toastTimer.current);
        toastTimer.current = setTimeout(() => setToast((s) => ({ ...s, show: false })), 2400);
    };

    const onSubmit = async (e) => {
        e.preventDefault();
        const id = cid.trim();
        const pw = password.trim();

        if (!id) { showToast(`Please enter your ${fields.idName}`); return; }
        if (fields.idMode === "numeric" && !/^\d+$/.test(id)) { showToast("CID must be a number"); return; }
        if (!pw) { showToast(`Please enter your ${fields.pwName}`); return; }
        if (busy) return;

        setBusy(true);
        showToast("Logging in...");
        try {
            await login(id, pw, remember);
            window.location.hash = "#/dashboard";
        } catch (error) {
            setBusy(false);
            showToast(errorMessage(error) || "Could not log in. Please try again.");
        }
    };

    const openLink = (url, fallback) => (e) => {
        if (!url) {
            e.preventDefault();
            showToast(fallback);
        }
    };

    return (
        <div className="cn-login">
            {/* ============ SUBTLE BACKGROUND DECOR ============ */}
            <div className="bg-decor">
                <div className="blob blob-1"></div>
                <div className="blob blob-2"></div>
                <div className="blob blob-3"></div>
                <div className="blob blob-4"></div>
            </div>

            {/* ============ PAGE ============ */}
            <div className="page">
                <div className="card">

                    {/* Logo */}
                    <div className="logo-wrap">
                        <div className="logo-ring">
                            {!logoFailed && (
                                <img src={company.logo} alt={company.name} className="logo-img" onError={() => setLogoFailed(true)} />
                            )}
                            <div className="logo-fallback" style={logoFailed ? { display: "grid" } : undefined}>
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                    <path d="M5 12.55a11 11 0 0 1 14.08 0" />
                                    <path d="M1.42 9a16 16 0 0 1 21.16 0" />
                                    <path d="M8.53 16.11a6 6 0 0 1 6.95 0" />
                                    <line x1="12" y1="20" x2="12.01" y2="20" />
                                </svg>
                            </div>
                        </div>
                        <div className="brand-name">{company.name}</div>
                        <div className="brand-sub">Self&nbsp;Care</div>
                    </div>

                    {/* Welcome */}
                    <div className="welcome">
                        <h1>Welcome back</h1>
                        <p>Sign in to manage your connection</p>
                    </div>

                    {/* Form */}
                    <form id="loginForm" autoComplete="off" noValidate onSubmit={onSubmit}>
                        <div className="field">
                            <label htmlFor="cid">{fields.idLabel}</label>
                            <div className="input-wrap">
                                <span className="input-icon">
                                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                        <rect x="2" y="5" width="20" height="14" rx="2" />
                                        <line x1="2" y1="10" x2="22" y2="10" />
                                    </svg>
                                </span>
                                <input id="cid" name="cid" type="text" inputMode={fields.idMode} placeholder={fields.idPlaceholder}
                                    required value={cid} onChange={(e) => setCid(e.target.value)} autoComplete="username" />
                            </div>
                        </div>

                        <div className="field">
                            <label htmlFor="password">{fields.pwLabel}</label>
                            <div className="input-wrap">
                                <span className="input-icon">
                                    {fields.isMobile ? (
                                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                            <rect x="5" y="2" width="14" height="20" rx="2" ry="2" />
                                            <line x1="12" y1="18" x2="12.01" y2="18" />
                                        </svg>
                                    ) : (
                                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                            <rect x="3" y="11" width="18" height="11" rx="2" />
                                            <path d="M7 11V7a5 5 0 0 1 10 0v4" />
                                        </svg>
                                    )}
                                </span>
                                {fields.isMobile ? (
                                    <input id="password" name="mobile" type="tel" inputMode="tel" placeholder={fields.pwPlaceholder}
                                        required value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="tel" />
                                ) : (
                                    <>
                                        <input id="password" name="password" type={showPw ? "text" : "password"} placeholder={fields.pwPlaceholder}
                                            required value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" />
                                        <button type="button" className="pw-toggle" aria-label={showPw ? "Hide password" : "Show password"} onClick={() => setShowPw((v) => !v)}>
                                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                                {showPw ? EYE_OFF : EYE}
                                            </svg>
                                        </button>
                                    </>
                                )}
                            </div>
                        </div>

                        <div className="row-between">
                            <label className="remember">
                                <input type="checkbox" id="remember" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
                                <span>Remember me</span>
                            </label>
                            {/* No password to forget when logging in by mobile number. */}
                            {!fields.isMobile && (
                                <a href={links.forgot_password || "#"} className="forgot"
                                    onClick={openLink(links.forgot_password, `To reset your password, call ${company.phone || "support"}`)}>Forgot password?</a>
                            )}
                        </div>

                        <button type="submit" className="btn-login" disabled={busy}>
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                                <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" />
                                <polyline points="10 17 15 12 10 7" />
                                <line x1="15" y1="12" x2="3" y2="12" />
                            </svg>
                            <span>Login</span>
                        </button>
                    </form>

                    <div className="divider">or</div>

                    <a href={links.new_connection || "#"} className="btn-secondary" onClick={openLink(links.new_connection, "Please contact support for a new connection")}>
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
                            <circle cx="9" cy="7" r="4" />
                            <line x1="19" y1="8" x2="19" y2="14" />
                            <line x1="22" y1="11" x2="16" y2="11" />
                        </svg>
                        <span>Register for new connection</span>
                    </a>

                    <a href={links.quick_payment || "#"} className="btn-secondary quick" onClick={openLink(links.quick_payment, "Quick payment is not available")}>
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z" />
                        </svg>
                        <span>Quick Payment</span>
                    </a>

                    <div className="footer-links">
                        <span>New here?</span>
                        <a href={company.phone ? `tel:${company.phone}` : "#"} onClick={(e) => { e.preventDefault(); showToast(`Contact support: ${company.phone || company.email || ""}`); }}>Contact support</a>
                    </div>

                </div>
            </div>

            {/* ============ SITE FOOTER ============ */}
            <footer className="site-footer">
                <div className="site-footer__inner">
                    <div className="site-footer__contacts">
                        {company.phone && (
                            <a href={`tel:${company.phone}`}>
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                    <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" />
                                </svg>
                                <span>Helpline: {company.phone}</span>
                            </a>
                        )}
                        {company.email && (
                            <a href={`mailto:${company.email}`}>
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                    <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
                                    <polyline points="22,6 12,13 2,6" />
                                </svg>
                                <span>{company.email}</span>
                            </a>
                        )}
                    </div>
                    <div className="site-footer__copy">
                        © <span id="year">{new Date().getFullYear()}</span> {company.name} — All rights reserved
                    </div>
                </div>
            </footer>

            {/* ============ TOAST ============ */}
            <div className={`toast${toast.show ? " show" : ""}`} id="toast">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M20 6 9 17l-5-5" />
                </svg>
                <span id="toastText">{toast.text}</span>
            </div>
        </div>
    );
}
