'use client';

import { useEffect, useState } from 'react';
import { Dialog, DialogHeader, DialogBody, DialogFooter } from '@/components/ui/dialog';
import { api } from '@/lib/api';

type EmailType = 'WELCOME' | 'TRAINING_REMINDER' | 'MEMBERSHIP_EXPIRING' | 'PROMO' | 'BIRTHDAY';

type EmailTemplate = {
  id: string;
  type: EmailType;
  subject: string;
  bodyHtml: string;
  bodyText?: string;
  variables: string[];
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
};

const EMAIL_TYPES: { value: EmailType; label: string }[] = [
  { value: 'WELCOME', label: 'Приветствие' },
  { value: 'TRAINING_REMINDER', label: 'Напоминание о тренировке' },
  { value: 'MEMBERSHIP_EXPIRING', label: 'Истечение абонемента' },
  { value: 'PROMO', label: 'Промо-акция' },
  { value: 'BIRTHDAY', label: 'День рождения' },
];

const AVAILABLE_VARIABLES = ['clientName', 'clubName', 'trainerName', 'date', 'time', 'serviceName', 'expirationDate', 'promoCode'];

type TemplateDialogProps = {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  template?: EmailTemplate | null;
};

export function TemplateDialog({ open, onClose, onSaved, template }: TemplateDialogProps) {
  const isEdit = !!template;

  const [type, setType] = useState<EmailType>('WELCOME');
  const [subject, setSubject] = useState('');
  const [bodyHtml, setBodyHtml] = useState('');
  const [bodyText, setBodyText] = useState('');
  const [variables, setVariables] = useState<string[]>([]);
  const [isActive, setIsActive] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (open) {
      if (template) {
        setType(template.type);
        setSubject(template.subject);
        setBodyHtml(template.bodyHtml);
        setBodyText(template.bodyText ?? '');
        setVariables(template.variables);
        setIsActive(template.isActive);
      } else {
        setType('WELCOME');
        setSubject('');
        setBodyHtml('');
        setBodyText('');
        setVariables([]);
        setIsActive(true);
      }
      setError(null);
    }
  }, [open, template]);

  const toggleVariable = (v: string) => {
    setVariables((prev) =>
      prev.includes(v) ? prev.filter((x) => x !== v) : [...prev, v]
    );
  };

  const handleSubmit = async () => {
    if (!subject.trim()) {
      setError('Введите тему письма');
      return;
    }
    if (!bodyHtml.trim()) {
      setError('Введите HTML-шаблон');
      return;
    }

    setLoading(true);
    setError(null);
    try {
      await api.put('/email/templates', {
        type,
        subject: subject.trim(),
        bodyHtml: bodyHtml.trim(),
        bodyText: bodyText.trim() || undefined,
        variables,
        isActive,
      });
      onSaved();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Не удалось сохранить шаблон');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} className="max-w-2xl">
      <DialogHeader
        title={isEdit ? 'Редактировать шаблон' : 'Новый шаблон'}
        description="Настройте тип письма, тему и HTML-шаблон с переменными Handlebars"
        onClose={onClose}
      />
      <DialogBody>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Тип письма
            </label>
            <select
              value={type}
              onChange={(e) => setType(e.target.value as EmailType)}
              disabled={isEdit}
              className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary disabled:opacity-60"
            >
              {EMAIL_TYPES.map((t) => (
                <option key={t.value} value={t.value}>{t.label}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Тема письма
            </label>
            <input
              type="text"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder="Например: Добро пожаловать в {{clubName}}!"
              className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              HTML-шаблон (Handlebars)
            </label>
            <textarea
              value={bodyHtml}
              onChange={(e) => setBodyHtml(e.target.value)}
              rows={8}
              placeholder="<h1>Привет, {{clientName}}!</h1>&#10;<p>Добро пожаловать в {{clubName}}.</p>"
              className="w-full px-3 py-2 border border-border rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary resize-none"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Текстовая версия (опционально)
            </label>
            <textarea
              value={bodyText}
              onChange={(e) => setBodyText(e.target.value)}
              rows={3}
              placeholder="Привет, {{clientName}}! Добро пожаловать..."
              className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary resize-none"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Переменные
            </label>
            <div className="flex flex-wrap gap-2">
              {AVAILABLE_VARIABLES.map((v) => (
                <button
                  key={v}
                  type="button"
                  onClick={() => toggleVariable(v)}
                  className={`px-2.5 py-1 rounded-lg text-xs font-mono border transition-colors ${
                    variables.includes(v)
                      ? 'bg-primary text-white border-primary'
                      : 'bg-white text-gray-700 border-border hover:bg-gray-50'
                  }`}
                >
                  {`{{${v}}}`}
                </button>
              ))}
            </div>
          </div>

          <div className="flex items-center gap-3">
            <button
              type="button"
              onClick={() => setIsActive(!isActive)}
              className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                isActive ? 'bg-primary' : 'bg-gray-300'
              }`}
            >
              <span
                className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                  isActive ? 'translate-x-6' : 'translate-x-1'
                }`}
              />
            </button>
            <span className="text-sm text-gray-700">
              {isActive ? 'Шаблон активен' : 'Шаблон выключен'}
            </span>
          </div>

          {error && (
            <p className="text-sm text-error">{error}</p>
          )}
        </div>
      </DialogBody>
      <DialogFooter>
        <button
          onClick={onClose}
          disabled={loading}
          className="px-4 py-2 rounded-xl border border-border text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
        >
          Отмена
        </button>
        <button
          onClick={() => void handleSubmit()}
          disabled={loading}
          className="bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50"
        >
          {loading ? 'Сохранение...' : isEdit ? 'Сохранить' : 'Создать'}
        </button>
      </DialogFooter>
    </Dialog>
  );
}
