"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { useAppTheme } from "@/components/ThemeProvider";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Eye, EyeOff, Loader2, X, Mail } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { loginSchema, type LoginInput } from "@/lib/schema/auth";
import { toast } from "sonner";
import { useRouter, usePathname } from "next/navigation";
import { ForgotPasswordDialog } from "./ForgotPasswordDialog";
import { VerifyOtpDialog } from "./VerifyOtpDialog";

interface LoginDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onLoginSuccess: () => void;
  prefillEmail?: string;
  onSwitchToSignup?: () => void;
  skipRedirect?: boolean; // Option to skip automatic redirect
}

// Login Dialog component
export function LoginDialog({ open, onOpenChange, onLoginSuccess, prefillEmail, onSwitchToSignup, skipRedirect = false }: LoginDialogProps) {
  const { theme } = useAppTheme();
  const isDark = theme === "dark";
  const router = useRouter();
  const pathname = usePathname();
  const { login, loginMutation } = useAuth();
  const [loginData, setLoginData] = useState<LoginInput>({
    email: "",
    password: "",
  });
  const [showPassword, setShowPassword] = useState(false);
  const [forgotPasswordDialogOpen, setForgotPasswordDialogOpen] = useState(false);
  const [showResendOtp, setShowResendOtp] = useState(false);
  const [verifyOtpDialogOpen, setVerifyOtpDialogOpen] = useState(false);

  // Pre-fill email if provided
  useEffect(() => {
    if (prefillEmail && open) {
      setLoginData(prev => ({ ...prev, email: prefillEmail }));
    }
  }, [prefillEmail, open]);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validate form
    const validation = loginSchema.safeParse(loginData);
    if (!validation.success) {
      const firstError = validation.error.issues[0];
      toast.error(firstError.message);
      return;
    }
    
    try {
      const result = await login(loginData);
      
      if (result.tokens && result.user) {
        toast.success("Login successful!");
        setShowPassword(false);
        setShowResendOtp(false);
        onOpenChange(false);
        // Reset form
        setLoginData({ email: "", password: "" });
        
        // Check if user is admin/staff/superuser
        const user = result.user as any;
        const isTruthy = (value: any): boolean => {
          if (value === true || value === "true" || value === 1 || value === "1") return true;
          return false;
        };
        
        const userIsAdmin = 
          isTruthy(user.is_admin) || 
          isTruthy(user.isAdmin) ||
          isTruthy(user.is_staff) ||
          isTruthy(user.isStaff) ||
          isTruthy(user.is_superuser) ||
          isTruthy(user.isSuperuser);
        
        // Call onLoginSuccess callback first
        onLoginSuccess();
        
        // Only redirect if skipRedirect is false and we're not on the booking page
        if (!skipRedirect && pathname !== "/book-now") {
          // Redirect based on user role
          const redirectPath = userIsAdmin ? "/admin/dashboard" : "/user/dashboard";
          setTimeout(() => {
            window.location.href = redirectPath;
          }, 200);
        }
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : "Login failed. Please try again.";
      toast.error(errorMessage);
      
      // Check if error is about email verification
      if (errorMessage.toLowerCase().includes("verify your email") || 
          errorMessage.toLowerCase().includes("email address before logging")) {
        setShowResendOtp(true);
      } else {
        setShowResendOtp(false);
      }
    }
  };

  // Handle resend OTP - just open the verification dialog (it will auto-send OTP)
  const handleResendOtp = () => {
    if (!loginData.email) {
      toast.error("Email address is required to resend OTP.");
      return;
    }
    
    // Close login dialog and open OTP verification dialog
    // The VerifyOtpDialog will automatically send the OTP when it opens
    setShowResendOtp(false);
    onOpenChange(false);
    setTimeout(() => {
      setVerifyOtpDialogOpen(true);
    }, 100);
  };

  // Handle OTP verification success
  const handleOtpVerificationSuccess = () => {
    // After successful verification, user can try logging in again
    setVerifyOtpDialogOpen(false);
    // Optionally reopen login dialog
    setTimeout(() => {
      onOpenChange(true);
    }, 100);
  };

  // Reset form when dialog closes
  const handleDialogChange = (isOpen: boolean) => {
    if (!isOpen) {
      setLoginData({ email: "", password: "" });
      setShowResendOtp(false);
    }
    onOpenChange(isOpen);
  };

  return (
    <Dialog open={open} onOpenChange={handleDialogChange}>
      <DialogContent 
        showCloseButton={false}
        className={`max-w-md max-h-[90vh] overflow-hidden flex flex-col p-0 ${isDark ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'}`}
      >
        {/* Header with Close Button - Fixed */}
        <div className="flex items-start justify-between p-6 pb-4 flex-shrink-0 border-b border-gray-200 dark:border-gray-700">
          <DialogHeader className="flex-1 pr-2">
            <DialogTitle className="text-2xl sm:text-3xl font-bold bg-gradient-to-r from-rose-600 via-pink-600 to-rose-600 bg-clip-text text-transparent">
              Welcome back
            </DialogTitle>
            <DialogDescription className={`text-sm sm:text-base mt-1 ${isDark ? 'text-gray-400' : 'text-gray-600'}`}>
              Please log in to complete your booking
            </DialogDescription>
          </DialogHeader>
          {/* Close Button */}
          <Button
            type="button"
            variant="ghost"
            size="icon"
            onClick={() => handleDialogChange(false)}
            className={`flex-shrink-0 w-8 h-8 rounded-full ${isDark ? 'text-gray-400 hover:text-gray-300 hover:bg-gray-700' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'}`}
            aria-label="Close"
          >
            <X className="w-5 h-5" />
          </Button>
        </div>

        {/* Scrollable Content */}
        <div className="overflow-y-auto flex-1 px-6">
          {/* Login Form */}
          <form className="space-y-4 sm:space-y-5 py-4 sm:py-6" onSubmit={handleLogin}>
            {/* Email Field */}
            <div className="space-y-1.5 sm:space-y-2">
              <label htmlFor="login-email" className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                Email address
              </label>
              <Input
                id="login-email"
                type="email"
                placeholder="Email address"
                value={loginData.email}
                onChange={(e) => setLoginData({ ...loginData, email: e.target.value })}
                className={`h-11 sm:h-12 text-sm sm:text-base ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900'}`}
                required
              />
            </div>

            {/* Password Field */}
            <div className="space-y-1.5 sm:space-y-2">
              <label htmlFor="login-password" className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                Your password
              </label>
              <div className="relative">
                <Input
                  id="login-password"
                  type={showPassword ? "text" : "password"}
                  placeholder="Your password"
                  value={loginData.password}
                  onChange={(e) => setLoginData({ ...loginData, password: e.target.value })}
                  className={`h-11 sm:h-12 pr-12 text-sm sm:text-base ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900'}`}
                  required
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  onClick={() => setShowPassword(!showPassword)}
                  className={`absolute right-3 sm:right-4 top-1/2 -translate-y-1/2 h-auto w-auto p-0 ${isDark ? 'text-gray-400 hover:text-gray-300' : 'text-gray-500 hover:text-gray-700'}`}
                  aria-label={showPassword ? "Hide password" : "Show password"}
                >
                  {showPassword ? (
                    <EyeOff className="w-4 h-4 sm:w-5 sm:h-5" />
                  ) : (
                    <Eye className="w-4 h-4 sm:w-5 sm:h-5" />
                  )}
                </Button>
              </div>
            </div>

            {/* Submit Button */}
            <Button
              type="submit"
              disabled={loginMutation.isPending}
              className="w-full h-11 sm:h-12 text-sm sm:text-base font-semibold bg-gradient-to-r from-rose-500 to-pink-600 hover:from-rose-600 hover:to-pink-700 text-white shadow-lg hover:shadow-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed mt-4 sm:mt-6"
            >
              {loginMutation.isPending ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Logging in...
                </>
              ) : (
                "Log in"
              )}
            </Button>

            {/* Resend OTP - Show when email verification error occurs */}
            {showResendOtp && (
              <div className={`p-3 sm:p-4 rounded-lg border ${isDark ? 'bg-yellow-900/20 border-yellow-800' : 'bg-yellow-50 border-yellow-200'}`}>
                <div className="flex items-start gap-3">
                  <Mail className={`w-5 h-5 mt-0.5 flex-shrink-0 ${isDark ? 'text-yellow-400' : 'text-yellow-600'}`} />
                  <div className="flex-1">
                    <p className={`text-sm font-medium ${isDark ? 'text-yellow-200' : 'text-yellow-900'}`}>
                      Email verification required
                    </p>
                    <p className={`text-xs sm:text-sm mt-1 ${isDark ? 'text-yellow-300' : 'text-yellow-700'}`}>
                      Please verify your email address before logging in. We can resend the verification code to {loginData.email}.
                    </p>
                    <Button
                      type="button"
                      variant="link"
                      onClick={handleResendOtp}
                      className={`h-auto p-0 mt-2 text-xs sm:text-sm font-medium ${isDark ? 'text-yellow-400 hover:text-yellow-300' : 'text-yellow-700 hover:text-yellow-800'}`}
                    >
                      Resend verification code
                    </Button>
                  </div>
                </div>
              </div>
            )}

            {/* Forgot Password */}
            <div className="flex items-center justify-end text-xs sm:text-sm">
              <Button
                type="button"
                variant="link"
                className={`font-medium text-xs sm:text-sm h-auto p-0 ${isDark ? 'text-blue-400 hover:text-blue-300' : 'text-blue-600 hover:text-blue-700'}`}
                onClick={() => {
                  handleDialogChange(false);
                  setTimeout(() => {
                    setForgotPasswordDialogOpen(true);
                  }, 100);
                }}
              >
                Forgot password?
              </Button>
            </div>

            {/* Sign Up Prompt */}
            <p className={`text-xs sm:text-sm text-center pt-2 ${isDark ? 'text-gray-400' : 'text-gray-600'}`}>
              New to Attune Heart Therapy?{" "}
              <Button
                type="button"
                variant="link"
                onClick={() => {
                  handleDialogChange(false);
                  if (onSwitchToSignup) {
                    onSwitchToSignup();
                  }
                }}
                className={`h-auto p-0 font-medium ${isDark ? 'text-blue-400 hover:text-blue-300' : 'text-blue-600 hover:text-blue-700'}`}
              >
                Sign up
              </Button>
            </p>
          </form>
        </div>
      </DialogContent>
      
      {/* Forgot Password Dialog */}
      <ForgotPasswordDialog
        open={forgotPasswordDialogOpen}
        onOpenChange={setForgotPasswordDialogOpen}
      />

      {/* Verify OTP Dialog */}
      <VerifyOtpDialog
        open={verifyOtpDialogOpen}
        onOpenChange={setVerifyOtpDialogOpen}
        email={loginData.email}
        context="registration"
        onVerificationSuccess={handleOtpVerificationSuccess}
      />
    </Dialog>
  );
}
