import { createSignal, Show } from "solid-js";

interface CommentFormData {
  content: string;
}

interface ValidationErrors {
  content?: string;
}

interface CommentFormProps {
  onSubmit: (data: CommentFormData) => void;
  isReply?: boolean;
  onCancel?: () => void;
  // Данные авторизованного пользователя из PocketBase
  user?: {
    name: string;
    email: string;
    avatar?: string;
  };
}

// 🔒 Запрещённые паттерны для защиты от XSS
const DANGEROUS_PATTERNS = [
  /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
  /javascript:/gi,
  /on\w+\s*=/gi,
  /<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
  /<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi,
  /<embed\b[^<]*>/gi,
  /data:text\/html/gi,
  /expression\s*\(/gi,
  /url\s*\(\s*['"]*\s*javascript:/gi,
];

// Лимиты
const MAX_MESSAGE_LENGTH = 2000;
const MIN_MESSAGE_LENGTH = 10;

export default function CommentForm(props: CommentFormProps) {
  const [content, setContent] = createSignal("");
  const [errors, setErrors] = createSignal<ValidationErrors>({});
  const [touched, setTouched] = createSignal<{ [key: string]: boolean }>({});

  const sanitizeInput = (input: string): string => {
    return input
      .replace(/[<>]/g, "")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#x27;")
      .replace(/&/g, "&amp;");
  };

  const containsDangerousContent = (input: string): boolean => {
    return DANGEROUS_PATTERNS.some((pattern) => pattern.test(input));
  };

  const validateContent = (value: string): string | undefined => {
    const trimmed = value.trim();
    if (!trimmed) return "Комментарий обязателен";
    if (trimmed.length < MIN_MESSAGE_LENGTH)
      return `Минимум ${MIN_MESSAGE_LENGTH} символов`;
    if (trimmed.length > MAX_MESSAGE_LENGTH)
      return `Максимум ${MAX_MESSAGE_LENGTH} символов`;
    if (containsDangerousContent(trimmed)) return "Обнаружен опасный контент";
    return undefined;
  };

  const handleContentChange = (e: Event) => {
    const target = e.target as HTMLTextAreaElement;
    let value = target.value;

    if (containsDangerousContent(value)) {
      DANGEROUS_PATTERNS.forEach((pattern) => {
        value = value.replace(pattern, "");
      });
    }

    if (value.length > MAX_MESSAGE_LENGTH) {
      value = value.slice(0, MAX_MESSAGE_LENGTH);
    }

    setContent(value);
    if (touched().content) {
      setErrors((prev) => ({ ...prev, content: validateContent(value) }));
    }
  };

  const validateForm = (): boolean => {
    const contentError = validateContent(content());

    setErrors({
      content: contentError,
    });

    setTouched({ content: true });

    return !contentError;
  };

  const handleSubmit = (e: Event) => {
    e.preventDefault();

    if (!validateForm()) return;

    props.onSubmit({
      content: sanitizeInput(content().trim()),
    });

    // Сброс
    setContent("");
    setErrors({});
    setTouched({});
  };

  const handleBlur = () => {
    setTouched((prev) => ({ ...prev, content: true }));
    setErrors((prev) => ({ ...prev, content: validateContent(content()) }));
  };

  const isValid = () => {
    return !errors().content && content().trim();
  };

  return (
    <div
      class={`bg-linear-to-br from-gray-50 to-gray-100 rounded-2xl border border-gray-200 ${props.isReply ? "p-4" : "p-6 md:p-8"}`}
    >
      <h4
        class={`font-semibold text-gray-900 mb-4 flex items-center gap-2 ${props.isReply ? "text-base" : "text-lg"}`}
      >
        <svg
          class="w-5 h-5 text-blue-600"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
          />
        </svg>
        {props.isReply ? "Написать ответ" : "Оставить комментарий"}
      </h4>

      <form onSubmit={handleSubmit} class="space-y-4">
        {/* Поле сообщения */}
        <div class="space-y-1">
          <textarea
            placeholder={props.user ? `Написать комментарий как ${props.user.name}...` : "Ваш комментарий... *"}
            value={content()}
            onInput={handleContentChange}
            onBlur={handleBlur}
            rows={props.isReply ? 3 : 4}
            class={`w-full px-4 py-3 rounded-xl border transition-all resize-none bg-white text-gray-900 placeholder-gray-400 outline-none
              ${
                errors().content && touched().content
                  ? "border-red-300 focus:border-red-500 focus:ring-2 focus:ring-red-200"
                  : "border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
              }`}
          />
          <div class="flex justify-between items-center">
            <Show when={errors().content && touched().content}>
              <p class="text-sm text-red-500 flex items-center gap-1">
                <svg
                  class="w-4 h-4"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                  />
                </svg>
                {errors().content}
              </p>
            </Show>
            <p
              class={`text-xs text-right ml-auto ${content().length > MAX_MESSAGE_LENGTH * 0.9 ? "text-orange-500" : "text-gray-400"}`}
            >
              {content().length}/{MAX_MESSAGE_LENGTH}
            </p>
          </div>
        </div>

        {/* Кнопки */}
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pt-2">
          <p class="text-sm text-gray-500">
            {props.user
              ? `Вы авторизованы как ${props.user.email}`
              : "Ваш email не будет опубликован"}
          </p>
          <div class="flex gap-2">
            <Show when={props.isReply && props.onCancel}>
              <button
                type="button"
                onClick={props.onCancel}
                class="px-6 py-3 text-gray-600 hover:text-gray-800 font-medium transition-colors"
              >
                Отмена
              </button>
            </Show>
            <button
              type="submit"
              disabled={!isValid()}
              class="px-8 py-3 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium rounded-xl transition-colors shadow-lg shadow-blue-200 flex items-center gap-2 hover:cursor-pointer group"
            >
              <svg
                class="w-5 h-5 transition-transform duration-300 group-hover:rotate-90"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
                />
              </svg>
              {props.isReply ? "Отправить" : "Отправить комментарий"}
            </button>
          </div>
        </div>
      </form>
    </div>
  );
}
