'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 { useTranslation } from '@/hooks/use-translation';

/**
 * EN: Create email settings schema with translated messages
 * VI: Tạo schema cài đặt email với thông báo đã dịch
 */
function createEmailSettingsSchema(t: (key: string) => string) {
  return z.object({
    smtpHost: z.string().min(1, t('validation.required')),
    smtpPort: z.number().min(1).max(65535),
    smtpUser: z.string().min(1, t('validation.required')),
    smtpPassword: z.string().min(1, t('validation.required')),
    smtpFromEmail: z.string().email(t('validation.email')),
    smtpFromName: z.string().min(1, t('validation.required')),
  });
}

/**
 * EN: EmailSettings component - Form for email/SMTP configuration
 * VI: Component EmailSettings - Form cho cấu hình email/SMTP
 *
 * Features:
 * - SMTP configuration (host, port, user, password)
 * - From email and name
 * - Email templates management
 * - Test email function
 *
 * Tính năng:
 * - Cấu hình SMTP (host, port, user, password)
 * - Email và tên người gửi
 * - Quản lý email templates
 * - Chức năng test email
 */
export function EmailSettings() {
  const { t } = useTranslation();
  const [isSaving, setIsSaving] = React.useState(false);
  const [isTesting, setIsTesting] = React.useState(false);
  const [saveSuccess, setSaveSuccess] = React.useState(false);
  const [testResult, setTestResult] = React.useState<'success' | 'error' | null>(null);

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

  const {
    register,
    handleSubmit,
    formState: { errors, isDirty },
    reset,
  } = useForm<EmailSettingsFormData>({
    resolver: zodResolver(emailSettingsSchema),
    defaultValues: {
      smtpHost: 'smtp.example.com',
      smtpPort: 587,
      smtpUser: '',
      smtpPassword: '',
      smtpFromEmail: 'noreply@goodgo.vn',
      smtpFromName: 'GoodGo Platform',
    },
  });

  // EN: Handle form submission / VI: Xử lý submit form
  const onSubmit = async (data: EmailSettingsFormData) => {
    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);
    }
  };

  // EN: Handle test email / VI: Xử lý test email
  const handleTestEmail = async () => {
    setIsTesting(true);
    setTestResult(null);

    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, 1000));
      setTestResult('success');
      setTimeout(() => setTestResult(null), 3000);
    } catch (error) {
      setTestResult('error');
      setTimeout(() => setTestResult(null), 3000);
    } finally {
      setIsTesting(false);
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>Email Settings / Cài đặt Email</CardTitle>
        <CardDescription>
          Configure SMTP settings for sending emails / Cấu hình cài đặt SMTP để gửi email
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CardContent className="space-y-6">
          {/* EN: SMTP Configuration / VI: Cấu hình SMTP */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-text-primary">
              SMTP Configuration / Cấu hình SMTP
            </h3>

            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <Input
                label="SMTP Host / SMTP Host"
                placeholder="smtp.example.com"
                {...register('smtpHost')}
                errorMessage={errors.smtpHost?.message}
                validationState={errors.smtpHost ? 'error' : 'default'}
              />

              <Input
                label="SMTP Port / SMTP Port"
                type="number"
                placeholder="587"
                {...register('smtpPort', { valueAsNumber: true })}
                errorMessage={errors.smtpPort?.message}
                validationState={errors.smtpPort ? 'error' : 'default'}
              />
            </div>

            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <Input
                label="SMTP User / SMTP User"
                placeholder="your-email@example.com"
                {...register('smtpUser')}
                errorMessage={errors.smtpUser?.message}
                validationState={errors.smtpUser ? 'error' : 'default'}
              />

              <Input
                label="SMTP Password / SMTP Password"
                type="password"
                placeholder="Enter SMTP password / Nhập mật khẩu SMTP"
                {...register('smtpPassword')}
                errorMessage={errors.smtpPassword?.message}
                validationState={errors.smtpPassword ? 'error' : 'default'}
              />
            </div>
          </div>

          {/* EN: From Settings / VI: Cài đặt người gửi */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-text-primary">
              From Settings / Cài đặt người gửi
            </h3>

            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <Input
                label="From Email / Email người gửi"
                type="email"
                placeholder="noreply@goodgo.vn"
                {...register('smtpFromEmail')}
                errorMessage={errors.smtpFromEmail?.message}
                validationState={errors.smtpFromEmail ? 'error' : 'default'}
              />

              <Input
                label="From Name / Tên người gửi"
                placeholder="GoodGo Platform"
                {...register('smtpFromName')}
                errorMessage={errors.smtpFromName?.message}
                validationState={errors.smtpFromName ? 'error' : 'default'}
              />
            </div>
          </div>

          {/* EN: Test email section / VI: Phần test email */}
          <div className="p-4 rounded-lg bg-bg-tertiary border border-border-primary">
            <div className="flex items-center justify-between">
              <div>
                <h4 className="text-sm font-medium text-text-primary">
                  Test Email / Test Email
                </h4>
                <p className="text-sm text-text-tertiary mt-1">
                  Send a test email to verify SMTP configuration / Gửi email test để xác minh cấu hình SMTP
                </p>
              </div>
              <Button
                type="button"
                variant="secondary"
                size="sm"
                onClick={handleTestEmail}
                loading={isTesting}
              >
                {t('admin.settings.sendTestEmail')}
              </Button>
            </div>
            {testResult === 'success' && (
              <p className="text-sm text-accent-success mt-2">
                {t('admin.settings.testEmailSent')}
              </p>
            )}
            {testResult === 'error' && (
              <p className="text-sm text-accent-error mt-2">
                {t('admin.settings.testEmailFailed')}
              </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>
  );
}
