"use client";

import { useState } from "react";
import { toast } from "sonner";
import { Button, buttonVariants } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useTranslations } from "next-intl";
import { authClient } from "@/lib/auth/client";
import { TwoFactorSettings } from "@/components/settings/two-factor-settings";

export function SecurityForm({
  currentEmail,
  twoFactorEnabled,
  hasPassword,
}: {
  currentEmail: string;
  twoFactorEnabled: boolean;
  hasPassword: boolean;
}) {
  const t = useTranslations("settingsForm");

  const [newEmail, setNewEmail] = useState("");
  const [sendingEmail, setSendingEmail] = useState(false);

  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [changingPassword, setChangingPassword] = useState(false);

  async function handleChangeEmail(e: React.FormEvent) {
    e.preventDefault();
    if (!newEmail.trim()) return;
    setSendingEmail(true);
    try {
      const { error } = await authClient.changeEmail({
        newEmail: newEmail.trim(),
        callbackURL: "/settings",
      });
      if (error) {
        toast.error(error.message ?? t("emailChangeFailed"));
      } else {
        toast.success(t("emailChangeSent"));
        setNewEmail("");
      }
    } finally {
      setSendingEmail(false);
    }
  }

  async function handleChangePassword(e: React.FormEvent) {
    e.preventDefault();
    if (newPassword !== confirmPassword) {
      toast.error(t("passwordMismatch"));
      return;
    }
    setChangingPassword(true);
    try {
      const { error } = await authClient.changePassword({
        currentPassword,
        newPassword,
        revokeOtherSessions: true,
      });
      if (error) {
        toast.error(error.message ?? t("passwordChangeFailed"));
      } else {
        toast.success(t("passwordChanged"));
        setCurrentPassword("");
        setNewPassword("");
        setConfirmPassword("");
      }
    } finally {
      setChangingPassword(false);
    }
  }

  return (
    <div className="space-y-6">
      <section className="rounded-xl border p-6 space-y-4">
        <div>
          <h2 className="font-semibold text-lg">{t("changeEmail")}</h2>
          <p className="text-sm text-muted-foreground mt-1">{t("changeEmailDescription")}</p>
        </div>
        <form onSubmit={handleChangeEmail} className="space-y-3">
          <div className="space-y-2">
            <Label htmlFor="new-email">{t("newEmail")}</Label>
            <Input
              id="new-email"
              type="email"
              value={newEmail}
              onChange={(e) => setNewEmail(e.target.value)}
              placeholder={currentEmail}
              required
            />
          </div>
          <Button type="submit" disabled={sendingEmail || !newEmail.trim()}>
            {sendingEmail ? t("sendingVerification") : t("sendVerification")}
          </Button>
        </form>
      </section>

      <section className="rounded-xl border p-6 space-y-4">
        <div>
          <h2 className="font-semibold text-lg">{t("changePassword")}</h2>
        </div>
        <form onSubmit={handleChangePassword} className="space-y-3">
          <div className="space-y-2">
            <Label htmlFor="current-password">{t("currentPassword")}</Label>
            <Input
              id="current-password"
              type="password"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              autoComplete="current-password"
              required
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="new-password">{t("newPassword")}</Label>
            <Input
              id="new-password"
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              autoComplete="new-password"
              minLength={8}
              required
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="confirm-password">{t("confirmPassword")}</Label>
            <Input
              id="confirm-password"
              type="password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              autoComplete="new-password"
              minLength={8}
              required
            />
          </div>
          <Button
            type="submit"
            disabled={changingPassword || !currentPassword || !newPassword || !confirmPassword}
          >
            {changingPassword ? t("changingPassword") : t("changePasswordButton")}
          </Button>
        </form>
      </section>

      <TwoFactorSettings initialEnabled={twoFactorEnabled} hasPassword={hasPassword} />

      <section className="rounded-xl border p-6 space-y-4">
        <div>
          <h2 className="font-semibold text-lg">{t("downloadData")}</h2>
          <p className="text-sm text-muted-foreground mt-1">{t("downloadDataDescription")}</p>
        </div>
        <a
          href="/api/v1/users/me/export"
          download
          className={buttonVariants({ variant: "outline" })}
        >
          {t("downloadDataButton")}
        </a>
      </section>
    </div>
  );
}
