"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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { CheckCircle, Mail } from "lucide-react"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"

export default function LoginPage() {
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")
  const [successMessage, setSuccessMessage] = useState("")
  const [requiresVerification, setRequiresVerification] = useState(false)
  const router = useRouter()

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>, isLogin: boolean) => {
    event.preventDefault()
    setIsLoading(true)
    setError("")
    setSuccessMessage("")
    setRequiresVerification(false)

    const formData = new FormData(event.currentTarget)
    const email = formData.get("email") as string
    const password = formData.get("password") as string
    const name = formData.get("name") as string

    // Validate email domain for registration
    if (!isLogin && !email.toLowerCase().endsWith("@gmail.com") && !email.toLowerCase().endsWith("@g7aerospace.com.my")) {
      setError(
        "Registration is restricted to G7 Aerospace employees. Please use your @g7aerospace.com.my email address.",
      )
      setIsLoading(false)
      return
    }

    try {
      const endpoint = isLogin ? "/api/auth/login" : "/api/auth/register"
      const body = isLogin ? { email, password } : { email, password, name }

      const response = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      })

      const data = await response.json()

      if (response.ok) {
        if (isLogin) {
          router.push("/")
        } else {
          // Registration successful
          setSuccessMessage(data.message)
          setRequiresVerification(data.requiresVerification)
        }
      } else {
        setError(data.error || "Authentication failed")
        setRequiresVerification(data.requiresVerification || false)
      }
    } catch (error) {
      setError("Network error. Please try again.")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center justify-center items-center">
          <div className="flex items-center justify-center">
            <Avatar className="h-20 w-20 aspect-square rounded-lg flex items-center justify-center">
              <AvatarImage src="/G7AI_avatar_2_no_bg.png" className="w-full h-full"/>
              <AvatarFallback className="h-10 w-10 bg-primary aspect-square rounded-lg">
                <span className="font-bold text-primary-foreground">G7</span>
              </AvatarFallback>
            </Avatar>
          </div>  
          <CardTitle className="text-2xl" style={{pointerEvents: "none", userSelect: "none"}}>G7 Astrum</CardTitle>
          <CardDescription style={{pointerEvents: "none", userSelect: "none"}}>Your Intelligent Agent AI for Industrial Precision and Security</CardDescription>
        </CardHeader>
        <CardContent>
          {successMessage && (
            <Alert className="mb-4 border-green-200 bg-green-50">
              <CheckCircle className="h-4 w-4 text-green-600" />
              <AlertDescription className="text-green-800">
                <div className="space-y-2">
                  <p>{successMessage}</p>
                  {requiresVerification && (
                    <div className="flex items-center gap-2 text-sm">
                      <Mail className="h-4 w-4" />
                      <span>Check your email inbox and spam folder</span>
                    </div>
                  )}
                </div>
              </AlertDescription>
            </Alert>
          )}

          <Tabs defaultValue="login" className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="login" className="cursor-pointer">Login</TabsTrigger>
              <TabsTrigger value="register" className="cursor-pointer">Register</TabsTrigger>
            </TabsList>

            <TabsContent value="login">
              <form onSubmit={(e) => handleSubmit(e, true)} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="email">Email</Label>
                  <Input id="email" name="email" type="email" placeholder="your.name@g7aerospace.com.my" required />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="password">Password</Label>
                  <Input id="password" name="password" type="password" placeholder="Enter your password" required />
                </div>
                {error && !requiresVerification && (
                  <Alert variant="destructive">
                    <AlertDescription>{error}</AlertDescription>
                  </Alert>
                )}
                {error && requiresVerification && (
                  <Alert className="border-amber-200 bg-amber-50">
                    <Mail className="h-4 w-4 text-amber-600" />
                    <AlertDescription className="text-amber-800">{error}</AlertDescription>
                  </Alert>
                )}
                <Button type="submit" className="w-full cursor-pointer" disabled={isLoading}>
                  {isLoading ? "Signing in..." : "Sign in"}
                </Button>
              </form>
            </TabsContent>

            <TabsContent value="register">
              <form onSubmit={(e) => handleSubmit(e, false)} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="name">Full Name</Label>
                  <Input id="name" name="name" type="text" placeholder="Enter your full name" required />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="email">G7 Aerospace Email</Label>
                  <Input id="email" name="email" type="email" placeholder="your.name@g7aerospace.com.my" required />
                  <p className="text-xs text-muted-foreground">Only @g7aerospace.com.my email addresses are allowed</p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="password">Password</Label>
                  <Input 
                    id="password" 
                    name="password" 
                    type="password" 
                    placeholder="Create a strong password (min. 8 characters)" 
                    required 
                    minLength={8}
                  />
                </div>
                {error && (
                  <Alert variant="destructive">
                    <AlertDescription>{error}</AlertDescription>
                  </Alert>
                )}
                <Button type="submit" className="w-full cursor-pointer" disabled={isLoading}>
                  {isLoading ? "Creating account..." : "Create account"}
                </Button>
                <p className="text-xs text-center text-muted-foreground">
                  By registering, you agree to receive verification emails and account notifications.
                </p>
              </form>
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    </div>
  )
}
