"use client";

import { useFormStatus } from 'react-dom';
import { loginAction } from '@/lib/actions/auth.actions';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Terminal, LogIn, Loader2 } from "lucide-react";
import { useEffect, useActionState } from 'react'; // Updated import
import { useToast } from '@/hooks/use-toast';


function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <Button type="submit" className="w-full" disabled={pending}>
      {pending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <LogIn className="mr-2 h-4 w-4" />}
      Sign In
    </Button>
  );
}

export default function LoginForm() {
  const initialState = { message: null };
  // Updated to useActionState
  const [state, dispatch, isPending] = useActionState(loginAction, initialState); 
  const { toast } = useToast();

  useEffect(() => {
    if (state?.message && !state.message.includes("Invalid fields")) { // Don't toast form validation errors handled inline
       toast({
        variant: "destructive",
        title: "Login Failed",
        description: state.message,
      });
    }
  }, [state, toast]);


  return (
    <form action={dispatch} className="space-y-6">
      <div className="space-y-2">
        <Label htmlFor="username">Username</Label>
        <Input
          id="username"
          name="username"
          type="text"
          placeholder="admin"
          required
          autoComplete="username"
          className="text-base"
        />
      </div>
      <div className="space-y-2">
        <Label htmlFor="password">Password</Label>
        <Input
          id="password"
          name="password"
          type="password"
          placeholder="••••••••"
          required
          autoComplete="current-password"
          className="text-base"
        />
      </div>
       {state?.message && state.message.includes("Invalid fields") && (
          <Alert variant="destructive" className="mt-4">
            <Terminal className="h-4 w-4" />
            <AlertTitle>Error</AlertTitle>
            <AlertDescription>{state.message}</AlertDescription>
          </Alert>
        )}
      <SubmitButton />
    </form>
  );
}
