"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import { createClient } from "@/lib/supabase/client";

export function useWorkerAuth() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [authError, setAuthError] = useState<string | null>(null);
  const [authLoading, setAuthLoading] = useState(false);
  
  const router = useRouter();
  const supabase = createClient();

  useEffect(() => {
    async function checkAuth() {
      try {
        const {
          data: { user },
        } = await supabase.auth.getUser();
        if (user) {
          setIsAuthenticated(true);
        }
      } catch {
        // Auth check failed — treat as not authenticated
      } finally {
        setLoading(false);
      }
    }
    checkAuth();
  }, [supabase.auth]);

  async function handleAuth(e: React.FormEvent) {
    e.preventDefault();

    if (isAuthenticated) {
      return;
    }

    // Confirm password match
    if (password !== confirmPassword) {
      setAuthError("Passwords don't match. Please check and try again.");
      return;
    }

    setAuthLoading(true);
    setAuthError(null);

    try {
      const { error } = await supabase.auth.signUp({
        email,
        password,
        options: {
          data: { type: "worker" },
          emailRedirectTo: `${window.location.origin}/auth/callback`,
        },
      });

      if (error) {
        if (error.message.includes("already registered")) {
          const { error: loginError } = await supabase.auth.signInWithPassword({
            email,
            password,
          });
          if (loginError) {
            setAuthError(loginError.message);
            setAuthLoading(false);
            return;
          }
        } else {
          setAuthError(error.message);
          setAuthLoading(false);
          return;
        }
      }

      setIsAuthenticated(true);
      setAuthLoading(false);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Something went wrong. Please try again.";
      setAuthError(message);
      setAuthLoading(false);
    }
  }

  return {
    isAuthenticated,
    loading,
    email,
    setEmail,
    password,
    setPassword,
    confirmPassword,
    setConfirmPassword,
    authError,
    authLoading,
    handleAuth,
  };
}