import React, { useCallback, useEffect, useState } from "react";
import { View } from "react-native";
import { useAuth, validatePassword } from "../../hooks/useAuth";
import { useNotificationContext } from "../../context/NotificationContext";
import AuthService from "../../services/auth.service";
import { cn } from "../../utils/cn";
import { Button } from "../button";
import { Card, CardContent } from "../card";
import { PasswordInput } from "../input";
// See ProfileTab.tsx's comment on this same import — FormLabel's Root
// is a bare Pressable, not Text; these are static captions, not
// pressable label-input pairs.
import { FormLabelText as Label } from "../label";
import { ErrorText, Text } from "../text";
/**
 * "Security" tab body: change master password (with optional client-side
 * key re-wrap) and toggle MFA. The MFA-enrolment route is consumer-
 * specific — pass it via `onEnableMfa`.
 */
export function SecurityTab({ visible, onClose, onEnableMfa, onComputeReWrap }) {
    const { user, refreshUser } = useAuth();
    const { push } = useNotificationContext();
    const [currentPassword, setCurrentPassword] = useState("");
    const [newPassword, setNewPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [passwordLoading, setPasswordLoading] = useState(false);
    const [passwordError, setPasswordError] = useState("");
    const [mfaPassword, setMfaPassword] = useState("");
    const [mfaLoading, setMfaLoading] = useState(false);
    const [mfaError, setMfaError] = useState("");
    const [mfaSuccess, setMfaSuccess] = useState("");
    useEffect(() => {
        if (visible) {
            return;
        }
        setCurrentPassword("");
        setNewPassword("");
        setConfirmPassword("");
        setPasswordError("");
        setMfaPassword("");
        setMfaError("");
        setMfaSuccess("");
    }, [visible]);
    const handleSavePassword = useCallback(async () => {
        setPasswordError("");
        if (!currentPassword) {
            setPasswordError("Current password is required");
            return;
        }
        if (newPassword !== confirmPassword) {
            setPasswordError("Passwords do not match");
            return;
        }
        const validation = validatePassword(newPassword);
        if (!validation.valid) {
            setPasswordError(validation.errors.join(", "));
            return;
        }
        setPasswordLoading(true);
        try {
            const reWrappedKey = onComputeReWrap
                ? await onComputeReWrap(currentPassword, newPassword)
                : undefined;
            await AuthService.changePassword(currentPassword, newPassword, reWrappedKey);
            setCurrentPassword("");
            setNewPassword("");
            setConfirmPassword("");
            push({ level: "success", title: "Password updated" });
        }
        catch (err) {
            setPasswordError(err instanceof Error ? err.message : "Failed to update password");
        }
        finally {
            setPasswordLoading(false);
        }
    }, [currentPassword, newPassword, confirmPassword, push, onComputeReWrap]);
    const handleDisableMfa = useCallback(async () => {
        setMfaError("");
        setMfaSuccess("");
        if (!mfaPassword) {
            setMfaError("Password is required to disable MFA");
            return;
        }
        setMfaLoading(true);
        try {
            await AuthService.disableMfa(mfaPassword);
            await refreshUser();
            setMfaPassword("");
            setMfaSuccess("MFA disabled");
        }
        catch (err) {
            setMfaError(err instanceof Error ? err.message : "Failed to disable MFA");
        }
        finally {
            setMfaLoading(false);
        }
    }, [mfaPassword, refreshUser]);
    const handleEnableMfa = useCallback(() => {
        onClose();
        onEnableMfa();
    }, [onClose, onEnableMfa]);
    return (<View className="gap-3">
      <Card>
        <CardContent className="p-4">
          <Label className="mb-3 text-xs font-semibold uppercase tracking-wider text-foreground dark:text-white">
            Change Password
          </Label>
          <PasswordInput value={currentPassword} onChangeText={setCurrentPassword} placeholder="Current password" containerClassName="mb-2.5"/>
          <PasswordInput value={newPassword} onChangeText={setNewPassword} placeholder="New password" containerClassName="mb-2.5"/>
          <PasswordInput value={confirmPassword} onChangeText={setConfirmPassword} placeholder="Confirm new password" error={passwordError}/>
          <Button variant="outline" size="sm" className="mt-3 self-end" onPress={handleSavePassword} isLoading={passwordLoading}>
            Update Password
          </Button>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-4">
          <Label className="mb-3 text-xs font-semibold uppercase tracking-wider text-foreground dark:text-white">
            Two-Factor Authentication
          </Label>
          <View className="mb-3.5 flex-row items-center">
            <View className={cn("mr-2 h-2 w-2 rounded-full", user?.mfa_enabled
            ? "bg-foreground dark:bg-white"
            : "bg-muted-foreground/40 dark:bg-neutral-600")}/>
            <Text className={cn("text-sm font-medium", user?.mfa_enabled
            ? "text-foreground dark:text-white"
            : "text-muted-foreground dark:text-neutral-400")}>
              {user?.mfa_enabled ? "Enabled" : "Not enabled"}
            </Text>
          </View>
          {user?.mfa_enabled ? (<>
              <PasswordInput value={mfaPassword} onChangeText={setMfaPassword} placeholder="Your current password" label="Password to Disable" error={mfaError}/>
              {mfaSuccess ? (<Text className="mt-1.5 text-sm text-foreground dark:text-white">{mfaSuccess}</Text>) : null}
              <Button variant="destructive" size="sm" className="mt-3 self-end" onPress={handleDisableMfa} isLoading={mfaLoading}>
                Disable MFA
              </Button>
            </>) : (<>
              {mfaError ? <ErrorText className="mb-2">{mfaError}</ErrorText> : null}
              <Button variant="outline" size="sm" className="mt-1 self-end" onPress={handleEnableMfa}>
                Enable MFA
              </Button>
            </>)}
        </CardContent>
      </Card>
    </View>);
}
//# sourceMappingURL=SecurityTab.jsx.map