"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 } from "@/components/ui/card"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { api } from "@/lib/api"
import { setAuthToken, setUser } from "@/lib/auth"
import type { AuthResponse } from "@/lib/types"
import Image from "next/image"
import { CircleX, Eye, EyeOff } from "lucide-react"

export default function LoginPage() {
  const router = useRouter()
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [error, setError] = useState("")
  const [loading, setLoading] = useState(false)
  const [showPassword, setShowPassword] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError("")
    setLoading(true)

    try {
      const response = await api.post<AuthResponse>("/auth/login", {
        email,
        password,
      })

      const { user, token } = response.data

      // Store auth data
      setAuthToken(token)
      setUser(user)

      // Redirect based on role
      if (user.role === "admin") {
        router.push("/dashboard")
      } else {
        router.push("/attendance")
      }
    } catch (err: any) {
      setError("Échec de la connexion. Veuillez vérifier vos identifiants.")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-background p-4">
      <Card className="w-full max-w-md border-border">
        <CardHeader className="space-y-1">
          <div className="flex justify-center">
            <Image src="/logo.png" alt="Logo" width={100} height={40} />
          </div>
          <CardDescription className="text-center text-muted-foreground">
            Entrez vos identifiants pour accéder au système
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            {error && (
            <Alert variant={"destructive"}>
              <CircleX size={4}/>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input
                id="email"
                type="email"
                placeholder="admin@school.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                disabled={loading}
                className="bg-background"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="password">Mot de passe</Label>
              <div className="relative">
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  placeholder="Entrez votre mot de passe"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  disabled={loading}
                  className="bg-background pr-10"
                />
                <Button
                  type="button"
                  variant="outline"
                  size="icon"
                  className="absolute right-1 top-1/2 -translate-y-1/2 border-none h-4 shadow-none hover:bg-white"
                  onClick={() => setShowPassword(!showPassword)}
                  disabled={loading}
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>

            <Button type="submit" className="w-full" disabled={loading}>
              {loading ? "Connexion en cours..." : "Se connecter"}
            </Button>
          </form>

          <div className="mt-6 text-center text-sm text-muted-foreground">
            <p>
              Développé par{" "}
              <a
                href="https://iyehah.com"
                target="_blank"
                rel="noopener noreferrer"
                className="text-primary hover:underline"
              >
                Iyehah
              </a>
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
