'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 advanced settings schema with translated messages
 * VI: Tạo schema cài đặt nâng cao với thông báo đã dịch
 */
function createAdvancedSettingsSchema(_t: (key: string) => string) {
  return z.object({
    enableFeatureFlags: z.boolean(),
    logLevel: z.enum(['debug', 'info', 'warn', 'error']),
    cacheTtl: z.number().min(60).max(86400),
    databasePoolSize: z.number().min(1).max(100),
  });
}

/**
 * EN: Advanced Settings component
 * VI: Component Advanced Settings
 */
export function AdvancedSettings() {
  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 advancedSettingsSchema = createAdvancedSettingsSchema(t);
  type AdvancedSettingsFormData = z.infer<typeof advancedSettingsSchema>;

  const {
    register,
    handleSubmit,
    formState: { errors, isDirty },
    reset,
    watch,
    setValue,
  } = useForm<AdvancedSettingsFormData>({
    resolver: zodResolver(advancedSettingsSchema),
    defaultValues: {
      enableFeatureFlags: true,
      logLevel: 'info',
      cacheTtl: 3600,
      databasePoolSize: 10,
    },
  });

  const enableFeatureFlags = watch('enableFeatureFlags');

  // EN: Handle form submission / VI: Xử lý submit form
  const onSubmit = async (data: AdvancedSettingsFormData) => {
    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.advanced')}</CardTitle>
        <CardDescription>
          {t('admin.settings.advancedDesc')}
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CardContent className="space-y-6">
          {/* EN: Feature Flags / VI: Cờ tính năng */}
          <div className="flex items-center justify-between p-4 rounded-lg bg-bg-tertiary border border-border-primary">
            <div className="flex-1">
              <label
                htmlFor="feature-flags"
                className="text-sm font-medium text-text-primary cursor-pointer"
              >
                {t('admin.settings.featureFlags')}
              </label>
              <p className="text-sm text-text-tertiary mt-1">
                {t('admin.settings.featureFlags')}
              </p>
            </div>
            <Switch
              id="feature-flags"
              checked={enableFeatureFlags}
              onCheckedChange={(checked) => setValue('enableFeatureFlags', checked)}
            />
          </div>

          {/* EN: System Logs / VI: Nhật ký hệ thống */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-text-primary">
              {t('admin.settings.systemLogs')}
            </h3>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">
                {t('admin.settings.systemLogs')}
              </label>
              <select
                {...register('logLevel')}
                className="flex w-full rounded-md border border-border-primary bg-bg-secondary px-3 py-2 text-base text-text-primary transition-all duration-[150ms] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent-primary focus-visible:ring-offset-2"
              >
                <option value="debug">Debug</option>
                <option value="info">Info</option>
                <option value="warn">Warn</option>
                <option value="error">Error</option>
              </select>
            </div>
          </div>

          {/* EN: Cache Management / VI: Quản lý cache */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-text-primary">
              {t('admin.settings.cacheManagement')}
            </h3>
            <Input
              label={t('admin.settings.cacheManagement')}
              type="number"
              placeholder="3600"
              {...register('cacheTtl', { valueAsNumber: true })}
              errorMessage={errors.cacheTtl?.message}
              validationState={errors.cacheTtl ? 'error' : 'default'}
              helperText={t('admin.settings.cacheManagement')}
            />
          </div>

          {/* EN: Database / VI: Cơ sở dữ liệu */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-text-primary">
              {t('admin.settings.database')}
            </h3>
            <Input
              label={t('admin.settings.database')}
              type="number"
              placeholder="10"
              {...register('databasePoolSize', { valueAsNumber: true })}
              errorMessage={errors.databasePoolSize?.message}
              validationState={errors.databasePoolSize ? 'error' : 'default'}
            />
          </div>

          {/* EN: Backup & Restore / VI: Sao lưu & Khôi phục */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-text-primary">
              {t('admin.settings.backup')}
            </h3>
            <div className="flex gap-2">
              <Button variant="secondary" size="sm" type="button">
                {t('admin.settings.backup')}
              </Button>
              <Button variant="secondary" size="sm" type="button">
                {t('admin.settings.restore')}
              </Button>
            </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>
  );
}
