'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 API settings schema with translated messages
 * VI: Tạo schema cài đặt API với thông báo đã dịch
 */
function createApiSettingsSchema(t: (key: string) => string) {
  return z.object({
    apiKeyPrefix: z.string().min(1, t('validation.required')),
    webhookUrl: z.string().url(t('validation.invalidFormat')).optional(),
    rateLimitRequests: z.number().min(10).max(10000),
    rateLimitWindow: z.number().min(1).max(60),
    enableRateLimiting: z.boolean(),
  });
}

/**
 * EN: API Settings component
 * VI: Component API Settings
 */
export function ApiSettings() {
  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 apiSettingsSchema = createApiSettingsSchema(t);
  type ApiSettingsFormData = z.infer<typeof apiSettingsSchema>;

  const {
    register,
    handleSubmit,
    formState: { errors, isDirty },
    reset,
    watch,
    setValue,
  } = useForm<ApiSettingsFormData>({
    resolver: zodResolver(apiSettingsSchema),
    defaultValues: {
      apiKeyPrefix: 'sk_',
      webhookUrl: '',
      rateLimitRequests: 100,
      rateLimitWindow: 1,
      enableRateLimiting: true,
    },
  });

  const enableRateLimiting = watch('enableRateLimiting');

  // EN: Handle form submission / VI: Xử lý submit form
  const onSubmit = async (data: ApiSettingsFormData) => {
    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.api')}</CardTitle>
        <CardDescription>
          {t('admin.settings.apiDesc')}
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CardContent className="space-y-6">
          {/* EN: API Keys / VI: Khóa API */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-text-primary">
              {t('admin.settings.apiKeys')}
            </h3>
            <Input
              label={t('admin.settings.apiKeys')}
              placeholder="sk_"
              {...register('apiKeyPrefix')}
              errorMessage={errors.apiKeyPrefix?.message}
              validationState={errors.apiKeyPrefix ? 'error' : 'default'}
              helperText={t('admin.settings.apiKeys')}
            />
            <Button variant="secondary" size="sm" type="button">
              {t('admin.settings.createApiKey')}
            </Button>
          </div>

          {/* EN: Webhooks / VI: Webhooks */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-text-primary">
              {t('admin.settings.webhooks')}
            </h3>
            <Input
              label={t('admin.settings.webhooks')}
              placeholder="https://example.com/webhook"
              {...register('webhookUrl')}
              errorMessage={errors.webhookUrl?.message}
              validationState={errors.webhookUrl ? 'error' : 'default'}
            />
          </div>

          {/* EN: Rate Limits / VI: Giới hạn tốc độ */}
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-lg font-semibold text-text-primary">
                  {t('admin.settings.rateLimits')}
                </h3>
                <p className="text-sm text-text-tertiary mt-1">
                  {t('admin.settings.rateLimits')}
                </p>
              </div>
              <Switch
                checked={enableRateLimiting}
                onCheckedChange={(checked) => setValue('enableRateLimiting', checked)}
              />
            </div>
            {enableRateLimiting && (
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <Input
                  label={t('admin.settings.rateLimits')}
                  type="number"
                  placeholder="100"
                  {...register('rateLimitRequests', { valueAsNumber: true })}
                  errorMessage={errors.rateLimitRequests?.message}
                  validationState={errors.rateLimitRequests ? 'error' : 'default'}
                />
                <Input
                  label={t('admin.settings.rateLimits')}
                  type="number"
                  placeholder="1"
                  {...register('rateLimitWindow', { valueAsNumber: true })}
                  errorMessage={errors.rateLimitWindow?.message}
                  validationState={errors.rateLimitWindow ? 'error' : 'default'}
                />
              </div>
            )}
          </div>

          {/* EN: Documentation / VI: Tài liệu */}
          <div className="p-4 rounded-lg bg-bg-tertiary border border-border-primary">
            <h4 className="text-sm font-medium text-text-primary mb-2">
              {t('admin.settings.documentation')}
            </h4>
            <p className="text-sm text-text-tertiary">
              {t('admin.settings.documentation')}
            </p>
          </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>
  );
}
