"use client"

import type React from "react"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
// Removed unused Card components
import { Eye, EyeOff, Loader2, User, Mail, Lock, Shield } from "lucide-react"
import { registerUser } from "../apis/authenticationHandler"

interface SignUpFormProps {
  onSignUpSuccess?: () => void
  onToggleMode?: () => void
}

export function SignUpForm({ onSignUpSuccess }: SignUpFormProps) {
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")
  const [formData, setFormData] = useState({
    username: "",
    first_name: "",
    last_name: "",
    email: "",
    password: "",
    confirmPassword: "",
    role: "user" // default role, adjust as needed
  })
  
  // const { signup } = useAuth() // Unused variable
  const router = useRouter()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError("")
    
    // Validation
    if (formData.password !== formData.confirmPassword) {
      setError("Passwords don't match")
      return
    }
    if (!formData.username || !formData.first_name || !formData.last_name || !formData.email || !formData.password) {
      setError("Please fill in all required fields.")
      return
    }
    
    // Password strength validation
    if (formData.password.length < 8) {
      setError("Password must be at least 8 characters long")
      return
    }
    
    setIsLoading(true)
    try {
      const response = await registerUser({
        username: formData.username,
        email: formData.email,
        password: formData.password,
        first_name: formData.first_name,
        last_name: formData.last_name,
        role: formData.role
      })
      
      if (response.success) {
        // Call success callback if provided
        if (onSignUpSuccess) {
          onSignUpSuccess()
        } else {
          // Default behavior - redirect to signin with message
          if (typeof window !== 'undefined') {
            router.push("/signin?message=Account created successfully! Please check your email to verify your account.")
          }
        }
      } else {
        setError(response.message || "Failed to create account. Please try again.")
      }
    } catch (err: unknown) {
      console.error('Signup error:', err)
      
      // The authentication handler now properly extracts error messages from server responses
      if (err instanceof Error) {
        setError(err.message)
      } else {
        setError("An error occurred during registration. Please try again.")
      }
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="w-full max-w-md">
      <form onSubmit={handleSubmit} className="space-y-4">
        {/* Personal Information Section */}
        <div className="space-y-3">
          <div className="flex items-center space-x-2 mb-2">
            <User className="h-4 w-4 text-orange-400" />
            <h3 className="text-base font-semibold text-white">Personal Information</h3>
          </div>
          
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <Label htmlFor="first_name" className="text-white/80 text-xs font-medium">First Name</Label>
              <Input
                id="first_name"
                type="text"
                placeholder="John"
                value={formData.first_name}
                onChange={(e) => setFormData({ ...formData, first_name: e.target.value })}
                required
                className="h-10 bg-white/5 border-white/10 text-white placeholder:text-white/30 focus:border-orange-400/50 focus:ring-orange-400/20 transition-all duration-200 text-sm"
              />
            </div>
            <div className="space-y-1">
              <Label htmlFor="last_name" className="text-white/80 text-xs font-medium">Last Name</Label>
              <Input
                id="last_name"
                type="text"
                placeholder="Doe"
                value={formData.last_name}
                onChange={(e) => setFormData({ ...formData, last_name: e.target.value })}
                required
                className="h-10 bg-white/5 border-white/10 text-white placeholder:text-white/30 focus:border-orange-400/50 focus:ring-orange-400/20 transition-all duration-200 text-sm"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <Label htmlFor="username" className="text-white/80 text-xs font-medium">Username</Label>
              <Input
                id="username"
                type="text"
                placeholder="johndoe123"
                value={formData.username}
                onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                required
                className="h-10 bg-white/5 border-white/10 text-white placeholder:text-white/30 focus:border-orange-400/50 focus:ring-orange-400/20 transition-all duration-200 text-sm"
              />
            </div>
            <div className="space-y-1">
              <Label htmlFor="role" className="text-white/80 text-xs font-medium">Role</Label>
              <Input
                id="role"
                type="text"
                placeholder="user"
                value={formData.role}
                onChange={(e) => setFormData({ ...formData, role: e.target.value })}
                required
                className="h-10 bg-white/5 border-white/10 text-white placeholder:text-white/30 focus:border-orange-400/50 focus:ring-orange-400/20 transition-all duration-200 text-sm"
              />
            </div>
          </div>
        </div>

        {/* Contact Information Section */}
        <div className="space-y-3">
          <div className="flex items-center space-x-2 mb-2">
            <Mail className="h-4 w-4 text-orange-400" />
            <h3 className="text-base font-semibold text-white">Contact Information</h3>
          </div>
          
          <div className="space-y-1">
            <Label htmlFor="email" className="text-white/80 text-xs font-medium">Email Address</Label>
            <Input
              id="email"
              type="email"
              placeholder="john.doe@example.com"
              value={formData.email}
              onChange={(e) => setFormData({ ...formData, email: e.target.value })}
              required
              className="h-10 bg-white/5 border-white/10 text-white placeholder:text-white/30 focus:border-orange-400/50 focus:ring-orange-400/20 transition-all duration-200 text-sm"
            />
          </div>
        </div>

        {/* Security Section */}
        <div className="space-y-3">
          <div className="flex items-center space-x-2 mb-2">
            <Lock className="h-4 w-4 text-orange-400" />
            <h3 className="text-base font-semibold text-white">Security</h3>
          </div>
          
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <Label htmlFor="password" className="text-white/80 text-xs font-medium">Password</Label>
              <div className="relative">
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  placeholder="Password"
                  value={formData.password}
                  onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                  required
                  className="h-10 bg-white/5 border-white/10 text-white placeholder:text-white/30 focus:border-orange-400/50 focus:ring-orange-400/20 transition-all duration-200 text-sm pr-10"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="absolute right-0 top-0 h-full px-2 py-1 text-white/60 hover:text-white hover:bg-white/5 transition-colors"
                  onClick={() => setShowPassword(!showPassword)}
                >
                  {showPassword ? <EyeOff className="h-3 w-3" /> : <Eye className="h-3 w-3" />}
                </Button>
              </div>
            </div>

            <div className="space-y-1">
              <Label htmlFor="confirmPassword" className="text-white/80 text-xs font-medium">Confirm</Label>
              <div className="relative">
                <Input
                  id="confirmPassword"
                  type={showConfirmPassword ? "text" : "password"}
                  placeholder="Confirm"
                  value={formData.confirmPassword}
                  onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
                  required
                  className="h-10 bg-white/5 border-white/10 text-white placeholder:text-white/30 focus:border-orange-400/50 focus:ring-orange-400/20 transition-all duration-200 text-sm pr-10"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="absolute right-0 top-0 h-full px-2 py-1 text-white/60 hover:text-white hover:bg-white/5 transition-colors"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                >
                  {showConfirmPassword ? <EyeOff className="h-3 w-3" /> : <Eye className="h-3 w-3" />}
                </Button>
              </div>
            </div>
          </div>
        </div>
        
        {error && (
          <div className="text-red-300 text-xs text-center bg-red-900/20 p-3 rounded-md border border-red-500/30">
            <div className="flex items-center justify-center space-x-1">
              <Shield className="h-3 w-3" />
              <span>{error}</span>
            </div>
          </div>
        )}
        
        <Button 
          type="submit" 
          className="w-full h-10 cursor-pointer bg-gradient-to-r from-orange-500 to-orange-600 text-white hover:from-orange-600 hover:to-orange-700 transition-all duration-200 font-semibold text-sm shadow-lg hover:shadow-orange-500/25" 
          disabled={isLoading}
        >
          {isLoading ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Creating Account...
            </>
          ) : (
            "Create Account"
          )}
        </Button>
      </form>
    </div>
  )
}