import { useState } from "react";
import { Form, redirect, useActionData, type ActionFunctionArgs } from "react-router";

export async function action({ request, context }: ActionFunctionArgs) {
  const formData = await request.formData();
  const env = context.cloudflare.env as { API: Fetcher };

  const mode = formData.get("mode"); // 'login' or 'register'
  const email = formData.get("email");
  const password = formData.get("password");
  const name = formData.get("username");
  const display_name = formData.get("displayName");

  // Determine path based on the radio selection
  const path = mode === "login" ? "/users/login" : "/users/create";

  // Construct body based on mode
  const body = mode === "login" 
    ? { email, password } 
    : { email, password, name, display_name };

  const response = await env.API.fetch(new Request(`http://internal${path}`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Cookie": request.headers.get("Cookie") || "",
    },
    body: JSON.stringify(body),
  }));

  if (!response.ok) {
    const errorText = await response.text();
    return { error: `Error (${response.status}): ${errorText}` };
  }

  // Important: We proxy the 'Set-Cookie' header from the internal API 
  // back to the browser so the user actually gets logged in.
  const headers = new Headers();
  const setCookie = response.headers.get("Set-Cookie");
  if (setCookie) {
    headers.append("Set-Cookie", setCookie);
  }

  return redirect("/", { headers });
}

export default function LoginPage() {
  const [loginRegisterSelection, setLoginRegisterSelection] = useState("login");
  const actionData = useActionData() as { error?: string } | undefined;

  return (
    <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 p-5 shadow-none shadow-black/0 hover:shadow-black/40 hover:shadow-2xl rounded-2xl bg-[#151515] text-center transition ease-in-out duration-300 hover:ring-2 hover:ring-[#cccccc]">
      <h1 className="text-2xl font-black mb-4">Login/Register</h1>
      
      {actionData?.error && (
        <div className="bg-red-500/20 border border-red-500 text-red-200 p-2 rounded-xl mb-4 text-sm">
          {actionData.error}
        </div>
      )}

      <Form method="post">
        {/* We use a hidden input or the radio group to tell the action which mode we are in */}
        <div className="flex gap-4 justify-center mb-4">
          <div>
            <input 
              type="radio" 
              id="loginOption" 
              name="mode" 
              value="login" 
              checked={loginRegisterSelection === 'login'} 
              onChange={() => setLoginRegisterSelection('login')} 
            />
            <label htmlFor="loginOption" className="ml-2">Login</label>
          </div>
          <div>
            <input 
              type="radio" 
              id="registerOption" 
              name="mode" 
              value="register" 
              checked={loginRegisterSelection === 'register'} 
              onChange={() => setLoginRegisterSelection('register')} 
            />
            <label htmlFor="registerOption" className="ml-2">Register</label>
          </div>
        </div>

        <div className="flex flex-col gap-3">
          <div className="flex items-center justify-between">
            <label htmlFor="email" className="mx-4">Email</label>
            <input 
              name="email" 
              type="email" 
              id="email" 
              required
              className="bg-transparent border-[1px] border-white/40 rounded-xl text-center p-1 focus:border-white outline-none" 
            />
          </div>
          
          <div className="flex items-center justify-between">
            <label htmlFor="password" className="mx-4">Password</label>
            <input 
              name="password" 
              type="password" 
              id="password" 
              required
              className="bg-transparent border-[1px] border-white/40 rounded-xl text-center p-1 focus:border-white outline-none" 
            />
          </div>

          {loginRegisterSelection === 'register' && (
            <>
              <div className="flex items-center justify-between">
                <label htmlFor="username" className="mx-4">Username</label>
                <input 
                  name="username" 
                  type="text" 
                  id="username" 
                  required
                  className="bg-transparent border-[1px] border-white/40 rounded-xl text-center p-1 focus:border-white outline-none" 
                />
              </div>
              <div className="flex items-center justify-between">
                <label htmlFor="displayName" className="mx-4">Display Name</label>
                <input 
                  name="displayName" 
                  type="text" 
                  id="displayName" 
                  required
                  className="bg-transparent border-[1px] border-white/40 rounded-xl text-center p-1 focus:border-white outline-none" 
                />
              </div>
            </>
          )}
        </div>

        <button 
          type="submit" 
          className="mt-6 bg-white text-black font-bold rounded-xl p-2 px-6 hover:scale-105 transition-transform"
        >
          {loginRegisterSelection === 'login' ? 'Login' : 'Register'}
        </button>
      </Form>
    </div>
  );
}