"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { useTranslations, useLocale } from "next-intl";
import { Link } from "@/i18n/navigation";
import { RoleType } from "@/lib/enums/RoleType";
import { loginSchema, LoginFormData } from "@/lib/validations/login";
import { normalizeEmail } from "@/lib/email";
import { setUserDataCookie, setRefreshTokenCookie } from "@/lib/cookies";
import { useLoginControllerLoginV1 } from "@/api/user/user-authentication/user-authentication";
import { subscriptionControllerGetSubscriptionStatusV1 } from "@/api/user/practitioner-subscription/practitioner-subscription";

const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '';

export default function LoginForm() {
  const t = useTranslations("login");
  const locale = useLocale();
  const [error, setError] = useState("");
  const [showPassword, setShowPassword] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormData>({
    resolver: yupResolver(loginSchema),
    defaultValues: {
      email: "",
      password: "",
    },
  });

  const { mutate: loginUser, isPending: isLoading } = useLoginControllerLoginV1({
    mutation: {
      onSuccess: async (response) => {
        if (response.data?.user) {
          // access_token is set as HttpOnly cookie by backend — no manual storage needed
          // Store refresh token for silent token refresh
          if (response.data.refresh_token) {
            setRefreshTokenCookie(response.data.refresh_token);
          }
          // Store user data in cookie
          // Normalize role to match RoleType enum (e.g. "admin" -> "Admin")
          const rawRole = response.data.user.role?.name || '';
          const role = rawRole.charAt(0).toUpperCase() + rawRole.slice(1);

          setUserDataCookie({
            id: response.data.user.uuid,
            role: role,
            name: response.data.user.name,
            email: response.data.user.email,
            subscription_type: response.data.subscription_type || 'individual',
            has_active_subscription: response.data.has_active_subscription,
            force_password_change: response.data.force_password_change ?? false,
            is_managed: response.data.is_managed ?? false,
          });
          // Role-based redirect with basePath and locale
          const buildPath = (path: string) => `${basePath}/${locale}${path}`;

          if (role === RoleType.ADMIN) {
            window.location.href = buildPath("/admin");
          } else if (role === RoleType.PRACTITIONERS) {
            const subscriptionType = response.data.subscription_type;
            if (response.data.is_managed) {
              // PM-invited therapist — covered by group plan, go straight to dashboard
              window.location.href = buildPath("/practitioner");
            } else if (subscriptionType === 'group' && response.data.has_active_subscription) {
              window.location.href = buildPath("/practice-manager/dashboard");
            } else {
              // Check subscription status before routing
              try {
                const statusRes = await subscriptionControllerGetSubscriptionStatusV1();
                const status = (statusRes as any)?.data?.status;
                if (status === 'none') {
                  // No subscription yet — send directly to the correct subscription page
                  const subPage = subscriptionType === 'group'
                    ? "/practice-manager/subscription"
                    : "/practitioner/subscription";
                  window.location.href = buildPath(subPage);
                } else {
                  // Active or trialing — go to dashboard
                  const dashboard = subscriptionType === 'group'
                    ? "/practice-manager/dashboard"
                    : "/practitioner";
                  window.location.href = buildPath(dashboard);
                }
              } catch {
                // Status check failed — fall back to dashboard and let layout handle it
                window.location.href = buildPath(subscriptionType === 'group' ? "/practice-manager/dashboard" : "/practitioner");
              }
            }
          } else if (role === RoleType.INDIVIDUALS) {
            window.location.href = buildPath("/individual");
          } else {
            // Invalid role - redirect to login
            window.location.href = buildPath("/login");
          }
        } else {
          setError(t("invalidCredentials"));
        }
      },
      onError: (err: any) => {
        // For 401 (wrong credentials), show generic message to prevent user enumeration
        // For other errors (account suspended, email unverified, etc.), show backend message
        if (err?.response?.status === 401) {
          setError(t("invalidCredentials"));
        } else {
          setError(err?.response?.data?.message || err?.message || t("invalidCredentials"));
        }
      },
    },
  });

  const onSubmit = (data: LoginFormData) => {
    loginUser({
      data: {
        username: normalizeEmail(data.email),
        password: data.password,
        device_name: "web",
        device_type: "web",
        device_id: `web-${Date.now()}`,
      },
    });
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="w-full space-y-5">
      {error && (
        <div className="p-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg">
          {error}
        </div>
      )}

      {/* Email Field */}
      <div className="space-y-2">
        <label htmlFor="email" className="block text-sm font-medium text-gray-800">
          {t("email")}
        </label>
        <div className="relative">
          <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
            <svg
              className="h-5 w-5 text-gray-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={1.5}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"
              />
            </svg>
          </div>
          <input
            id="email"
            type="email"
            {...register("email", {
              onChange: () => error && setError("")
            })}
            placeholder={t("emailPlaceholder")}
            disabled={isLoading}
            className={`w-full pl-12 pr-4 py-3.5 rounded-xl bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] transition border disabled:opacity-50 ${
              errors.email ? "border-red-500" : "border-gray-100"
            }`}
          />
        </div>
        {errors.email && (
          <p className="text-sm text-red-600">{errors.email.message}</p>
        )}
      </div>

      {/* Password Field */}
      <div className="space-y-2">
        <label htmlFor="password" className="block text-sm font-medium text-gray-800">
          {t("password")}
        </label>
        <div className="relative">
          <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
            <svg
              className="h-5 w-5 text-gray-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={1.5}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
              />
            </svg>
          </div>
          <input
            id="password"
            type={showPassword ? "text" : "password"}
            {...register("password", {
              onChange: () => error && setError("")
            })}
            placeholder={t("passwordPlaceholder")}
            disabled={isLoading}
            className={`w-full pl-12 pr-12 py-3.5 rounded-xl bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] transition border disabled:opacity-50 ${
              errors.password ? "border-red-500" : "border-gray-100"
            }`}
          />
          <button
            type="button"
            onClick={() => setShowPassword(!showPassword)}
            className="absolute inset-y-0 right-0 pr-4 flex items-center cursor-pointer"
          >
            {showPassword ? (
              <svg
                className="h-5 w-5 text-gray-400 hover:text-gray-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.5}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"
                />
              </svg>
            ) : (
              <svg
                className="h-5 w-5 text-gray-400 hover:text-gray-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.5}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"
                />
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                />
              </svg>
            )}
          </button>
        </div>
        {errors.password && (
          <p className="text-sm text-red-600">{errors.password.message}</p>
        )}
      </div>

      {/* Forgot Password Link */}
      <div className="flex justify-end">
        <Link
          href="/forgot-password"
          className="text-sm text-[#3B9EC9] hover:text-[#2D8AB5] font-medium"
        >
          {t("forgotPassword")}
        </Link>
      </div>

      {/* Submit Button */}
      <div className="pt-2">
        <button
          type="submit"
          disabled={isLoading}
          className="w-full py-4 px-4 bg-[#3B9EC9] hover:bg-[#2D8AB5] text-white font-medium rounded-full transition focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex items-center justify-center"
        >
          {isLoading ? (
            <>
              <svg
                className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
              >
                <circle
                  className="opacity-25"
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  strokeWidth="4"
                ></circle>
                <path
                  className="opacity-75"
                  fill="currentColor"
                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                ></path>
              </svg>
              {t("signIn")}...
            </>
          ) : (
            t("signIn")
          )}
        </button>
      </div>

      {/* Sign Up Link */}
      <p className="text-center text-sm text-gray-600 pt-2">
        {t("noAccount")}{" "}
        <Link href="/signup" className="font-semibold text-gray-900 hover:text-[#3B9EC9]">
          {t("signUp")}
        </Link>
      </p>
    </form>
  );
}
