"use client";

import { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Layout from "@/components/layout/Layout";
import PortalSelector from "@/components/dashboard/PortalSelector";
import LogoutButton from "@/components/dashboard/LogoutButton";

export default function Portal() {
  const searchParams = useSearchParams();
  const router = useRouter();

  // Use dummy user data
  const [sessionAccess, setSessionAccess] = useState(true);
  const [session, setSession] = useState({
    user: {
      username: "admin",
      password: "admin",
      user_metadata: {
        client_id: "dummy_client_id",
      },
    },
  });

  useEffect(() => {
    // Simulate Stripe session handling if session_id exists in URL
    const stripeSessionId = searchParams.get("session_id");
    if (stripeSessionId) {
      handleSuccessfulPayment(
        stripeSessionId,
        session.user.user_metadata.client_id
      );
    }
  }, [searchParams, session]);

  const handleSuccessfulPayment = async (stripeSessionId, userId) => {
    try {
      const response = await fetch("/api/handle-successful-payment", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ sessionId: stripeSessionId, userId }),
      });

      if (!response.ok) {
        throw new Error("Failed to handle successful payment");
      }
      // Optionally, you can update the UI or show a success message here
    } catch (error) {
      console.error("Error handling successful payment:", error);
      // Optionally, show an error message to the user
    }
  };

  return (
    <>
      {!sessionAccess && <p>Loading...</p>}
      {sessionAccess && (
        <Layout headerStyle={6} footerStyle={3} transparent={false}>
          <section className="portal__area">
            <div className="container">
              <PortalSelector session={session} />
            </div>
            <LogoutButton />
          </section>
        </Layout>
      )}
    </>
  );
}
