import { createSignal } from 'solid-js';
import { LogOut } from 'lucide-solid';
import { BTN_GHOST, BTN_ORANGE, CARD } from '~/components/DashboardShell';

const API = '';
const NAVY = '#0D0D2A';
const ORANGE = '#FF5E13';

async function apiFetch(path: string, opts?: RequestInit) {
  const token =
    typeof window !== "undefined"
      ? window.sessionStorage.getItem("nxtgauge_access_token") || ""
      : "";
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts?.headers ?? {}),
    },
  });
}

export default function LogoutPage() {
  const [busy, setBusy] = createSignal(false);
  const [err, setErr] = createSignal('');

  const doLogout = async () => {
    setBusy(true);
    setErr('');
    try {
      await apiFetch('/api/auth/logout', { method: 'POST' });
    } catch {
      // ignore and clear local state anyway
    } finally {
      try {
        window.localStorage.removeItem('nxtgauge_signup_profile_v1');
        window.localStorage.removeItem('nxtgauge_auth_user');
        window.localStorage.removeItem('nxtgauge_user');
        window.sessionStorage.removeItem('nxtgauge_access_token');
        window.sessionStorage.removeItem('nxtgauge_refresh_token');
        window.sessionStorage.removeItem('nxtgauge_auth_user');
        window.sessionStorage.removeItem('nxtgauge_user');
      } catch {
        setErr('Could not clear local session completely.');
      }
      window.location.href = '/login';
      setBusy(false);
    }
  };

  return (
    <div style={{ display: 'grid', gap: '14px', 'max-width': '760px' }}>
      <div
        style={{
          background: NAVY,
          "border-radius": "12px",
          padding: "16px 20px",
          display: "flex",
          "align-items": "center",
          gap: "12px",
        }}
      >
        <span style={{ color: ORANGE }}>
          <LogOut size={24} />
        </span>
        <div>
          <p style={{ margin: "0", "font-size": "18px", "font-weight": "800", color: "#fff" }}>
            Logout
          </p>
          <p style={{ margin: "4px 0 0", "font-size": "13px", color: "rgba(255,255,255,0.65)" }}>
            End your current session securely.
          </p>
        </div>
      </div>

      <div style={CARD}>
        <p style={{ margin: '0 0 12px', 'font-size': '14px', color: '#374151' }}>
          Are you sure you want to logout from this account?
        </p>
        <div style={{ display: 'flex', gap: '10px' }}>
          <button type="button" onClick={() => window.history.back()} style={BTN_GHOST}>Cancel</button>
          <button type="button" onClick={doLogout} disabled={busy()} style={{ ...BTN_ORANGE, opacity: busy() ? '0.7' : '1' }}>
            {busy() ? 'Logging out...' : 'Confirm Logout'}
          </button>
        </div>
      </div>

      {err() && (
        <div style={{ ...CARD, border: '1px solid #FECACA', background: '#FEF2F2', padding: '12px 14px', color: '#B91C1C', 'font-size': '13px', 'font-weight': '600' }}>
          {err()}
        </div>
      )}
    </div>
  );
}

