"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/input-otp";
import { Heart, Eye, EyeOff, X, Loader2, CheckCircle2 } from "lucide-react";
import Link from "next/link";
import Image from "next/image";
import { useRouter, useSearchParams } from "next/navigation";
import { useAppTheme } from "@/components/ThemeProvider";
import { useAuth } from "@/hooks/useAuth";
import { registerSchema, verifyOtpSchema, type RegisterInput, type VerifyOtpInput } from "@/lib/schema/auth";
import { toast } from "sonner";

export default function Signup() {
  const { theme } = useAppTheme();
  const isDark = theme === "dark";
  const [showPassword, setShowPassword] = useState(false);
  const [showPassword2, setShowPassword2] = useState(false);
  const [step, setStep] = useState<"register" | "verify">("register");
  const [registeredEmail, setRegisteredEmail] = useState("");
  const [formData, setFormData] = useState<RegisterInput>({
    first_name: "",
    last_name: "",
    email: "",
    phone_number: "",
    password: "",
    password2: "",
  });
  const [otpData, setOtpData] = useState<VerifyOtpInput>({
    email: "",
    otp: "",
  });
  const [errors, setErrors] = useState<Partial<Record<keyof RegisterInput | keyof VerifyOtpInput, string>>>({});
  const router = useRouter();
  const searchParams = useSearchParams();
  const { register, verifyOtp, isAuthenticated, registerMutation, verifyOtpMutation, resendOtpMutation } = useAuth();

  // Redirect if already authenticated
  useEffect(() => {
    if (isAuthenticated) {
      const redirect = searchParams.get("redirect") || "/admin/dashboard";
      router.push(redirect);
    }
  }, [isAuthenticated, router, searchParams]);

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrors({});

    // Validate form
    const validation = registerSchema.safeParse(formData);
    if (!validation.success) {
      const fieldErrors: Partial<Record<keyof RegisterInput, string>> = {};
      validation.error.issues.forEach((err) => {
        if (err.path[0]) {
          fieldErrors[err.path[0] as keyof RegisterInput] = err.message;
        }
      });
      setErrors(fieldErrors);
      return;
    }

    try {
      const result = await register(formData);
      
      // If registration is successful, redirect to login page with verify parameter
      toast.success("Registration successful! Please check your email for OTP verification.");
      // Redirect to login page with verify step
      router.push(`/login?verify=true&email=${encodeURIComponent(formData.email)}`);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "Registration failed. Please try again.";
      
      // If OTP sending failed, don't show OTP verification - just show error
      if (errorMessage.toLowerCase().includes("failed to send") || 
          errorMessage.toLowerCase().includes("failed to send otp")) {
        toast.error("Registration failed: OTP could not be sent. Please try again later or contact support.");
        setErrors({});
        return;
      }
      
      toast.error(errorMessage);
      // Don't set field errors for server errors, only show toast
      setErrors({});
    }
  };

  const handleVerifyOtp = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrors({});

    // Validate OTP
    const validation = verifyOtpSchema.safeParse(otpData);
    if (!validation.success) {
      const fieldErrors: Partial<Record<keyof VerifyOtpInput, string>> = {};
      validation.error.issues.forEach((err) => {
        if (err.path[0]) {
          fieldErrors[err.path[0] as keyof VerifyOtpInput] = err.message;
        }
      });
      setErrors(fieldErrors);
      return;
    }

    try {
      const result = await verifyOtp(otpData);
      
      // If verification is successful (no error thrown), show success and redirect
      toast.success("Email verified successfully! Redirecting to login...");
      
      // Redirect to login page after OTP verification with email pre-filled
      setTimeout(() => {
        router.push(`/login?email=${encodeURIComponent(otpData.email)}`);
      }, 1500);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "OTP verification failed. Please try again.";
      toast.error(errorMessage);
      // Don't set field errors for server errors, only show toast
      setErrors({});
    }
  };

  const handleResendOtp = async () => {
    try {
      await resendOtpMutation.mutateAsync({ email: registeredEmail, context: "registration" });
      toast.success("OTP resent successfully! Please check your email.");
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "Failed to resend OTP. Please try again.";
      toast.error(errorMessage);
    }
  };

  const handleChange = (field: keyof RegisterInput, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    // Clear error when user starts typing
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: undefined }));
    }
  };

  const handleOtpChange = (field: keyof VerifyOtpInput, value: string) => {
    setOtpData((prev) => ({ ...prev, [field]: value }));
    // Clear error when user starts typing
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: undefined }));
    }
  };

  return (
    <div className="min-h-screen relative flex items-center justify-center px-4 py-12">
      {/* Background Image */}
      <div className="absolute inset-0 z-0">
        <Image
          src="/woman.jpg"
          alt="Therapy and counseling session with African American clients"
          fill
          className="object-cover object-center"
          priority
          sizes="100vw"
        />
        {/* Overlay for better readability */}
        <div className="absolute inset-0 bg-black/20"></div>
      </div>

      {/* Branding - Top Left */}
      <div className="absolute top-8 left-8 flex items-center gap-3 z-30">
        <Heart className="w-6 h-6 text-white" fill="white" />
        <span className="text-white text-xl font-semibold">Attune Heart Therapy</span>
      </div>

      {/* Centered White Card - Signup Form */}
      <div className={`relative z-20 w-full max-w-md rounded-2xl shadow-2xl p-8 ${isDark ? 'bg-gray-800 border border-gray-700' : 'bg-white'}`}>
        {/* Header with Close Button */}
        <div className="flex items-start justify-between mb-2">
          <div className="flex-1">
            {/* Heading */}
            <h1 className="text-3xl font-bold bg-gradient-to-r from-rose-600 via-pink-600 to-rose-600 bg-clip-text text-transparent mb-2">
              {step === "register" ? "Create an account" : "Verify your email"}
            </h1>
            {/* Login Prompt */}
            {step === "register" && (
              <p className={`mb-6 ${isDark ? 'text-gray-400' : 'text-gray-600'}`}>
                Already have an account?{" "}
                <Link href="/login" className={`underline font-medium ${isDark ? 'text-blue-400 hover:text-blue-300' : 'text-blue-600 hover:text-blue-700'}`}>
                  Log in
                </Link>
              </p>
            )}
            {step === "verify" && (
              <p className={`mb-6 ${isDark ? 'text-gray-400' : 'text-gray-600'}`}>
                We've sent a verification code to <strong>{registeredEmail}</strong>
              </p>
            )}
          </div>
          {/* Close Button */}
          <Button
            onClick={() => router.back()}
            variant="ghost"
            size="icon"
            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>

        {step === "register" ? (
          /* Registration Form */
          <form className="space-y-4" onSubmit={handleRegister}>
            {/* First Name Field */}
            <div className="space-y-2">
              <label htmlFor="firstName" className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                First Name *
              </label>
              <Input
                id="firstName"
                type="text"
                placeholder="John"
                value={formData.first_name}
                onChange={(e) => handleChange("first_name", e.target.value)}
                className={`h-11 ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900'} ${errors.first_name ? 'border-red-500' : ''}`}
                required
              />
              {errors.first_name && (
                <p className="text-sm text-red-500">{errors.first_name}</p>
              )}
            </div>

            {/* Last Name Field */}
            <div className="space-y-2">
              <label htmlFor="lastName" className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                Last Name *
              </label>
              <Input
                id="lastName"
                type="text"
                placeholder="Doe"
                value={formData.last_name}
                onChange={(e) => handleChange("last_name", e.target.value)}
                className={`h-11 ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900'} ${errors.last_name ? 'border-red-500' : ''}`}
                required
              />
              {errors.last_name && (
                <p className="text-sm text-red-500">{errors.last_name}</p>
              )}
            </div>

            {/* Email Field */}
            <div className="space-y-2">
              <label htmlFor="email" className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                Email address *
              </label>
              <Input
                id="email"
                type="email"
                placeholder="Email address"
                value={formData.email}
                onChange={(e) => handleChange("email", e.target.value)}
                className={`h-11 ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900'} ${errors.email ? 'border-red-500' : ''}`}
                required
              />
            </div>

            {/* Phone Field */}
            <div className="space-y-2">
              <label htmlFor="phone" className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                Phone Number (Optional)
              </label>
              <Input
                id="phone"
                type="tel"
                placeholder="+1 (555) 123-4567"
                value={formData.phone_number || ""}
                onChange={(e) => handleChange("phone_number", e.target.value)}
                className={`h-11 ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900'}`}
              />
            </div>

            {/* Password Field */}
            <div className="space-y-2">
              <label htmlFor="password" className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                Password *
              </label>
              <div className="relative">
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  placeholder="Password (min 8 characters)"
                  value={formData.password}
                  onChange={(e) => handleChange("password", e.target.value)}
                  className={`h-11 pr-12 ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900'} ${errors.password ? 'border-red-500' : ''}`}
                  required
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  onClick={() => setShowPassword(!showPassword)}
                  className={`absolute 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-5 h-5" />
                  ) : (
                    <Eye className="w-5 h-5" />
                  )}
                </Button>
              </div>
              {errors.password && (
                <p className="text-sm text-red-500">{errors.password}</p>
              )}
            </div>

            {/* Confirm Password Field */}
            <div className="space-y-2">
              <label htmlFor="password2" className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                Confirm Password *
              </label>
              <div className="relative">
                <Input
                  id="password2"
                  type={showPassword2 ? "text" : "password"}
                  placeholder="Confirm password"
                  value={formData.password2}
                  onChange={(e) => handleChange("password2", e.target.value)}
                  className={`h-11 pr-12 ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900'} ${errors.password2 ? 'border-red-500' : ''}`}
                  required
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  onClick={() => setShowPassword2(!showPassword2)}
                  className={`absolute 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={showPassword2 ? "Hide password" : "Show password"}
                >
                  {showPassword2 ? (
                    <EyeOff className="w-5 h-5" />
                  ) : (
                    <Eye className="w-5 h-5" />
                  )}
                </Button>
              </div>
              {errors.password2 && (
                <p className="text-sm text-red-500">{errors.password2}</p>
              )}
            </div>

            {/* Submit Button */}
            <Button
              type="submit"
              disabled={registerMutation.isPending}
              className="w-full h-12 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-6"
            >
              {registerMutation.isPending ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Creating account...
                </>
              ) : (
                "Sign up"
              )}
            </Button>
          </form>
        ) : (
          /* OTP Verification Form */
          <form className="space-y-6" onSubmit={handleVerifyOtp}>
            <div className={`p-4 rounded-lg border ${isDark ? 'bg-blue-900/20 border-blue-800' : 'bg-blue-50 border-blue-200'}`}>
              <div className="flex items-start gap-3">
                <CheckCircle2 className={`w-5 h-5 mt-0.5 ${isDark ? 'text-blue-400' : 'text-blue-600'}`} />
                <div>
                  <p className={`text-sm font-medium ${isDark ? 'text-blue-200' : 'text-blue-900'}`}>
                    Check your email
                  </p>
                  <p className={`text-sm mt-1 ${isDark ? 'text-blue-300' : 'text-blue-700'}`}>
                    We've sent a 6-digit verification code to your email address.
                  </p>
                </div>
              </div>
            </div>

            {/* OTP Field */}
            <div className="space-y-2">
              <label className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                Verification Code *
              </label>
              <div className="flex justify-center">
                <InputOTP
                  maxLength={6}
                  value={otpData.otp}
                  onChange={(value) => handleOtpChange("otp", value)}
                  aria-invalid={!!errors.otp}
                >
                  <InputOTPGroup>
                    <InputOTPSlot index={0} />
                    <InputOTPSlot index={1} />
                    <InputOTPSlot index={2} />
                    <InputOTPSlot index={3} />
                    <InputOTPSlot index={4} />
                    <InputOTPSlot index={5} />
                  </InputOTPGroup>
                </InputOTP>
              </div>
            </div>

            {/* Resend OTP */}
            <div className="text-center">
              <button
                type="button"
                onClick={handleResendOtp}
                disabled={resendOtpMutation.isPending}
                className={`text-sm font-medium ${isDark ? 'text-blue-400 hover:text-blue-300' : 'text-blue-600 hover:text-blue-700'} disabled:opacity-50 disabled:cursor-not-allowed`}
              >
                {resendOtpMutation.isPending ? "Sending..." : "Didn't receive the code? Resend"}
              </button>
            </div>

            {/* Submit Button */}
            <Button
              type="submit"
              disabled={verifyOtpMutation.isPending}
              className="w-full h-12 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"
            >
              {verifyOtpMutation.isPending ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Verifying...
                </>
              ) : (
                "Verify Email"
              )}
            </Button>

            {/* Back to registration */}
            <div className="text-center">
              <button
                type="button"
                onClick={() => {
                  setStep("register");
                  setOtpData({ email: "", otp: "" });
                }}
                className={`text-sm font-medium ${isDark ? 'text-gray-400 hover:text-gray-300' : 'text-gray-600 hover:text-gray-700'}`}
              >
                ← Back to registration
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

