import { LitElement, html, css } from "lit";
import { customElement, state } from "lit/decorators.js";
import { authService } from "../../services/auth.service.js";
import { LocaleController } from "../../i18n/locale-controller.js";
import "../../components/button/primary-button.js";
import "../../components/input/text-input.js";

@customElement("login-page")
export class LoginPage extends LitElement {
  private _t = new LocaleController(this);

  @state() private email = "";
  @state() private password = "";
  @state() private remember = false;
  @state() private error: string | null = null;
  @state() private loading = false;

  static styles = css`
    :host {
      flex: 1;
      display: flex;
    }

    .layout {
      display: grid;
      grid-template-columns: minmax(320px, 34rem) 1fr;
      width: 100%;
      min-height: 100%;
    }

    /* ── Left panel ──────────────────────────── */
    .form-panel {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: 3.5rem 4rem;
      background: var(--color-bg, #f5f5f5);
    }

    .form-content {
      max-width: 26rem;
    }

    .eyebrow {
      margin: 0 0 1rem;
      font-size: var(--font-size-xs, 0.75rem);
      font-weight: var(--font-weight-medium, 500);
      letter-spacing: 0.12em;
      color: color-mix(in srgb, var(--color-text) 50%, transparent);
    }

    h1 {
      margin: 0 0 0.75rem;
      font-size: 1.75rem;
      font-weight: var(--font-weight-bold, 700);
      color: var(--color-text, #111);
      line-height: 1.2;
    }

    .subtitle {
      margin: 0 0 2.5rem;
      font-size: var(--font-size-sm, 0.875rem);
      color: color-mix(in srgb, var(--color-text) 60%, transparent);
      line-height: 1.55;
    }

    form {
      display: flex;
      flex-direction: column;
      gap: 1.25rem;
    }

    .field {
      display: flex;
      flex-direction: column;
      gap: 0.4rem;
    }

    .field-label {
      font-size: var(--font-size-xs, 0.75rem);
      font-weight: var(--font-weight-medium, 500);
      letter-spacing: 0.08em;
      color: color-mix(in srgb, var(--color-text) 65%, transparent);
    }

    .row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 1rem;
    }

    .remember {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      font-size: var(--font-size-sm, 0.875rem);
      color: color-mix(in srgb, var(--color-text) 70%, transparent);
      cursor: pointer;
      user-select: none;
    }

    .remember input[type="checkbox"] {
      width: 1rem;
      height: 1rem;
      cursor: pointer;
      accent-color: var(--color-accent, #2b6cb0);
      flex-shrink: 0;
    }

    .forgot {
      font-size: var(--font-size-sm, 0.875rem);
      color: var(--color-accent, #2b6cb0);
      text-decoration: none;
      white-space: nowrap;
      flex-shrink: 0;
    }

    .forgot:hover {
      text-decoration: underline;
    }

    .error {
      font-size: var(--font-size-sm, 0.875rem);
      color: #c53030;
      margin: 0;
    }

    .footer {
      margin-top: 2rem;
      font-size: var(--font-size-xs, 0.75rem);
      color: color-mix(in srgb, var(--color-text) 40%, transparent);
    }

    /* ── Right panel ─────────────────────────── */
    .hero-panel {
      position: relative;
      background: var(--color-border, #ddd);
      overflow: hidden;
    }

    .hero-panel img {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
      pointer-events: none;
      user-select: none;
      -webkit-user-drag: none;
    }

    /* ── Responsive ──────────────────────────── */
    @media (max-width: 34rem) {
      .layout {
        grid-template-columns: 1fr;
      }

      .hero-panel {
        display: none;
      }

      .form-panel {
        max-width: 34rem;
        margin: 0 auto;
        padding: 2.5rem 1.5rem;
      }

      .form-content {
        width: 100%;
        margin: 0 auto;
      }
    }
  `;

  private _navigate(path: string) {
    window.dispatchEvent(
      new CustomEvent("nav", { detail: { path }, bubbles: true, composed: true }),
    );
  }

  private async _handleSubmit(e: Event) {
    e.preventDefault();
    if (this.loading) return;

    this.error = null;
    this.loading = true;

    try {
      const response = await fetch("http://127.0.0.1:8080/auth/login", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: this.email, password: this.password }),
      });

      if (!response.ok) {
        this.error =
          response.status === 401
            ? this._t.t("login.error.credentials")
            : this._t.t("login.error.failed");
        return;
      }

      const raw = await response.json();
      const base64url = raw.accessToken.split(".")[1];
      const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
      const payload = JSON.parse(atob(base64));

      authService.setSession(
        {
          id: payload.sub,
          email: payload.email,
          role: payload.role ?? null,
          permissions: payload.permissions ?? [],
        },
        raw.accessToken,
      );

      window.dispatchEvent(new CustomEvent("auth-changed"));
      this._navigate(authService.isAdmin ? "/admin" : "/cc");
    } catch {
      this.error = this._t.t("login.error.network");
    } finally {
      this.loading = false;
    }
  }

  render() {
    const t = (k: Parameters<typeof this._t.t>[0]) => this._t.t(k);

    return html`
      <div class="layout">
        <div class="form-panel">
          <div class="form-content">
            <p class="eyebrow">${t("login.eyebrow")}</p>
            <h1>${t("login.title")}</h1>
            <p class="subtitle">${t("login.subtitle")}</p>

            <form @submit=${this._handleSubmit} novalidate>
              <div class="field">
                <span class="field-label">${t("login.email")}</span>
                <text-input
                  name="email"
                  autocomplete="email"
                  placeholder="name@example.com"
                  .value=${this.email}
                  .onValueChange=${(v: string) => { this.email = v; }}
                ></text-input>
              </div>

              <div class="field">
                <span class="field-label">${t("login.password")}</span>
                <text-input
                  name="password"
                  autocomplete="current-password"
                  password
                  .value=${this.password}
                  .onValueChange=${(v: string) => { this.password = v; }}
                ></text-input>
              </div>

              <div class="row">
                <label class="remember">
                  <input
                    type="checkbox"
                    .checked=${this.remember}
                    @change=${(e: Event) =>
                      (this.remember = (e.target as HTMLInputElement).checked)}
                  />
                  ${t("login.remember")}
                </label>
                <a class="forgot" href="/forgot-password" @click=${(e: Event) => {
                  e.preventDefault();
                  this._navigate("/forgot-password");
                }}>
                  ${t("login.forgot")}
                </a>
              </div>

              ${this.error ? html`<p class="error">${this.error}</p>` : null}

              <primary-button
                label=${this.loading ? t("login.loading") : t("login.submit")}
                ?disabled=${this.loading}
                .onClick=${() => {}}
                icon="arrow-right"
              ></primary-button>
            </form>
          </div>

          <p class="footer">© ${new Date().getFullYear()} FlightScore</p>
        </div>

        <div class="hero-panel">
          <img src="/auth/hero.jpeg" alt="" aria-hidden="true" />
        </div>
      </div>
    `;
  }
}
