"use client";
import Button from "@/components/ui/button/Button";
import { EyeCloseIcon, EyeIcon } from "@/icons";
import React, { useState } from "react";
import Input from "../form/input/InputField";
import Label from "../form/Label";
import { useRouter, useSearchParams } from "next/navigation";
import { BASE_URL } from "@/api/config";
import { toast } from "react-hot-toast";
import { useUser } from "@/context/UserContext";
import { fetchWrapper } from "@/api/fetchWrapper";

export default function SignInForm() {
  const { refetchUser } = useUser();
  const router = useRouter();
  const searchParams = useSearchParams();
  const next = searchParams.get("next");
  const [showPassword, setShowPassword] = useState(false);
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError("");
    setLoading(true);

    try {
      const response = await fetchWrapper(`${BASE_URL}/api/auth/login/`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include",
        body: JSON.stringify({ username, password }),
      });

      if (response.ok) {
        toast.success("Login successful!");
        router.push(next || "/");
        refetchUser();
      } else {
        const errorData = await response.json();
        setError(errorData.detail || "Invalid username or password");
      }
    } catch (error) {
      setError("An unexpected error occurred. Please try again.");
      console.error("Login error:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col flex-1 w-full lg:w-1/2">
      <div className="w-full max-w-md mx-auto mb-5 sm:pt-10">
        {/* <SmartLink
          href="/"
          className="inline-flex items-center text-sm text-gray-500 transition-colors hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
        >
          <ChevronLeftIcon />
          Back to dashboard
        </SmartLink> */}
      </div>
      <div className="flex flex-col justify-center flex-1 w-full max-w-md mx-auto">
        <div>
          <div className="mb-5 sm:mb-8">
            <h1 className="mb-2 font-semibold text-gray-800 text-title-sm dark:text-white/90 sm:text-title-md">
              ورود
            </h1>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              لطفاً اطلاعات حساب کاربری خود را وارد کنید.
            </p>
          </div>

          <form onSubmit={handleSubmit}>
            <div className="space-y-6">
              <div>
                <Label>
                  نام کاربری <span className="text-error-500">*</span>{" "}
                </Label>
                <Input
                  placeholder="نام کاربری خود را وارد کنید"
                  type="text"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                />
              </div>
              <div>
                <Label>
                  رمز عبور <span className="text-error-500">*</span>{" "}
                </Label>
                <div className="relative">
                  <Input
                    type={showPassword ? "text" : "password"}
                    placeholder="رمز عبور خود را وارد کنید"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                  <span
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute z-30 -translate-y-1/2 cursor-pointer right-4 top-1/2"
                  >
                    {showPassword ? (
                      <EyeIcon className="fill-gray-500 dark:fill-gray-400" />
                    ) : (
                      <EyeCloseIcon className="fill-gray-500 dark:fill-gray-400" />
                    )}
                  </span>
                </div>
              </div>
              {error && (
                <div className="p-3 text-sm text-center text-white rounded-lg bg-error-500">
                  {error}
                </div>
              )}
              <div>
                <Button className="w-full" size="sm" disabled={loading}>
                  {loading ? "ورود..." : "ورود"}
                </Button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
