'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useState, useEffect } from 'react';
import { authApi } from '@/services/api/auth.api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Shield, Smartphone, Trash2, LogOut, CheckCircle2, AlertCircle } from 'lucide-react';
import { useTranslation } from '@/hooks/use-translation';

/**
 * EN: Create change password schema with translated messages
 * VI: Tạo change password schema với thông báo đã dịch
 */
function createChangePasswordSchema(
  t: (key: string, values?: Record<string, any>) => string
) {
  return z
    .object({
      currentPassword: z.string().min(1, t('settings.security.currentPasswordRequired')),
      newPassword: z
        .string()
        .min(1, t('validation.password'))
        .min(8, t('validation.passwordMin')),
      confirmPassword: z.string().min(1, t('validation.passwordConfirmRequired')),
    })
    .refine((data) => data.newPassword === data.confirmPassword, {
      message: t('validation.passwordConfirm'),
      path: ['confirmPassword'],
    });
}

/**
 * EN: Create TOTP verify schema with translated messages
 * VI: Tạo TOTP verify schema với thông báo đã dịch
 */
function createTotpVerifySchema(
  t: (key: string, values?: Record<string, any>) => string
) {
  return z.object({
    token: z
      .string()
      .min(6, t('settings.security.codeMustBe6Digits'))
      .max(6, t('settings.security.codeMustBe6Digits'))
      .regex(/^\d{6}$/, t('settings.security.codeMustBe6Digits')),
  });
}

/**
 * EN: Session interface
 * VI: Interface cho session
 */
interface Session {
  id: string;
  deviceName: string | null;
  ipAddress: string | null;
  lastActivityAt: string | null;
  createdAt: string;
  expiresAt: string | null;
}

/**
 * EN: Format timestamp to relative time string
 * VI: Format timestamp thành chuỗi thời gian tương đối
 */
function formatRelativeTime(date: string | null, t: (key: string, values?: any) => string, locale: string): string {
  if (!date) return t('settings.security.never');
  const dateObj = new Date(date);
  const now = new Date();
  const diffMs = now.getTime() - dateObj.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);

  if (diffMins < 1) return t('chat.justNow');
  if (diffMins < 60) return t('chat.minutesAgo', { minutes: diffMins });
  if (diffHours < 24) return t('chat.hoursAgo', { hours: diffHours });
  if (diffDays < 7) return t('chat.daysAgo', { days: diffDays });
  return dateObj.toLocaleDateString(locale === 'vi' ? 'vi-VN' : 'en-US', {
    month: 'short',
    day: 'numeric',
    year: dateObj.getFullYear() !== now.getFullYear() ? 'numeric' : undefined,
  });
}

/**
 * EN: Security settings page component
 * VI: Component trang cài đặt bảo mật
 *
 * Features:
 * - Change password form
 * - Two-factor authentication (2FA) setup with QR code
 * - Active sessions management
 */
