/* eslint-disable @typescript-eslint/no-explicit-any */
import { Card, CardContent } from "@/components/ui/card";
import { Mail, Lock } from "lucide-react";
import { Link, useLocation } from "react-router";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

import { useForm, type SubmitHandler } from "react-hook-form";
import { useCallback, useState } from "react";
import { loginApi } from "@/api/login";
import { useAccountRepo } from "@/repository/account";
import { useAuth } from "@/store/auth";

interface LoginForm {
  email: string;
  password: string;
}

export default function LoginPage() {
  const {
    register,
    reset,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginForm>();

  const [isLoading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  const repo = useAccountRepo();

  const location = useLocation();

  const updateActiveAccount = useAuth((state) => state.updateActiveAccount);

  const onSubmit: SubmitHandler<LoginForm> = useCallback(
    async (data) => {
      setLoading(true);
      setError("");
      setSuccess("");

      try {
        const response = await loginApi({
          email: data.email,
          password: data.password,
        });

        const account = await repo.save({
          accountId: response.id,
          label: response.full_name,
          email: response.email,
          profilePicture: response.profile_picture,
          access: response.access,
          refresh: response.refresh,
        });

        setSuccess("You have successfully logged in");
        reset();

        await updateActiveAccount(account);
      } catch (err: any) {
        console.log(err);
        setError(
          "Failed to create account. " +
            (err.message ?? "Unexpected error happened"),
        );
      } finally {
        setLoading(false);
      }
    },
    [repo, reset, updateActiveAccount],
  );

  return (
    <div className="relative z-10 flex items-center justify-center min-h-screen">
      <Card className="sm:w-96 sm:min-w-96 sm:max-w-96 sm:min-h-auto p-3 min-h-screen w-full min-w-full shadow-lg bg-white/65 dark:bg-black/70 backdrop-blur-md">
        <div className="flex flex-col items-center pt-16 sm:pt-0">
          <img
            src="/icon.png"
            alt="icon"
            className="w-16 h-16 mb-4 mt-2 sm:mt-6"
          />

          <div className="px-4 sm:mt-4 mt-8">
            <h2 className="text-2xl font-bold text-gray-800 dark:text-gray-200 text-left w-full">
              Sign In
            </h2>
            <h4 className="text-base mb-3 text-gray-400 dark:text-gray-500 text-left">
              Enter your credentials to access home services and tools.
            </h4>
          </div>

          <CardContent className="w-full space-y-4">
            <form onSubmit={handleSubmit(onSubmit)}>
              <div className="mb-4">
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 dark:text-gray-600 w-4 h-4" />
                  <Input
                    id="email"
                    type="email"
                    placeholder="Email Address"
                    className="pl-10"
                    {...register("email", {
                      required: true,
                      pattern: {
                        value: /\S+@\S+\.\S+/,
                        message: "Invalid email",
                      },
                    })}
                    aria-invalid={errors.email ? "true" : "false"}
                  />
                </div>
                {!!errors.email && (
                  <p className="text-red-500">
                    {errors.email.message ?? "Email is required"}
                  </p>
                )}
              </div>

              <div className="mb-4">
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 dark:text-gray-600 w-4 h-4" />
                  <Input
                    id="password"
                    type="password"
                    placeholder="Password"
                    className="pl-10"
                    {...register("password", {
                      required: true,
                    })}
                    aria-invalid={errors.password ? "true" : "false"}
                  />
                </div>
                {!!errors.password && (
                  <p className="text-red-500">
                    {errors.password.message ?? "Password is required"}
                  </p>
                )}
              </div>

              {success.length > 0 && (
                <div className="border border-green-400 p-2 rounded bg-green-200 text-sm">
                  {success}
                </div>
              )}

              {error.length > 0 && (
                <div className="border border-red-400 p-2 rounded bg-red-200 dark:border-red-600 dark:bg-red-400 text-sm">
                  {error}
                </div>
              )}

              <Button
                className="w-full mt-2 mb-4"
                type="submit"
                loading={isLoading}
              >
                Log In
              </Button>
              <div className="text-sm text-center text-gray-600">
                Don't have an account?{" "}
                <Link
                  to="/auth/register"
                  state={location.state}
                  className="text-blue-600 hover:underline"
                >
                  Register
                </Link>
              </div>
            </form>
          </CardContent>
        </div>
      </Card>
    </div>
  );
}
