'use client';

import { useCallback, useState } from 'react';

import { apiTotp } from '../../clients';
import { authLogger } from '../utils/logger';

export interface TwoFactorDevice {
  id: string;
  name: string;
  createdAt: string;
  lastUsedAt: string | null;
  isPrimary: boolean;
}

export interface UseTwoFactorStatusReturn {
  /** Loading state */
  isLoading: boolean;
  /** Error message */
  error: string | null;
  /** Whether 2FA is enabled for user */
  has2FAEnabled: boolean | null;
  /** List of TOTP devices */
  devices: TwoFactorDevice[];
  /** Fetch 2FA status */
  fetchStatus: () => Promise<void>;
  /** Disable 2FA (requires TOTP code) */
  disable2FA: (code: string) => Promise<boolean>;
  /** Clear error */
  clearError: () => void;
}

/**
 * Hook for checking and managing 2FA status.
 *
 * @example
 * ```tsx
 * const { has2FAEnabled, devices, fetchStatus, disable2FA, isLoading } = useTwoFactorStatus();
 *
 * useEffect(() => {
 *   fetchStatus();
 * }, [fetchStatus]);
 *
 * if (has2FAEnabled) {
 *   // Show disable button
 * } else {
 *   // Show enable button
 * }
 * ```
 */
export const useTwoFactorStatus = (): UseTwoFactorStatusReturn => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [has2FAEnabled, setHas2FAEnabled] = useState<boolean | null>(null);
  const [devices, setDevices] = useState<TwoFactorDevice[]>([]);

  const clearError = useCallback(() => {
    setError(null);
  }, []);

  /**
   * Fetch current 2FA status and devices
   */
  const fetchStatus = useCallback(async (): Promise<void> => {
    setIsLoading(true);
    setError(null);

    try {
      authLogger.info('Fetching 2FA status...');

      const response = await apiTotp.totp_management.totpDevicesList();

      // Map devices to our format

      // Join all devices into a single array
      const devices = response.results.flatMap((device) => device.devices);
      const mappedDevices: TwoFactorDevice[] = devices.map((device) => ({
        id: device.id,
        name: device.name,
        createdAt: device.created_at,
        lastUsedAt: device.last_used_at ?? null,
        isPrimary: device.is_primary,
      }));

      setDevices(mappedDevices);
      
      // 2FA is enabled if there are any devices
      const enabled = mappedDevices.length > 0;
      setHas2FAEnabled(enabled);

      authLogger.info('2FA status:', enabled ? 'enabled' : 'disabled');

    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to fetch 2FA status';
      authLogger.error('Failed to fetch 2FA status:', err);
      setError(errorMessage);
    } finally {
      setIsLoading(false);
    }
  }, []);

  /**
   * Disable 2FA for the account
   */
  const disable2FA = useCallback(async (code: string): Promise<boolean> => {
    if (!code || code.length !== 6) {
      setError('Please enter a 6-digit code');
      return false;
    }

    setIsLoading(true);
    setError(null);

    try {
      authLogger.info('Disabling 2FA...');

      await apiTotp.totp_management.totpDisableCreate({ code });

      setHas2FAEnabled(false);
      setDevices([]);

      authLogger.info('2FA disabled successfully');
      return true;

    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Invalid verification code';
      authLogger.error('Failed to disable 2FA:', err);
      setError(errorMessage);
      return false;
    } finally {
      setIsLoading(false);
    }
  }, []);

  return {
    isLoading,
    error,
    has2FAEnabled,
    devices,
    fetchStatus,
    disable2FA,
    clearError,
  };
};
