"use client";

import { useState, useEffect } from "react";
import { XMarkIcon } from "@heroicons/react/24/outline";
import { SignupForm } from "../SignupForm/SignupForm";
import { LoginForm } from "../LoginForm/LoginForm";
import { useAuthStore } from "../../stores/auth.store";
import { useRouter } from "next/navigation";

interface AuthModalProps {
  isOpen: boolean;
  onClose: () => void;
  initialMode?: "signup" | "login" | undefined;
  redirectTo?: string | undefined;
  title?: string | undefined;
  description?: string | undefined;
  showCloseButton?: boolean | undefined;
}

export function AuthModal({
  isOpen,
  onClose,
  initialMode = "signup",
  redirectTo,
  title,
  description,
  showCloseButton = true,
}: AuthModalProps) {
  const [mode, setMode] = useState<"signup" | "login">(initialMode);
  const router = useRouter();
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
  const hasCheckedAuth = useAuthStore(state => state.hasCheckedAuth);

  // Update mode when initialMode changes
  useEffect(() => {
    setMode(initialMode);
  }, [initialMode]);

  // Close modal and redirect when authenticated
  useEffect(() => {
    if (isOpen && hasCheckedAuth && isAuthenticated && redirectTo) {
      onClose();
      router.push(redirectTo);
    }
  }, [isOpen, hasCheckedAuth, isAuthenticated, redirectTo, onClose, router]);

  if (!isOpen) return null;

  const defaultTitle = mode === "signup" ? "Create your account" : "Sign in to continue";
  const defaultDescription =
    mode === "signup"
      ? "Create an account to continue with your order and access personalized plans."
      : "Sign in to your account to continue with your order.";

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      onClick={e => {
        if (e.target === e.currentTarget) {
          onClose();
        }
      }}
    >
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-background/80 backdrop-blur-sm transition-opacity"
        aria-hidden="true"
      />

      {/* Modal */}
      <div
        className="relative z-10 w-full max-w-lg rounded-2xl border border-border bg-card text-card-foreground shadow-[var(--cp-shadow-3)] max-h-[90vh] overflow-y-auto"
        onClick={e => e.stopPropagation()}
      >
        <div className="sticky top-0 z-10 flex items-center justify-between border-b border-border bg-card px-6 py-4">
          <div className="flex-1">
            <h2 className="text-xl font-semibold text-foreground">{title || defaultTitle}</h2>
            <p className="mt-1 text-sm text-muted-foreground">
              {description || defaultDescription}
            </p>
          </div>
          {showCloseButton && (
            <button
              onClick={onClose}
              className="ml-4 text-muted-foreground transition-colors hover:text-foreground"
              aria-label="Close modal"
              type="button"
            >
              <XMarkIcon className="h-5 w-5" />
            </button>
          )}
        </div>

        <div className="p-6">
          {mode === "signup" ? (
            <SignupForm
              redirectTo={redirectTo}
              onSuccess={() => {
                // Will be handled by useEffect above
              }}
            />
          ) : (
            <LoginForm
              redirectTo={redirectTo}
              onSuccess={() => {
                // Will be handled by useEffect above
              }}
              showSignupLink={false}
            />
          )}

          {/* Toggle between signup and login */}
          <div className="mt-6 border-t border-border pt-6 text-center">
            {mode === "signup" ? (
              <p className="text-sm text-muted-foreground">
                Already have an account?{" "}
                <button
                  onClick={() => setMode("login")}
                  className="font-medium text-primary hover:underline transition-colors"
                >
                  Sign in
                </button>
              </p>
            ) : (
              <p className="text-sm text-muted-foreground">
                Don&apos;t have an account?{" "}
                <button
                  onClick={() => setMode("signup")}
                  className="font-medium text-primary hover:underline transition-colors"
                >
                  Create one
                </button>
              </p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
