"use client";

import { useState } from "react";
import {
  Eye,
  EyeOff,
  Info,
  Loader2,
  LockKeyhole,
  ShieldCheck,
} from "lucide-react";
import { toast } from "react-toastify";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { apiRequest, apiUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { useAuth } from "@/lib/auth-context";
import { useLanguage } from "@/lib/i18n";

type ValidationErrors = Record<string, string[]>;

type PasswordForm = {
  password: string;
  new_password: string;
  new_password_confirmation: string;
};

type PasswordResponse = {
  statusCode: number;
  success: boolean;
  data: ValidationErrors | "" | [];
  message: string;
  message_hi?: string;
};

const emptyPasswordForm: PasswordForm = {
  password: "",
  new_password: "",
  new_password_confirmation: "",
};

function getErrors(data: PasswordResponse["data"]) {
  if (!data || Array.isArray(data) || typeof data !== "object") {
    return {};
  }

  return data as ValidationErrors;
}

function firstError(errors: ValidationErrors, field: string) {
  return errors[field]?.[0];
}

function FieldError({ message }: { message?: string }) {
  if (!message) return null;

  return <p className="mt-2 text-xs font-semibold text-red-600">{message}</p>;
}

export function ChangePasswordPage() {
  const { token } = useAuth();
  const { t } = useLanguage();
  const [isSaving, setIsSaving] = useState(false);
  const [errors, setErrors] = useState<ValidationErrors>({});
  const [form, setForm] = useState<PasswordForm>(emptyPasswordForm);
  const [visiblePasswords, setVisiblePasswords] = useState<
    Record<keyof PasswordForm, boolean>
  >({
    password: false,
    new_password: false,
    new_password_confirmation: false,
  });

  const activeToken =
    token ||
    (typeof window !== "undefined" ? localStorage.getItem("auth_token") : null);

  const passwordRules = [
    {
      label: t("register.ruleLength"),
      passed: form.new_password.length >= 8,
    },
    {
      label: t("register.ruleUppercase"),
      passed: /[A-Z]/.test(form.new_password),
    },
    {
      label: t("register.ruleNumber"),
      passed: /\d/.test(form.new_password),
    },
    {
      label: t("register.ruleSpecial"),
      passed: /[^A-Za-z0-9]/.test(form.new_password),
    },
  ];

  const setField = (field: keyof PasswordForm, value: string) => {
    setForm((current) => ({ ...current, [field]: value }));
    setErrors((current) => ({ ...current, [field]: [] }));
  };

  const togglePasswordVisibility = (field: keyof PasswordForm) => {
    setVisiblePasswords((current) => ({
      ...current,
      [field]: !current[field],
    }));
  };

  const submitPassword = async () => {
    setIsSaving(true);
    setErrors({});

    try {
      const response = await apiRequest(apiUrl("/profile/change-password"), {
        method: "POST",
        headers: {
          Authorization: `Bearer ${activeToken || ""}`,
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(form),
      });
      const result = (await response.json()) as PasswordResponse;

      if (!response.ok || !result.success) {
        setErrors(getErrors(result.data));
        toast.error(getLocalizedApiMessage(result, "Password change failed."));
        return;
      }

      toast.success(
        getLocalizedApiMessage(result, "Password changed successfully."),
      );
      setForm(emptyPasswordForm);
    } catch {
      toast.error("Unable to connect to the password server.");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="mx-auto max-w-6xl">
      <div className="overflow-hidden rounded-2xl border border-[var(--theme-border)] bg-white shadow-sm">
        <div className="border-b border-[var(--theme-border)] px-6 py-8 sm:px-8">
          <div className="flex items-center gap-4">
            <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl bg-[var(--theme-primary)] text-white shadow-lg shadow-[var(--theme-primary)]/25">
              <ShieldCheck className="h-6 w-6" />
            </span>
            <div>
              <h1 className="text-2xl font-black text-slate-950">
                {t("admin.changePasswordTitle")}
              </h1>
              <p className="mt-2 text-sm font-medium text-slate-600">
                {t("admin.changePasswordDescription")}
              </p>
            </div>
          </div>
        </div>

        <div className="space-y-6 px-6 py-8 sm:px-8">
          {[
            {
              id: "current-password",
              label: t("admin.currentPassword"),
              placeholder: t("admin.enterCurrentPassword"),
              field: "password" as const,
            },
            {
              id: "new-password",
              label: t("admin.newPassword"),
              placeholder: t("admin.enterNewPassword"),
              field: "new_password" as const,
            },
            {
              id: "confirm-password",
              label: t("admin.confirmNewPassword"),
              placeholder: t("admin.confirmNewPasswordPlaceholder"),
              field: "new_password_confirmation" as const,
            },
          ].map((item) => (
            <div key={item.field}>
              <Label
                htmlFor={item.id}
                className="text-sm font-black text-slate-950"
              >
                {item.label}
              </Label>
              <div className="relative mt-3">
                <LockKeyhole className="absolute left-5 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--theme-primary)]" />
                <Input
                  id={item.id}
                  type={visiblePasswords[item.field] ? "text" : "password"}
                  value={form[item.field]}
                  onChange={(event) => setField(item.field, event.target.value)}
                  placeholder={item.placeholder}
                  className="h-14 rounded-2xl border-[var(--theme-border)] bg-[var(--theme-surface)] pl-12 pr-12 text-sm font-semibold shadow-none placeholder:text-slate-400 focus-visible:border-[var(--theme-primary)] focus-visible:ring-[var(--theme-primary)]/20"
                  aria-invalid={!!firstError(errors, item.field)}
                />
                <button
                  type="button"
                  onClick={() => togglePasswordVisibility(item.field)}
                  className="absolute right-5 top-1/2 -translate-y-1/2 text-[var(--theme-primary)] transition hover:text-[var(--theme-emphasis-text)]"
                  aria-label={
                    visiblePasswords[item.field]
                      ? t("register.hidePassword")
                      : t("register.showPassword")
                  }
                >
                  {visiblePasswords[item.field] ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </button>
              </div>
              <FieldError message={firstError(errors, item.field)} />

              {item.field === "new_password" && (
                <div className="mt-4 space-y-2">
                  {passwordRules.map((rule) => (
                    <div
                      key={rule.label}
                      className="flex items-center gap-2 text-xs font-semibold"
                    >
                      <span
                        className={`h-2.5 w-2.5 rounded-full ${
                          rule.passed
                            ? "bg-[var(--theme-primary)]"
                            : "bg-slate-300"
                        }`}
                      />
                      <span
                        className={
                          rule.passed
                            ? "text-[var(--theme-emphasis-text)]"
                            : "text-slate-400"
                        }
                      >
                        {rule.label}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ))}

          <div className="rounded-2xl border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] px-5 py-4">
            <div className="flex gap-3">
              <Info className="mt-0.5 h-5 w-5 shrink-0 text-[var(--theme-primary)]" />
              <div>
                <p className="font-black text-slate-950">
                  {t("admin.passwordSecurityTips")}
                </p>
                <p className="mt-2 text-sm font-medium text-slate-700">
                  {t("admin.passwordSecurityTipsDescription")}
                </p>
              </div>
            </div>
          </div>
        </div>

        <div className="flex justify-end border-t border-[var(--theme-border)] px-6 py-6 sm:px-8">
          <Button
            type="button"
            onClick={submitPassword}
            disabled={isSaving}
            className="h-12 rounded-2xl bg-[var(--theme-primary)] px-7 font-black text-white shadow-lg shadow-[var(--theme-primary)]/25 hover:bg-[var(--theme-accent-dark)]"
          >
            {isSaving ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <ShieldCheck className="mr-2 h-4 w-4" />
            )}
            {t("admin.updatePassword")}
          </Button>
        </div>
      </div>
    </div>
  );
}
