"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth, Permission } from "../auth-context";
import { API_URL } from "../config";
import { sharedStyles } from "../styles/shared";

export default function SumPage() {
  const [a, setA] = useState("");
  const [b, setB] = useState("");
  const [result, setResult] = useState<number | null>(null);
  const [showResult, setShowResult] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { user, isLoading, logout, hasPermission } = useAuth();
  const router = useRouter();

  const canUseSum = hasPermission(Permission.USE_SUM);

  useEffect(() => {
    if (!isLoading) {
      if (!user) {
        router.push("/login");
      } else if (!canUseSum) {
        router.push(hasPermission(Permission.VIEW_AUDIT) ? "/audit" : "/login");
      }
    }
  }, [isLoading, user, router, canUseSum, hasPermission]);

  const handleSum = async () => {
    const numA = parseFloat(a) || 0;
    const numB = parseFloat(b) || 0;
    setError(null);
    
    try {
      const res = await fetch(`${API_URL}/api/sum`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ a: numA, b: numB }),
      });
      if (!res.ok) {
        throw new Error("Calculation failed");
      }
      const data = await res.json();
      setResult(data.result);
      setShowResult(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Calculation failed");
    }
  };

  const handleReset = () => {
    setA("");
    setB("");
    setResult(null);
    setShowResult(false);
    setError(null);
  };

  const handleLogout = async () => {
    await logout();
    router.push("/login");
  };

  if (isLoading) {
    return (
      <main style={styles.main}>
        <div style={styles.loader}>Loading...</div>
      </main>
    );
  }

  if (!user || !canUseSum) {
    return null;
  }

  return (
    <main style={styles.main}>
      <div style={styles.header}>
        <div style={styles.nav}>
          <a href="/" style={styles.navLink}>Counter</a>
          <span style={styles.navDivider}>•</span>
          <span style={styles.navCurrent}>Sum</span>
        </div>
        <div style={styles.userInfo}>
          <span style={styles.userEmail}>{user.email}</span>
          <button onClick={handleLogout} style={styles.logoutBtn}>
            Sign out
          </button>
        </div>
      </div>

      <div style={styles.content}>
        <div style={styles.card}>
          <span style={styles.label}>Sum Calculator</span>
          
          {!showResult ? (
            <div style={styles.inputSection}>
              <div style={styles.inputRow}>
                <div style={styles.inputWrapper}>
                  <input
                    type="number"
                    value={a}
                    onChange={(e) => setA(e.target.value)}
                    placeholder="0"
                    style={styles.input}
                    aria-label="First number"
                  />
                </div>
                <span style={styles.operator}>+</span>
                <div style={styles.inputWrapper}>
                  <input
                    type="number"
                    value={b}
                    onChange={(e) => setB(e.target.value)}
                    placeholder="0"
                    style={styles.input}
                    aria-label="Second number"
                  />
                </div>
              </div>
              <button 
                onClick={handleSum} 
                style={styles.sumBtn}
                disabled={a === "" && b === ""}
              >
                <span style={styles.equalsIcon}>=</span>
                Calculate
              </button>
              {error && (
                <div style={styles.error}>{error}</div>
              )}
            </div>
          ) : (
            <div style={styles.resultSection}>
              <div style={styles.equation}>
                <span style={styles.equationNum}>{parseFloat(a) || 0}</span>
                <span style={styles.equationOp}>+</span>
                <span style={styles.equationNum}>{parseFloat(b) || 0}</span>
                <span style={styles.equationOp}>=</span>
              </div>
              <h1 style={styles.result}>{result}</h1>
              <button onClick={handleReset} style={styles.resetBtn}>
                <span style={styles.resetIcon}>↺</span>
                Try Again
              </button>
            </div>
          )}
        </div>
      </div>
    </main>
  );
}

const pageStyles: Record<string, React.CSSProperties> = {
  card: {
    background: "rgba(255, 255, 255, 0.03)",
    backdropFilter: "blur(10px)",
    border: "1px solid rgba(255, 255, 255, 0.08)",
    borderRadius: "32px",
    padding: "3rem 4rem",
    textAlign: "center",
    boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.5)",
    minWidth: "400px",
  },
  label: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    display: "block",
    color: "rgba(255, 255, 255, 0.4)",
    fontSize: "0.875rem",
    textTransform: "uppercase",
    letterSpacing: "0.1em",
    marginBottom: "2rem",
  },
  inputSection: {
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    gap: "2rem",
  },
  inputRow: {
    display: "flex",
    alignItems: "center",
    gap: "1rem",
  },
  inputWrapper: {
    position: "relative",
  },
  input: {
    fontFamily: "'Instrument Serif', Georgia, serif",
    fontSize: "3rem",
    fontWeight: 400,
    width: "120px",
    padding: "0.75rem 1rem",
    textAlign: "center",
    background: "rgba(255, 255, 255, 0.05)",
    border: "2px solid rgba(255, 255, 255, 0.1)",
    borderRadius: "16px",
    color: "#fff",
    outline: "none",
    transition: "border-color 0.2s, box-shadow 0.2s",
  },
  operator: {
    fontFamily: "'Instrument Serif', Georgia, serif",
    fontSize: "3rem",
    color: "#a78bfa",
    fontWeight: 400,
  },
  sumBtn: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    padding: "1rem 2.5rem",
    fontSize: "1.125rem",
    fontWeight: 600,
    background: "linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)",
    color: "#fff",
    border: "none",
    borderRadius: "16px",
    cursor: "pointer",
    display: "inline-flex",
    alignItems: "center",
    gap: "0.5rem",
    transition: "transform 0.2s, box-shadow 0.2s",
    boxShadow: "0 4px 14px rgba(99, 102, 241, 0.4)",
  },
  equalsIcon: {
    fontSize: "1.5rem",
    fontWeight: 400,
  },
  resultSection: {
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
  },
  equation: {
    display: "flex",
    alignItems: "center",
    gap: "0.5rem",
    marginBottom: "0.5rem",
  },
  equationNum: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    fontSize: "1.25rem",
    color: "rgba(255, 255, 255, 0.6)",
  },
  equationOp: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    fontSize: "1.25rem",
    color: "rgba(139, 92, 246, 0.8)",
  },
  result: {
    fontFamily: "'Instrument Serif', Georgia, serif",
    fontSize: "7rem",
    fontWeight: 400,
    color: "#fff",
    margin: 0,
    lineHeight: 1,
    background: "linear-gradient(135deg, #fff 0%, #a78bfa 100%)",
    WebkitBackgroundClip: "text",
    WebkitTextFillColor: "transparent",
    backgroundClip: "text",
  },
  resetBtn: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    marginTop: "2rem",
    padding: "0.875rem 2rem",
    fontSize: "1rem",
    fontWeight: 500,
    background: "rgba(255, 255, 255, 0.05)",
    color: "rgba(255, 255, 255, 0.7)",
    border: "1px solid rgba(255, 255, 255, 0.1)",
    borderRadius: "12px",
    cursor: "pointer",
    display: "inline-flex",
    alignItems: "center",
    gap: "0.5rem",
    transition: "all 0.2s",
  },
  resetIcon: {
    fontSize: "1.25rem",
  },
  error: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    color: "#f87171",
    fontSize: "0.875rem",
    marginTop: "0.5rem",
  },
};

const styles = { ...sharedStyles, ...pageStyles };

