"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useAuth } from "@/hooks/use-auth";
import { loginStart, loginSuccess, loginFailure } from "@/lib/store/slices/auth-slice";
import { useAppDispatch } from "@/hooks/use-redux";

export function LoginExample() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { loading, error, clearError } = useAuth();

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      dispatch(loginStart());
      clearError();

      // Example: Replace this with your actual authentication API call
      const response = await fetch("/api/auth/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ email, password }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || "Login failed");
      }

      const { user, accessToken, refreshToken } = await response.json();

      // Store tokens in localStorage
      localStorage.setItem("attendant_token", accessToken);
      if (refreshToken) {
        localStorage.setItem("attendant_refresh_token", refreshToken);
      }

      // Store user data
      localStorage.setItem("user_data", JSON.stringify(user));

      // Update Redux state
      dispatch(
        loginSuccess({
          user,
          accessToken,
          refreshToken,
        }),
      );

      // Redirect to dashboard
      router.push("/dashboard");
    } catch (error) {
      const message = error instanceof Error ? error.message : "An unexpected error occurred";
      dispatch(loginFailure(message));
    }
  };

  return (
    <Card className="mx-auto w-full max-w-md">
      <CardHeader>
        <CardTitle>Login</CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleLogin} className="space-y-4">
          {error && (
            <Alert variant="destructive">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          <div className="space-y-2">
            <Input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} required />
          </div>

          <div className="space-y-2">
            <Input
              type="password"
              placeholder="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </div>

          <Button type="submit" className="w-full" disabled={loading}>
            {loading ? "Logging in..." : "Login"}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}
