/**
 * Vacation responder — toggle + date range + auto-reply text.
 * Form validation: React Hook Form + Zod.
 */

import React, { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
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 } from '@/components/ui/Card';
import { useToast } from '@/components/ui/Toast';
import { configureVacation, type VacationPayload } from '@/api/mail';

// ── Zod Schema ──
const vacationSchema = z.object({
  enabled: z.boolean().default(false),
  start_date: z.string().optional().default(''),
  end_date: z.string().optional().default(''),
  subject: z.string().optional().default(''),
  body: z.string().optional().default(''),
}).superRefine((data, ctx) => {
  if (data.enabled && data.start_date && data.end_date) {
    const start = new Date(data.start_date);
    const end = new Date(data.end_date);
    if (!Number.isNaN(start.getTime()) && !Number.isNaN(end.getTime())) {
      if (end < start) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: 'endBeforeStart',
          path: ['end_date'],
        });
      }
    }
  }
});

type VacationFormData = z.infer<typeof vacationSchema>;

export function VacationResponder({ accountId }: { accountId: string }) {
  const { t } = useTranslation();
  const toast = useToast();

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors, isSubmitting },
  } = useForm<VacationFormData>({
    resolver: zodResolver(vacationSchema),
    defaultValues: { enabled: false, start_date: '', end_date: '', subject: '', body: '' },
  });

  const enabled = watch('enabled');

  const onSubmit = useCallback(async (data: VacationFormData) => {
    try {
      const payload: VacationPayload = {
        enabled: data.enabled,
        start_date: data.start_date || null,
        end_date: data.end_date || null,
        subject: data.subject,
        body: data.body,
      };
      await configureVacation(payload);
      toast.success(t('mail.vacationSaved'));
    } catch (err) {
      toast.error(err instanceof Error ? err.message : String(err));
    }
  }, [toast, t]);

  const errorMsg = (key: string | undefined) => {
    if (!key) return undefined;
    if (key === 'endBeforeStart') return t('calendar.endBeforeStart', 'End must be after start');
    return key;
  };

  return (
    <div data-testid="vacation-responder">
      <Card title={t('mail.vacationResponder')}>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <label className="flex items-center gap-3 cursor-pointer">
            <input
              type="checkbox"
              {...register('enabled')}
              className="w-5 h-5 rounded border-secondary-300 text-primary-600 focus:ring-primary-500"
              data-testid="vacation-toggle"
            />
            <span className="text-sm font-medium text-secondary-700">{t('mail.enableVacation')}</span>
          </label>

          {enabled && (
            <div className="space-y-3" data-testid="vacation-settings">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <Input
                  label={t('mail.vacationStart')}
                  type="date"
                  {...register('start_date')}
                />
                <Input
                  label={t('mail.vacationEnd')}
                  type="date"
                  {...register('end_date')}
                  error={errorMsg(errors.end_date?.message)}
                />
              </div>
              <Input
                label={t('mail.vacationSubject')}
                {...register('subject')}
                placeholder={t('mail.vacationSubjectPlaceholder')}
              />
              <div>
                <label className="block text-sm font-medium text-secondary-700 mb-1">{t('mail.vacationBody')}</label>
                <textarea
                  {...register('body')}
                  className="w-full min-h-32 border border-secondary-300 rounded-md p-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
                  placeholder={t('mail.vacationBodyPlaceholder')}
                  data-testid="vacation-body"
                />
              </div>
            </div>
          )}

          <Button type="submit" isLoading={isSubmitting} size="sm" data-testid="vacation-save">
            {t('common.save')}
          </Button>
        </form>
      </Card>
    </div>
  );
}
