'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 { Select } from '@/components/ui/select';
import { useTranslation } from '@/hooks/use-translation';
import { useI18n } from '@/contexts/i18n-context';

/**
 * EN: Create general settings schema with translated messages
 * VI: Tạo schema cài đặt chung với thông báo đã dịch
 */
function createGeneralSettingsSchema(t: (key: string) => string) {
  return z.object({
    siteName: z.string().min(1, t('validation.siteNameRequired')),
    defaultLanguage: z.enum(['en', 'vi'], {
      required_error: t('validation.languageRequired'),
    }),
    timezone: z.string().min(1, t('validation.timezoneRequired')),
    maintenanceMode: z.boolean(),
  });
}

/**
 * EN: GeneralSettings component - Form for general system settings
 * VI: Component GeneralSettings - Form cho cài đặt hệ thống chung
 *
 * Features:
 * - Site name input
 * - Logo upload
 * - Default language selection
 * - Timezone selection
 * - Maintenance mode toggle
 *
 * Tính năng:
 * - Input tên site
 * - Upload logo
 * - Chọn ngôn ngữ mặc định
 * - Chọn múi giờ
 * - Toggle chế độ bảo trì
 */
export function GeneralSettings() {
  const { t } = useTranslation();
  const { locale, setLocale } = useI18n();
  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 generalSettingsSchema = createGeneralSettingsSchema(t);
  type GeneralSettingsFormData = z.infer<typeof generalSettingsSchema>;

  const {
    register,
    handleSubmit,
    formState: { errors, isDirty },
    reset,
    watch,
    setValue,
  } = useForm<GeneralSettingsFormData>({
    resolver: zodResolver(generalSettingsSchema),
    defaultValues: {
      siteName: 'GoodGo Platform',
      defaultLanguage: 'en',
      timezone: 'UTC',
      maintenanceMode: false,
    },
  });

  const maintenanceMode = watch('maintenanceMode');

  // EN: Handle form submission / VI: Xử lý submit form
  const onSubmit = async (data: GeneralSettingsFormData) => {
    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.general')}</CardTitle>
        <CardDescription>
          {t('admin.settings.generalDesc')}
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CardContent className="space-y-6">
          {/* EN: Site name / VI: Tên site */}
          <Input
            label={t('admin.settings.siteName')}
            placeholder={t('admin.settings.siteNamePlaceholder')}
            {...register('siteName')}
            errorMessage={errors.siteName?.message}
            validationState={errors.siteName ? 'error' : 'default'}
          />

          {/* EN: Logo upload / VI: Upload logo */}
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-2">
              {t('admin.settings.siteLogo')}
            </label>
            <div className="flex items-center gap-4">
              <div className="h-16 w-16 rounded-lg bg-bg-tertiary border border-border-primary flex items-center justify-center">
                <span className="text-xs text-text-tertiary">Logo</span>
              </div>
              <div>
                <Button variant="secondary" size="sm" type="button">
                  {t('admin.settings.uploadLogo')}
                </Button>
                <p className="text-xs text-text-tertiary mt-1">
                  {t('admin.settings.logoRecommendation')}
                </p>
              </div>
            </div>
          </div>

          {/* EN: Interface language / VI: Ngôn ngữ giao diện */}
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-2">
              {t('admin.settings.interfaceLanguage')}
            </label>
            <Select
              value={locale}
              onChange={(e) => {
                const newLocale = e.target.value as 'en' | 'vi';
                if (newLocale === 'en' || newLocale === 'vi') {
                  setLocale(newLocale);
                }
              }}
              helperText={t('admin.settings.interfaceLanguageDesc')}
            >
              <option value="en">English</option>
              <option value="vi">Tiếng Việt</option>
            </Select>
          </div>

          {/* EN: Default language / VI: Ngôn ngữ mặc định */}
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-2">
              {t('admin.settings.defaultLanguage')}
            </label>
            <select
              {...register('defaultLanguage')}
              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="en">English</option>
              <option value="vi">Tiếng Việt</option>
            </select>
          </div>

          {/* EN: Timezone / VI: Múi giờ */}
          <Input
            label={t('admin.settings.timezone')}
            placeholder="UTC"
            {...register('timezone')}
            errorMessage={errors.timezone?.message}
            validationState={errors.timezone ? 'error' : 'default'}
            helperText={t('admin.settings.timezoneHelper')}
          />

          {/* EN: Maintenance mode / VI: Chế độ bảo trì */}
          <div className="flex items-center justify-between p-4 rounded-lg bg-bg-tertiary border border-border-primary">
            <div className="flex-1">
              <label
                htmlFor="maintenance-mode"
                className="text-sm font-medium text-text-primary cursor-pointer"
              >
                {t('admin.settings.maintenanceMode')}
              </label>
              <p className="text-sm text-text-tertiary mt-1">
                {t('admin.settings.maintenanceModeDesc')}
              </p>
            </div>
            <Switch
              id="maintenance-mode"
              checked={maintenanceMode}
              onCheckedChange={(checked) => setValue('maintenanceMode', checked)}
            />
          </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>
  );
}