export default function SecurityPage() {
  // EN: Translation hook / VI: Hook translation
  const { t, locale } = useTranslation();

  // EN: Create schemas with translations / VI: Tạo schemas với translations
  const changePasswordSchema = createChangePasswordSchema(t);
  type ChangePasswordFormData = z.infer<typeof changePasswordSchema>;
  const totpVerifySchema = createTotpVerifySchema(t);
  type TOTPVerifyFormData = z.infer<typeof totpVerifySchema>;

  // EN: Password change state / VI: State đổi mật khẩu
  const [passwordError, setPasswordError] = useState<string>('');
  const [passwordSuccess, setPasswordSuccess] = useState<string>('');

  // EN: 2FA state / VI: State 2FA
  const [mfaEnabled, setMfaEnabled] = useState<boolean>(false);
  const [mfaLoading, setMfaLoading] = useState<boolean>(false);
  const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
  const [totpSecret, setTotpSecret] = useState<string>('');
  const [showQRDialog, setShowQRDialog] = useState<boolean>(false);
  const [mfaError, setMfaError] = useState<string>('');
  const [mfaSuccess, setMfaSuccess] = useState<string>('');

  // EN: Sessions state / VI: State sessions
  const [sessions, setSessions] = useState<Session[]>([]);
  const [sessionsLoading, setSessionsLoading] = useState<boolean>(true);
  const [revokingSessionId, setRevokingSessionId] = useState<string | null>(null);

  // EN: React Hook Form setup for password change / VI: Setup React Hook Form cho đổi mật khẩu
  const {
    register: registerPassword,
    handleSubmit: handlePasswordSubmit,
    formState: { errors: passwordErrors, isSubmitting: isPasswordSubmitting },
    reset: resetPasswordForm,
  } = useForm<ChangePasswordFormData>({
    resolver: zodResolver(changePasswordSchema),
    defaultValues: {
      currentPassword: '',
      newPassword: '',
      confirmPassword: '',
    },
  });

  // EN: React Hook Form setup for TOTP verification / VI: Setup React Hook Form cho xác thực TOTP
  const {
    register: registerTOTP,
    handleSubmit: handleTOTPSubmit,
    formState: { errors: totpErrors, isSubmitting: isTOTPSubmitting },
    reset: resetTOTPForm,
  } = useForm<TOTPVerifyFormData>({
    resolver: zodResolver(totpVerifySchema),
    defaultValues: {
      token: '',
    },
  });

  // EN: Load MFA status and sessions on mount / VI: Tải trạng thái MFA và sessions khi mount
  useEffect(() => {
    loadMFADevices();
    loadSessions();
  }, []);

  /**
   * EN: Load MFA devices to check if MFA is enabled
   * VI: Tải thiết bị MFA để kiểm tra xem MFA có được bật không
   */
  const loadMFADevices = async () => {
    try {
      const response = await authApi.getMFADevices();
      if (response.success && response.data) {
        setMfaEnabled(response.data.length > 0);
      }
    } catch (error) {
      // EN: Silently fail if MFA is not enabled / VI: Thất bại im lặng nếu MFA chưa được bật
      console.error('Failed to load MFA devices:', error);
    }
  };

  /**
   * EN: Load user sessions
   * VI: Tải sessions của người dùng
   */
  const loadSessions = async () => {
    setSessionsLoading(true);
    try {
      const response = await authApi.getSessions();
      if (response.success && response.data) {
        setSessions(response.data);
      }
    } catch (error: any) {
      console.error('Failed to load sessions:', error);
    } finally {
      setSessionsLoading(false);
    }
  };

  /**
   * EN: Handle password change form submission
   * VI: Xử lý submit form đổi mật khẩu
   */
  const onPasswordSubmit = async (data: ChangePasswordFormData) => {
    setPasswordError('');
    setPasswordSuccess('');
    try {
      const response = await authApi.changePassword(data.currentPassword, data.newPassword);
      if (response.success) {
        setPasswordSuccess(t('settings.security.passwordChanged'));
        resetPasswordForm();
        // EN: Clear success message after 5 seconds / VI: Xóa thông báo thành công sau 5 giây
        setTimeout(() => setPasswordSuccess(''), 5000);
      } else {
        setPasswordError(
          response.error?.message || t('settings.security.passwordChangeFailed')
        );
      }
    } catch (error: any) {
      setPasswordError(error.message || t('settings.security.passwordChangeFailed'));
    }
  };

  /**
   * EN: Handle enable 2FA button click
   * VI: Xử lý click nút bật 2FA
   */
  const handleEnable2FA = async () => {
    setMfaLoading(true);
    setMfaError('');
    try {
      const response = await authApi.enableTOTP();
      if (response.success && response.data) {
        setQrCodeUrl(response.data.qrCodeUrl);
        setTotpSecret(response.data.secret);
        setShowQRDialog(true);
      } else {
        setMfaError(
          response.error?.message || t('settings.security.enable2FAFailed')
        );
      }
    } catch (error: any) {
      setMfaError(error.message || t('settings.security.enable2FAFailed'));
    } finally {
      setMfaLoading(false);
    }
  };

  /**
   * EN: Handle TOTP verification form submission
   * VI: Xử lý submit form xác thực TOTP
   */
  const onTOTPSubmit = async (data: TOTPVerifyFormData) => {
    setMfaError('');
    setMfaSuccess('');
    try {
      const response = await authApi.verifyAndEnableTOTP(totpSecret, data.token);
      if (response.success) {
        setMfaSuccess(t('settings.security.2FAEnabled'));
        setShowQRDialog(false);
        setMfaEnabled(true);
        resetTOTPForm();
        setQrCodeUrl('');
        setTotpSecret('');
        // EN: Clear success message after 5 seconds / VI: Xóa thông báo thành công sau 5 giây
        setTimeout(() => setMfaSuccess(''), 5000);
      } else {
        setMfaError(
          response.error?.message || t('settings.security.invalidVerificationCode')
        );
      }
    } catch (error: any) {
      setMfaError(error.message || t('settings.security.invalidVerificationCode'));
    }
  };

  /**
   * EN: Handle disable 2FA
   * VI: Xử lý tắt 2FA
   */
  const handleDisable2FA = async () => {
    if (!confirm(t('settings.security.confirmDisable2FA'))) {
      return;
    }
    setMfaLoading(true);
    setMfaError('');
    try {
      const response = await authApi.disableMFA();
      if (response.success) {
        setMfaEnabled(false);
        setMfaSuccess(t('settings.security.2FADisabled'));
        // EN: Clear success message after 5 seconds / VI: Xóa thông báo thành công sau 5 giây
        setTimeout(() => setMfaSuccess(''), 5000);
      } else {
        setMfaError(
          response.error?.message || t('settings.security.disable2FAFailed')
        );
      }
    } catch (error: any) {
      setMfaError(error.message || t('settings.security.disable2FAFailed'));
    } finally {
      setMfaLoading(false);
    }
  };

  /**
   * EN: Handle revoke session
   * VI: Xử lý thu hồi session
   */
  const handleRevokeSession = async (sessionId: string) => {
    setRevokingSessionId(sessionId);
    try {
      const response = await authApi.revokeSession(sessionId);
      if (response.success) {
        // EN: Reload sessions after revoking / VI: Tải lại sessions sau khi thu hồi
        await loadSessions();
      }
    } catch (error: any) {
      console.error('Failed to revoke session:', error);
    } finally {
      setRevokingSessionId(null);
    }
  };

  /**
   * EN: Handle revoke all sessions
   * VI: Xử lý thu hồi tất cả sessions
   */
  const handleRevokeAllSessions = async () => {
    if (!confirm(t('settings.security.confirmRevokeAll', { defaultValue: 'Are you sure you want to revoke all other sessions?' }))) {
      return;
    }
    try {
      const response = await authApi.revokeAllSessions();
      if (response.success) {
        // EN: Reload sessions after revoking / VI: Tải lại sessions sau khi thu hồi
        await loadSessions();
      }
    } catch (error: any) {
      console.error('Failed to revoke all sessions:', error);
    }
  };

  return (
    <div className="space-y-6">
      {/* EN: Page header / VI: Header trang */}
      <div>
        <h2 className="text-2xl font-semibold text-text-primary">
          {t('settings.security.title')}
        </h2>
        <p className="mt-1 text-sm text-text-tertiary">
          {t('settings.security.manageSettings', { defaultValue: 'Manage your account security settings' })}
        </p>
      </div>

      {/* EN: Change Password Card / VI: Card Đổi mật khẩu */}
      <Card hover={false} bordered>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5 text-[#3B82F6]" />
            {t('settings.security.changePassword')}
          </CardTitle>
          <CardDescription>
            {t('settings.security.updatePasswordDesc', { defaultValue: 'Update your password to keep your account secure' })}
          </CardDescription>
        </CardHeader>
        <form onSubmit={handlePasswordSubmit(onPasswordSubmit)}>
          <CardContent className="space-y-4">
            {/* EN: Success message / VI: Thông báo thành công */}
            {passwordSuccess && (
              <div
                className="p-3 rounded-md bg-bg-tertiary border border-accent-success text-accent-success text-sm flex items-center gap-2"
                role="alert"
              >
                <CheckCircle2 className="h-4 w-4 flex-shrink-0" />
                <span>{passwordSuccess}</span>
              </div>
            )}

            {/* EN: Error message / VI: Thông báo lỗi */}
            {passwordError && (
              <div
                className="p-3 rounded-md bg-bg-tertiary border border-accent-error text-accent-error text-sm flex items-center gap-2"
                role="alert"
              >
                <AlertCircle className="h-4 w-4 flex-shrink-0" />
                <span>{passwordError}</span>
              </div>
            )}

            {/* EN: Current password input / VI: Input mật khẩu hiện tại */}
            <Input
              type="password"
              label={t('settings.security.currentPassword')}
              placeholder={t('settings.security.enterCurrentPassword', { defaultValue: 'Enter current password' })}
              {...registerPassword('currentPassword')}
              errorMessage={passwordErrors.currentPassword?.message}
              validationState={passwordErrors.currentPassword ? 'error' : 'default'}
            />

            {/* EN: New password input / VI: Input mật khẩu mới */}
            <Input
              type="password"
              label={t('settings.security.newPassword')}
              placeholder={t('settings.security.enterNewPassword', { defaultValue: 'Enter new password' })}
              {...registerPassword('newPassword')}
              errorMessage={passwordErrors.newPassword?.message}
              validationState={passwordErrors.newPassword ? 'error' : 'default'}
              helperText={t('validation.passwordMin')}
            />

            {/* EN: Confirm password input / VI: Input xác nhận mật khẩu */}
            <Input
              type="password"
              label={t('settings.security.confirmPassword')}
              placeholder={t('settings.security.confirmNewPassword', { defaultValue: 'Confirm new password' })}
              {...registerPassword('confirmPassword')}
              errorMessage={passwordErrors.confirmPassword?.message}
              validationState={passwordErrors.confirmPassword ? 'error' : 'default'}
            />
          </CardContent>
          <CardFooter>
            <Button type="submit" loading={isPasswordSubmitting}>
              {t('settings.security.updatePassword', { defaultValue: 'Update Password' })}
            </Button>
          </CardFooter>
        </form>
      </Card>

      {/* EN: Two-Factor Authentication Card / VI: Card Xác thực hai yếu tố */}
      <Card hover={false} bordered>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Smartphone className="h-5 w-5 text-[#8B5CF6]" />
            {t('settings.security.twoFactorAuth')}
          </CardTitle>
          <CardDescription>
            {t('settings.security.twoFactorDesc', { defaultValue: 'Add an extra layer of security to your account' })}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* EN: Success message / VI: Thông báo thành công */}
          {mfaSuccess && (
            <div
              className="p-3 rounded-md bg-bg-tertiary border border-accent-success text-accent-success text-sm flex items-center gap-2"
              role="alert"
            >
              <CheckCircle2 className="h-4 w-4 flex-shrink-0" />
              <span>{mfaSuccess}</span>
            </div>
          )}

          {/* EN: Error message / VI: Thông báo lỗi */}
          {mfaError && (
            <div
              className="p-3 rounded-md bg-bg-tertiary border border-accent-error text-accent-error text-sm flex items-center gap-2"
              role="alert"
            >
              <AlertCircle className="h-4 w-4 flex-shrink-0" />
              <span>{mfaError}</span>
            </div>
          )}

          {/* EN: 2FA status / VI: Trạng thái 2FA */}
          <div className="flex items-center justify-between p-4 rounded-lg bg-bg-tertiary border border-border-primary">
            <div>
              <p className="text-sm font-medium text-text-primary">
                {t('settings.security.2FAStatus', { defaultValue: '2FA Status' })}
              </p>
              <p className="text-sm text-text-tertiary mt-1">
                {mfaEnabled
                  ? t('settings.security.enabled', { defaultValue: 'Enabled' })
                  : t('settings.security.disabled', { defaultValue: 'Disabled' })}
              </p>
            </div>
            {mfaEnabled ? (
              <Button
                variant="danger"
                size="sm"
                onClick={handleDisable2FA}
                loading={mfaLoading}
              >
                {t('settings.security.disable2FA')}
              </Button>
            ) : (
              <Button
                variant="primary"
                size="sm"
                onClick={handleEnable2FA}
                loading={mfaLoading}
              >
                {t('settings.security.enable2FA')}
              </Button>
            )}
          </div>

          {/* EN: Instructions / VI: Hướng dẫn */}
          {!mfaEnabled && (
            <div className="p-4 rounded-lg bg-bg-tertiary border border-border-primary">
              <p className="text-sm text-text-secondary">
                {t('settings.security.twoFactorInstructions', { defaultValue: 'Two-factor authentication adds an extra layer of security. When enabled, you\'ll need to enter a code from your authenticator app in addition to your password when signing in.' })}
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* EN: Active Sessions Card / VI: Card Sessions đang hoạt động */}
      <Card hover={false} bordered>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <LogOut className="h-5 w-5 text-accent-info" />
            {t('settings.security.activeSessions')}
          </CardTitle>
          <CardDescription>
            {t('settings.security.manageDevices', { defaultValue: 'Manage devices that are signed in to your account' })}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {sessionsLoading ? (
            <div className="text-center py-8 text-[#A0A0A0]">
              {t('common.loading')}
            </div>
          ) : sessions.length === 0 ? (
            <div className="text-center py-8 text-[#A0A0A0]">
              {t('settings.security.noActiveSessions')}
            </div>
          ) : (
            <>
              {/* EN: Sessions list / VI: Danh sách sessions */}
              <div className="space-y-3">
                {sessions.map((session) => (
                  <div
                    key={session.id}
                    className="flex items-center justify-between p-4 rounded-lg bg-[#1A1A1A] border border-[#2A2A2A]"
                  >
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <Smartphone className="h-4 w-4 text-[#A0A0A0]" />
                        <p className="text-sm font-medium text-[#FAFAFA]">
                          {session.deviceName || t('settings.security.unknownDevice', { defaultValue: 'Unknown Device' })}
                        </p>
                      </div>
                      <div className="mt-2 space-y-1">
                        {session.ipAddress && (
                          <p className="text-xs text-[#A0A0A0]">
                            {t('settings.security.ipAddress')}: {session.ipAddress}
                          </p>
                        )}
                        <p className="text-xs text-[#A0A0A0]">
                          {t('settings.security.lastActivity')}: {formatRelativeTime(session.lastActivityAt, t, locale)}
                        </p>
                        <p className="text-xs text-[#A0A0A0]">
                          {t('settings.security.created')}: {formatRelativeTime(session.createdAt, t, locale)}
                        </p>
                      </div>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRevokeSession(session.id)}
                      loading={revokingSessionId === session.id}
                      className="text-[#EF4444] hover:text-[#DC2626] hover:bg-[#EF4444]/10"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>

              {/* EN: Revoke all button / VI: Nút thu hồi tất cả */}
              {sessions.length > 1 && (
                <div className="pt-4 border-t border-[#2A2A2A]">
                  <Button
                    variant="danger"
                    size="sm"
                    onClick={handleRevokeAllSessions}
                  >
                    {t('settings.security.revokeAllOtherSessions', { defaultValue: 'Revoke All Other Sessions' })}
                  </Button>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      {/* EN: QR Code Dialog for 2FA Setup / VI: Dialog mã QR cho cài đặt 2FA */}
      <Dialog open={showQRDialog} onOpenChange={setShowQRDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t('settings.security.setup2FA', { defaultValue: 'Set Up Two-Factor Authentication' })}</DialogTitle>
            <DialogDescription>
              {t('settings.security.scanQRCode', { defaultValue: 'Scan this QR code with your authenticator app' })}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* EN: QR Code Image / VI: Hình ảnh mã QR */}
            {qrCodeUrl && (
              <div className="flex justify-center p-4 bg-white rounded-lg">
                {/* EN: Using img for data URLs (QR codes), Next.js Image doesn't support data URLs / VI: Sử dụng img cho data URLs (QR codes), Next.js Image không hỗ trợ data URLs */}
                <img
                  src={qrCodeUrl}
                  alt={t('settings.security.qrCodeAlt', { defaultValue: 'QR Code for two-factor authentication' })}
                  className="w-64 h-64"
                  loading="lazy"
                />
              </div>
            )}

            {/* EN: Manual entry code / VI: Mã nhập thủ công */}
            {totpSecret && (
              <div className="p-3 rounded-lg bg-bg-tertiary border border-border-primary">
                <p className="text-xs text-text-tertiary mb-1">
                  {t('settings.security.cantScan', { defaultValue: 'Can\'t scan? Enter this code manually' })}
                </p>
                <p className="text-sm font-mono text-text-primary break-all">
                  {totpSecret}
                </p>
              </div>
            )}

            {/* EN: Error message / VI: Thông báo lỗi */}
            {mfaError && (
              <div
                className="p-3 rounded-md bg-bg-tertiary border border-accent-error text-accent-error text-sm flex items-center gap-2"
                role="alert"
              >
                <AlertCircle className="h-4 w-4 flex-shrink-0" />
                <span>{mfaError}</span>
              </div>
            )}

            {/* EN: Verification form / VI: Form xác thực */}
            <form onSubmit={handleTOTPSubmit(onTOTPSubmit)} className="space-y-4">
              <Input
                type="text"
                label={t('settings.security.verificationCode', { defaultValue: 'Verification Code' })}
                placeholder={t('settings.security.enter6DigitCode', { defaultValue: 'Enter 6-digit code' })}
                maxLength={6}
                {...registerTOTP('token')}
                errorMessage={totpErrors.token?.message}
                validationState={totpErrors.token ? 'error' : 'default'}
                helperText={t('settings.security.enterCodeFromApp', { defaultValue: 'Enter the 6-digit code from your authenticator app' })}
              />

              <DialogFooter>
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => {
                    setShowQRDialog(false);
                    setQrCodeUrl('');
                    setTotpSecret('');
                    resetTOTPForm();
                    setMfaError('');
                  }}
                >
                  {t('common.cancel')}
                </Button>
                <Button type="submit" loading={isTOTPSubmitting}>
                  {t('settings.security.verifyAndEnable', { defaultValue: 'Verify & Enable' })}
                </Button>
              </DialogFooter>
            </form>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
