import CardCaroussel from "@/components/CardCaroussel";
import Button from "@/components/Button";
import Row from "@/components/Row";
import Content from "@/components/Content";
import { ArrowOutward } from "@mui/icons-material";
import { FormEvent, useEffect, useState } from "react";
import { useRouter } from "next/router";
import styles from "@/styles/Home.module.css";
import StartSessionPopup from "@/components/Session/PopUps/StartSessionPopup";
import type { SessionCardProps } from "@/components/SessionCard";

function openCard(sessionId: string) {
  console.log(`${sessionId} clicked`);
}

type HomeProps = {
  isAuthenticated?: boolean;
  onRequireLogin?: (action?: "startSession" | "profile") => void;
};

function Home({ isAuthenticated, onRequireLogin }: HomeProps) {
  const router = useRouter();
  const [joinCode, setJoinCode] = useState("");
  const [showStartPopup, setShowStartPopup] = useState(false);
  const [recentSessions, setRecentSessions] = useState<SessionCardProps[]>([]);

  function handleJoinLobby(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const trimmed = joinCode.trim();
    if (!trimmed) return;
    router.push(
      {
        pathname: "/session",
        query: { id: trimmed },
      },
      `/session/${encodeURIComponent(trimmed)}`
    ).catch(() => {});
  }

  function handleCreateSession() {
    if (!isAuthenticated) {
      onRequireLogin?.("startSession");
      return;
    }
    setShowStartPopup(true);
  }

  useEffect(() => {
    const loadRecent = async () => {
      if (!isAuthenticated) {
        setRecentSessions([]);
        return;
      }
      try {
        const res = await fetch("/api/sessions/recent");
        if (!res.ok) return;
        const json = await res.json();
        const sessions = (json?.sessions ?? []) as Array<{
          sessionCode: string;
          pdfPath: string;
          topic: string | null;
        }>;
        const mapped: SessionCardProps[] = sessions.map((s) => ({
          previewUrl: s.pdfPath,
          title: s.topic ?? undefined,
          sessionId: s.sessionCode,
          callBack: openCard,
        }));
        setRecentSessions(mapped);
      } catch (err) {
        console.error("recent sessions failed", err);
      }
    };
    loadRecent();
  }, [isAuthenticated]);

  return (
    <>
      <Content>
        <h1>Gemeinsam Kreativ</h1>
        <p style={{ maxWidth: 780, fontSize: 24, marginBottom: 24 }}>
          Starte eine gemeinsame Kreativ-Session und entwickelt im Team neue Ideen:
          In kurzen Runden notiert oder skizziert jede Person eigene Einfälle oder
          führt die der anderen weiter. Am Ende bewertet ihr die Ergebnisse und
          könnt eure besten Ideen als PDF sichern – strukturiert, kollaborativ und
          komplett online.
        </p>

        <form onSubmit={handleJoinLobby} style={{ width: "100%" }}>
          <Row className={styles.joinRow} style={{ marginBottom: 16 }}>
            <input
              type="text"
              placeholder="Session-Code eingeben"
              value={joinCode}
              onChange={(e) => setJoinCode(e.target.value)}
              style={{
                padding: "8px 12px",
                borderRadius: 12,
                border: "1px solid #d0d0d0",
                fontSize: "1rem",
                height: "40px",
                minHeight: "40px",
              }}
            />
            <Button
              type="submit"
              className={styles.joinButton}
              style={{ margin: 0, height: "40px", minHeight: "40px" }}
              icon={<ArrowOutward />}
              iconPosition="right"
              variant="secondary"
            >
              Session beitreten
            </Button>
            <Button
              type="button"
              className={styles.joinButton}
              style={{ margin: 0, height: "40px", minHeight: "40px" }}
              onClick={handleCreateSession}
              icon={<ArrowOutward />}
              iconPosition="right"
            >
              Neue Session starten
            </Button>
          </Row>
        </form>

        {isAuthenticated && recentSessions.length > 0 && (
          <div style={{ marginTop: 32 }}>
            <h2>Letzte Sessions</h2>
            <CardCaroussel
              cardProps={recentSessions.map((c) => ({
                ...c,
                callBack: () => window.open(c.previewUrl, "_blank", "noopener"),
              }))}
            />
          </div>
        )}
      </Content>

      <StartSessionPopup
        open={showStartPopup}
        onClose={() => setShowStartPopup(false)}
        onConfirm={() => {}}
      />
    </>
  );
}

export default Home;
