'use client';

import * as React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from '@/components/ui/card';
import { Switch } from '@/components/ui/switch';
import { useTranslation } from '@/hooks/use-translation';

/**
 * EN: Create security settings schema with translated messages
 * VI: Tạo schema cài đặt bảo mật với thông báo đã dịch
 */
function createSecuritySettingsSchema(_t: (key: string) => string) {
  return z.object({
    minPasswordLength: z.number().min(8).max(128),
    requireUppercase: z.boolean(),
    requireLowercase: z.boolean(),
    requireNumbers: z.boolean(),
    requireSpecialChars: z.boolean(),
    sessionTimeout: z.number().min(5).max(1440), // minutes
    maxLoginAttempts: z.number().min(3).max(10),
    lockoutDuration: z.number().min(5).max(60), // minutes
    enableRateLimiting: z.boolean(),
    rateLimitRequests: z.number().min(10).max(10000),
    rateLimitWindow: z.number().min(1).max(60), // minutes
  });
}

/**
 * EN: SecuritySettings component - Form for security settings
 * VI: Component SecuritySettings - Form cho cài đặt bảo mật
 *
 * Features:
 * - Password policy configuration
 * - Session timeout
 * - IP whitelist/blacklist
 * - Rate limiting
 * - CORS settings
 *
 * Tính năng:
 * - Cấu hình chính sách mật khẩu
 * - Timeout session
 * - IP whitelist/blacklist
 * - Rate limiting
 * - Cài đặt CORS
 */
