"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"
import { Eye, EyeOff, Loader2, Shield } from "lucide-react"
import { useAuth } from "@/contexts/auth-context"
import { loginUser } from "@/components/apis/authenticationHandler"
import { setTokens } from "@/components/apis/authApiClients"

interface SignInFormProps {
  onToggleMode?: () => void
}

export function SignInForm({ }: SignInFormProps) {
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")
  const [formData, setFormData] = useState({
    email: "",
    password: "",
  })
  
  const router = useRouter()
  const { setUserFromApi } = useAuth()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError("")
    
    if (!formData.email || !formData.password) {
      setError("Please fill in all required fields.")
      return
    }
    
    setIsLoading(true)
    try {
      const response = await loginUser(formData.email, formData.password)
      
      if (response && response.data && response.data.tokens && response.data.user) {
        setTokens(response.data.tokens.accessToken, response.data.tokens.refreshToken)
        // Set user in context so header updates immediately
        setUserFromApi(response.data.user)
        // Persist for refresh
        localStorage.setItem("codenuk_user", JSON.stringify(response.data.user))
        
        // Redirect based on user role
        if (response.data.user.role === 'admin') {
          router.push("/admin")
        } else {
          router.push("/")
        }
      } else {
        setError("Invalid response from server. Please try again.")
      }
    } catch (err: unknown) {
      console.error('Login error:', err)
      
      // Handle different types of errors
      const error = err as { response?: { data?: { message?: string; error?: string } }; message?: string };
      if (error.response?.data?.message) {
        setError(error.response.data.message)
      } else if (error.response?.data?.error) {
        setError(error.response.data.error)
      } else if (error.message) {
        setError(error.message)
      } else {
        setError("An error occurred during login. Please try again.")
      }
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="w-full">
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="email" className="text-white text-sm">Email</Label>
          <Input
            id="email"
            type="email"
            placeholder="Enter your email"
            value={formData.email}
            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
            required
            className="h-11 bg-white/5 border-white/10 text-white placeholder:text-white/40 focus:border-orange-400/50 focus:ring-orange-400/20 transition-all duration-200"
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="password" className="text-white text-sm">Password</Label>
          <div className="relative">
            <Input
              id="password"
              type={showPassword ? "text" : "password"}
              placeholder="Enter your password"
              value={formData.password}
              onChange={(e) => setFormData({ ...formData, password: e.target.value })}
              required
              className="h-11 bg-white/5 border-white/10 text-white placeholder:text-white/40 focus:border-orange-400/50 focus:ring-orange-400/20 transition-all duration-200 pr-12"
            />
            <Button
              type="button"
              variant="ghost"
              size="sm"
              className="absolute right-0 top-0 h-full px-3 py-2 text-white/60 hover:text-white hover:bg-white/5 transition-colors"
              onClick={() => setShowPassword(!showPassword)}
            >
              {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </Button>
          </div>
        </div>
        
        {error && (
          <div className="text-red-300 text-sm text-center bg-red-900/20 p-3 rounded-md border border-red-500/30">
            <div className="flex items-center justify-center space-x-2">
              <Shield className="h-4 w-4" />
              <span>{error}</span>
            </div>
          </div>
        )}
        
        <Button 
          type="submit" 
          className="w-full h-11 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 shadow-lg hover:shadow-orange-500/25" 
          disabled={isLoading}
        >
          {isLoading ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Signing In...
            </>
          ) : (
            "Sign In"
          )}
        </Button>
      </form>
    </div>
  )
}
