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

interface ReviewFormProps {
  onSubmit: (data: {
    name: string;
    surname: string;
    profession: string;
    rating: number;
    text: string;
  }) => void;
  onCancel?: () => void;
  user?: {
    name: string;
    email: string;
    avatar?: string;
  };
}

const EMOJIS = [
  "👍", "👎", "❤️", "😊", "😂", "🎉", "🔥", "👏",
  "😢", "😮", "😡", "🙏", "⭐", "💯", "❤️‍🔥", "🤔",
  "👀", "💪", "🚀", "✨"
];

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_TEXT_LENGTH = 2000;
const MIN_TEXT_LENGTH = 50;
const MAX_NAME_LENGTH = 50;
const MAX_PROFESSION_LENGTH = 100;

interface ValidationErrors {
  name?: string;
  surname?: string;
  profession?: string;
  rating?: string;
  text?: string;
}

export default function ReviewForm(props: ReviewFormProps) {
  const [name, setName] = createSignal("");
  const [surname, setSurname] = createSignal("");
  const [profession, setProfession] = createSignal("");
  const [rating, setRating] = createSignal(0);
  const [text, setText] = createSignal("");
  const [errors, setErrors] = createSignal<ValidationErrors>({});
  const [touched, setTouched] = createSignal<{ [key: string]: boolean }>({});
  const [showEmojiPicker, setShowEmojiPicker] = createSignal(false);

  createEffect(() => {
    if (props.user?.name) {
      const parts = props.user.name.split(" ");
      if (parts.length >= 2) {
        setName(parts[0]);
        setSurname(parts.slice(1).join(" "));
      } else {
        setName(props.user.name);
      }
    }
  });

  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 validateName = (value: string): string | undefined => {
    const trimmed = value.trim();
    if (!trimmed) return "Имя обязательно";
    if (trimmed.length > MAX_NAME_LENGTH) return `Максимум ${MAX_NAME_LENGTH} символов`;
    return undefined;
  };

  const validateSurname = (value: string): string | undefined => {
    const trimmed = value.trim();
    if (!trimmed) return "Фамилия обязательна";
    if (trimmed.length > MAX_NAME_LENGTH) return `Максимум ${MAX_NAME_LENGTH} символов`;
    return undefined;
  };

  const validateProfession = (value: string): string | undefined => {
    const trimmed = value.trim();
    if (!trimmed) return "Профессия обязательна";
    if (trimmed.length > MAX_PROFESSION_LENGTH) return `Максимум ${MAX_PROFESSION_LENGTH} символов`;
    return undefined;
  };

  const validateRating = (value: number): string | undefined => {
    if (!value || value < 1 || value > 5) return "Выберите оценку";
    return undefined;
  };

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

  const handleTextChange = (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_TEXT_LENGTH) {
      value = value.slice(0, MAX_TEXT_LENGTH);
    }

    setText(value);
    if (touched().text) {
      setErrors((prev) => ({ ...prev, text: validateText(value) }));
    }
  };

  const addEmoji = (emoji: string) => {
    setText((prev) => prev + emoji);
    setShowEmojiPicker(false);
  };

  const validateForm = (): boolean => {
    const newErrors: ValidationErrors = {
      name: validateName(name()),
      surname: validateSurname(surname()),
      profession: validateProfession(profession()),
      rating: validateRating(rating()),
      text: validateText(text()),
    };

    setErrors(newErrors);
    setTouched({
      name: true,
      surname: true,
      profession: true,
      rating: true,
      text: true,
    });

    return !Object.values(newErrors).some((error) => error);
  };

  const handleSubmit = (e: Event) => {
    e.preventDefault();
    if (!validateForm()) return;

    props.onSubmit({
      name: sanitizeInput(name().trim()),
      surname: sanitizeInput(surname().trim()),
      profession: sanitizeInput(profession().trim()),
      rating: rating(),
      text: sanitizeInput(text().trim()),
    });

    setName("");
    setSurname("");
    setProfession("");
    setRating(0);
    setText("");
    setErrors({});
    setTouched({});
  };

  const handleBlur = (field: string) => {
    setTouched((prev) => ({ ...prev, [field]: true }));
    
    const fieldValidators: Record<string, () => string | undefined> = {
      name: () => validateName(name()),
      surname: () => validateSurname(surname()),
      profession: () => validateProfession(profession()),
      rating: () => validateRating(rating()),
      text: () => validateText(text()),
    };

    setErrors((prev) => ({
      ...prev,
      [field]: fieldValidators[field](),
    }));
  };

  const isValid = () => {
    return !errors().name && !errors().surname && !errors().profession && 
           !errors().rating && !errors().text && 
           name().trim() && surname().trim() && profession().trim() && 
           rating() > 0 && text().trim();
  };

  const ratingOptions = [
    { value: 5, label: "5 — Отлично" },
    { value: 4, label: "4 — Хорошо" },
    { value: 3, label: "3 — Удовлетворительно" },
    { value: 2, label: "2 — Плохо" },
    { value: 1, label: "1 — Очень плохо" },
  ];

  const getInputClass = (field: keyof ValidationErrors) => {
    const hasError = errors()[field] && touched()[field];
    return `w-full px-4 py-3 rounded-xl border transition-all resize-none bg-white text-gray-900 placeholder-gray-400 outline-none ${
      hasError
        ? "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"
    }`;
  };

  return (
    <form onSubmit={handleSubmit} class="review-form max-w-700px mx-auto flex flex-col gap-6">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div class="flex flex-col gap-1">
          <label class="text-sm font-semibold text-gray-900">Имя *</label>
          <input
            type="text"
            value={name()}
            onInput={(e) => setName(e.currentTarget.value)}
            onBlur={() => handleBlur("name")}
            placeholder="Иван"
            class={getInputClass("name")}
          />
          <Show when={errors().name && touched().name}>
            <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().name}
            </p>
          </Show>
        </div>

        <div class="flex flex-col gap-1">
          <label class="text-sm font-semibold text-gray-900">Фамилия *</label>
          <input
            type="text"
            value={surname()}
            onInput={(e) => setSurname(e.currentTarget.value)}
            onBlur={() => handleBlur("surname")}
            placeholder="Иванов"
            class={getInputClass("surname")}
          />
          <Show when={errors().surname && touched().surname}>
            <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().surname}
            </p>
          </Show>
        </div>
      </div>

      <div class="flex flex-col gap-1">
        <label class="text-sm font-semibold text-gray-900">Профессия *</label>
        <input
          type="text"
          value={profession()}
          onInput={(e) => setProfession(e.currentTarget.value)}
          onBlur={() => handleBlur("profession")}
          placeholder="Например: Предприниматель, Врач, Инженер..."
          class={getInputClass("profession")}
        />
        <Show when={errors().profession && touched().profession}>
          <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().profession}
          </p>
        </Show>
      </div>

      <div class="flex flex-col gap-1">
        <label class="text-sm font-semibold text-gray-900">Оценка *</label>
        <select
          value={rating()}
          onChange={(e) => setRating(parseInt(e.currentTarget.value))}
          onBlur={() => handleBlur("rating")}
          class={getInputClass("rating")}
        >
          <option value="">Выберите оценку</option>
          <For each={ratingOptions}>
            {(option) => (
              <option value={option.value}>{option.label}</option>
            )}
          </For>
        </select>
        <Show when={errors().rating && touched().rating}>
          <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().rating}
          </p>
        </Show>
      </div>

      <div class="flex flex-col gap-1">
        <div class="flex justify-between items-center">
          <label class="text-sm font-semibold text-gray-900">Ваш отзыв *</label>
          <div class="relative">
            <button
              type="button"
              onClick={() => setShowEmojiPicker(!showEmojiPicker())}
              class="p-2 text-gray-400 hover:text-blue-600 transition-colors rounded-lg hover:bg-gray-100"
            >
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
              </svg>
            </button>
            <Show when={showEmojiPicker()}>
              <div class="absolute bottom-full right-0 mb-2 bg-white rounded-xl shadow-lg border border-gray-200 p-3 z-10 w-64">
                <div class="grid grid-cols-5 gap-2">
                  <For each={EMOJIS}>
                    {(emoji) => (
                      <button
                        type="button"
                        onClick={() => addEmoji(emoji)}
                        class="p-2 text-xl hover:bg-gray-100 rounded-lg transition-colors"
                      >
                        {emoji}
                      </button>
                    )}
                  </For>
                </div>
              </div>
            </Show>
          </div>
        </div>
        <textarea
          value={text()}
          onInput={handleTextChange}
          onBlur={() => handleBlur("text")}
          placeholder="Расскажите о вашем опыте работы с нами..."
          rows={5}
          class={getInputClass("text")}
        />
        <div class="flex justify-between items-center">
          <Show when={errors().text && touched().text}>
            <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().text}
            </p>
          </Show>
          <p
            class={`text-xs text-right ml-auto ${text().length > MAX_TEXT_LENGTH * 0.9 ? "text-orange-500" : "text-gray-400"}`}
          >
            {text().length}/{MAX_TEXT_LENGTH}
          </p>
        </div>
      </div>

      <button
        type="submit"
        disabled={!isValid()}
        class="px-8 py-3 bg-gradient-to-b from-blue-600 to-blue-800 hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium rounded-xl transition-all 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>
        Отправить отзыв
      </button>

      <p class="text-xs text-gray-500 text-center">
        Нажимая кнопку, вы соглашаетесь с{" "}
        <a href="/privacy" class="text-blue-600 hover:underline">политикой конфиденциальности</a>
      </p>
    </form>
  );
}