export function SecuritySettings() {
  const { t } = useTranslation();
  const [isSaving, setIsSaving] = React.useState(false);
  const [saveSuccess, setSaveSuccess] = React.useState(false);

  // EN: Create schema with translations / VI: Tạo schema với translations
  const securitySettingsSchema = createSecuritySettingsSchema(t);
  type SecuritySettingsFormData = z.infer<typeof securitySettingsSchema>;

  const {
    register,
    handleSubmit,
    formState: { errors, isDirty },
    reset,
    watch,
    setValue,
  } = useForm<SecuritySettingsFormData>({
    resolver: zodResolver(securitySettingsSchema),
    defaultValues: {
      minPasswordLength: 8,
      requireUppercase: true,
      requireLowercase: true,
      requireNumbers: true,
      requireSpecialChars: true,
      sessionTimeout: 30,
      maxLoginAttempts: 5,
      lockoutDuration: 15,
      enableRateLimiting: true,
      rateLimitRequests: 100,
      rateLimitWindow: 1,
    },
  });

  // EN: Handle form submission / VI: Xử lý submit form
  const onSubmit = async (data: SecuritySettingsFormData) => {
    setIsSaving(true);
    setSaveSuccess(false);

    try {
      // EN: TODO: Replace with actual API call / VI: TODO: Thay thế bằng API call thực tế
      await new Promise((resolve) => setTimeout(resolve, 500));
      
      reset(data);
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 3000);
    } catch (error) {
      console.error(t('admin.settings.settingsSaveFailed'), error);
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t('admin.settings.security')}</CardTitle>
        <CardDescription>
          {t('admin.settings.securityDesc')}
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CardContent className="space-y-6">
          {/* EN: Password Policy / VI: Chính sách mật khẩu */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-text-primary">
              {t('admin.settings.passwordPolicy')}
            </h3>

            <Input
              label={t('admin.settings.minLength')}
              type="number"
              {...register('minPasswordLength', { valueAsNumber: true })}
              errorMessage={errors.minPasswordLength?.message}
              validationState={errors.minPasswordLength ? 'error' : 'default'}
              helperText={t('admin.settings.minLength')}
            />

            <div className="space-y-3">
              <div className="flex items-center justify-between p-3 rounded-lg bg-bg-tertiary border border-border-primary">
                <label htmlFor="require-uppercase" className="text-sm font-medium text-text-primary cursor-pointer">
                  {t('admin.settings.requireUppercase')}
                </label>
                <Switch
                  id="require-uppercase"
                  checked={watch('requireUppercase')}
                  onCheckedChange={(checked) => setValue('requireUppercase', checked)}
                />
              </div>

              <div className="flex items-center justify-between p-3 rounded-lg bg-bg-tertiary border border-border-primary">
                <label htmlFor="require-lowercase" className="text-sm font-medium text-text-primary cursor-pointer">
                  {t('admin.settings.requireLowercase')}
                </label>
                <Switch
                  id="require-lowercase"
                  checked={watch('requireLowercase')}
                  onCheckedChange={(checked) => setValue('requireLowercase', checked)}
                />
              </div>

              <div className="flex items-center justify-between p-3 rounded-lg bg-bg-tertiary border border-border-primary">
                <label htmlFor="require-numbers" className="text-sm font-medium text-text-primary cursor-pointer">
                  {t('admin.settings.requireNumbers')}
                </label>
                <Switch
                  id="require-numbers"
                  checked={watch('requireNumbers')}
                  onCheckedChange={(checked) => setValue('requireNumbers', checked)}
                />
              </div>

              <div className="flex items-center justify-between p-3 rounded-lg bg-bg-tertiary border border-border-primary">
                <label htmlFor="require-special" className="text-sm font-medium text-text-primary cursor-pointer">
                  {t('admin.settings.requireSpecialChars')}
                </label>
                <Switch
                  id="require-special"
                  checked={watch('requireSpecialChars')}
                  onCheckedChange={(checked) => setValue('requireSpecialChars', checked)}
                />
              </div>
            </div>
          </div>

          {/* EN: Session Settings / VI: Cài đặt session */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-text-primary">
              {t('admin.settings.sessionTimeout')}
            </h3>

            <Input
              label={t('admin.settings.sessionTimeout')}
              type="number"
              {...register('sessionTimeout', { valueAsNumber: true })}
              errorMessage={errors.sessionTimeout?.message}
              validationState={errors.sessionTimeout ? 'error' : 'default'}
            />

            <Input
              label={t('admin.settings.sessionTimeout')}
              type="number"
              {...register('maxLoginAttempts', { valueAsNumber: true })}
              errorMessage={errors.maxLoginAttempts?.message}
              validationState={errors.maxLoginAttempts ? 'error' : 'default'}
            />

            <Input
              label={t('admin.settings.sessionTimeout')}
              type="number"
              {...register('lockoutDuration', { valueAsNumber: true })}
              errorMessage={errors.lockoutDuration?.message}
              validationState={errors.lockoutDuration ? 'error' : 'default'}
            />
          </div>

          {/* EN: Rate Limiting / VI: Rate limiting */}
          <div className="space-y-4">
            <div className="flex items-center justify-between p-4 rounded-lg bg-bg-tertiary border border-border-primary">
              <div className="flex-1">
                <label htmlFor="enable-rate-limiting" className="text-sm font-medium text-text-primary cursor-pointer">
                  {t('admin.settings.rateLimits')}
                </label>
                <p className="text-sm text-text-tertiary mt-1">
                  {t('admin.settings.rateLimits')}
                </p>
              </div>
              <Switch
                id="enable-rate-limiting"
                checked={watch('enableRateLimiting')}
                onCheckedChange={(checked) => setValue('enableRateLimiting', checked)}
              />
            </div>

            {watch('enableRateLimiting') && (
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <Input
                  label={t('admin.settings.rateLimits')}
                  type="number"
                  {...register('rateLimitRequests', { valueAsNumber: true })}
                  errorMessage={errors.rateLimitRequests?.message}
                  validationState={errors.rateLimitRequests ? 'error' : 'default'}
                />

                <Input
                  label={t('admin.settings.rateLimits')}
                  type="number"
                  {...register('rateLimitWindow', { valueAsNumber: true })}
                  errorMessage={errors.rateLimitWindow?.message}
                  validationState={errors.rateLimitWindow ? 'error' : 'default'}
                />
              </div>
            )}
          </div>

          {/* EN: Success message / VI: Thông báo thành công */}
          {saveSuccess && (
            <div className="rounded-lg bg-accent-success/10 border border-accent-success p-3 flex items-center gap-2 text-sm text-accent-success">
              <svg
                className="h-4 w-4"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                aria-hidden="true"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M5 13l4 4L19 7"
                />
              </svg>
              {t('admin.settings.settingsSaved')}
            </div>
          )}
        </CardContent>
        <CardFooter className="flex justify-end">
          <Button
            type="submit"
            variant="primary"
            loading={isSaving}
            disabled={!isDirty || isSaving}
          >
            {isSaving ? t('admin.settings.saving') : t('admin.settings.saveSettings')}
          </Button>
        </CardFooter>
      </form>
    </Card>
  );
}
