"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";
import { CheckCircle2, KeyRound, Eye, EyeOff, AlertCircle } from "lucide-react";
import { TopBar } from "@/components/ui/TopBar";
import { Button } from "@/components/ui/Button";
import { useAuth } from "@/lib/auth/auth-provider";
import { apiPost, ApiError } from "@/lib/api/client";
import { useTranslation } from "@/lib/i18n/LanguageProvider";

// Local field, not the shared TextField — that one's styled for AuthShell's
// fixed-dark background (text-paper, border-white/10 with no dark: variants),
// which would be unreadable here in light mode. Mirrors Edit Profile's own
// local Field for the same reason, with a show/hide toggle added.
function PasswordField({
  label,
  value,
  onChange,
  autoComplete,
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  autoComplete: "current-password" | "new-password";
}) {
  const [show, setShow] = useState(false);
  return (
    <div>
      <label className="mb-2 block text-sm font-medium text-muted">{label}</label>
      <div className="flex items-center gap-3 rounded-2xl glass px-4 py-3.5">
        <KeyRound size={17} className="shrink-0 text-muted" strokeWidth={2} />
        <input
          type={show ? "text" : "password"}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          autoComplete={autoComplete}
          className="w-full bg-transparent text-[15px] outline-none placeholder:text-muted"
        />
        <button
          type="button"
          onClick={() => setShow((s) => !s)}
          tabIndex={-1}
          className="shrink-0 text-muted"
        >
          {show ? <EyeOff size={17} /> : <Eye size={17} />}
        </button>
      </div>
    </div>
  );
}

export default function ChangePasswordPage() {
  const router = useRouter();
  const { user } = useAuth();
  const { t } = useTranslation();
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [saved, setSaved] = useState(false);

  function validate(): string | null {
    if (!currentPassword) return t("changePassword.currentPasswordRequired");
    if (newPassword.length < 8) return t("changePassword.newPasswordTooShort");
    if (newPassword !== confirmPassword) return t("changePassword.passwordMismatch");
    if (newPassword === currentPassword) return t("changePassword.samePassword");
    return null;
  }

  async function handleSave() {
    if (!user?.email) return;
    const validationError = validate();
    if (validationError) {
      setError(validationError);
      return;
    }

    setError(null);
    setLoading(true);

    try {
      // MySQL's change-password route verifies currentPassword itself
      // server-side (see lib/db/services/auth.ts's changePassword()) —
      // no separate re-sign-in step needed the way Supabase's
      // updateUser() required.
      await apiPost("/api/auth/change-password", { currentPassword, newPassword });
    } catch (err) {
      setLoading(false);
      setError(
        err instanceof ApiError && err.status === 400
          ? t("changePassword.currentPasswordIncorrect")
          : err instanceof ApiError
            ? err.message
            : t("common.genericError")
      );
      return;
    }

    setLoading(false);
    setSaved(true);
    setCurrentPassword("");
    setNewPassword("");
    setConfirmPassword("");
    setTimeout(() => router.push("/profile"), 1600);
  }

  return (
    <div className="relative flex flex-1 flex-col">
      <TopBar title={t("changePassword.title")} />

      <div className="flex flex-1 flex-col gap-6 px-4 pb-6 pt-4">
        <p className="text-sm text-muted">{t("changePassword.description")}</p>

        <div className="flex flex-col gap-4">
          <PasswordField
            label={t("changePassword.currentPassword")}
            value={currentPassword}
            onChange={setCurrentPassword}
            autoComplete="current-password"
          />
          <PasswordField
            label={t("changePassword.newPassword")}
            value={newPassword}
            onChange={setNewPassword}
            autoComplete="new-password"
          />
          <PasswordField
            label={t("changePassword.confirmNewPassword")}
            value={confirmPassword}
            onChange={setConfirmPassword}
            autoComplete="new-password"
          />
        </div>

        {error && (
          <div className="flex items-start gap-2 rounded-xl bg-danger/10 px-3.5 py-3 text-sm text-danger">
            <AlertCircle size={16} className="mt-0.5 shrink-0" />
            {error}
          </div>
        )}

        <div className="mt-auto">
          <Button size="lg" fullWidth onClick={handleSave} disabled={loading}>
            {loading ? t("changePassword.updating") : t("changePassword.updatePassword")}
          </Button>
        </div>
      </div>

      <AnimatePresence>
        {saved && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 20 }}
            className="pointer-events-none absolute inset-x-4 bottom-24 flex items-center gap-2 rounded-2xl bg-teal px-4 py-3 text-sm font-semibold text-ink shadow-glow-teal"
          >
            <CheckCircle2 size={16} strokeWidth={2.5} />
            {t("changePassword.passwordUpdated")}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
