import 'quill/dist/quill.snow.css';

import { useEffect, useRef, useState } from 'react';
import Quill from 'quill';

import { rpc } from '@/api/request';
import { toast } from '@/components/ToastRoot';
import { Lang } from '@/lang/Lang';

import DataDescription from './components/DataDescription';
import DataLabel from './components/DataLabel';
import { ItemDataProps } from './types';

const QUILL_MODULES = {
  toolbar: {
    container: [
      [{ font: [] }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      ['bold', 'italic', 'underline', 'strike', 'blockquote'],
      [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
      ['link', 'image'],
      [{ script: 'sub' }, { script: 'super' }],
      [{ direction: 'rtl' }],
      [{ size: ['small', false, 'large', 'huge'] }],
      [{ color: [] }, { background: [] }],
      [{ align: [] }],
      ['clean'],
    ],
  },
};

const QUILL_FORMATS = [
  'font', 'header', 'bold', 'italic', 'underline', 'strike', 'blockquote',
  'list', 'bullet', 'indent', 'link', 'image', 'script', 'direction',
  'size', 'color', 'background', 'align'
];

export const HTMLData = (props: ItemDataProps) => {
  const [localValue, setLocalValue] = useState(props.getValue());
  const quillContainerRef = useRef<HTMLDivElement>(null);
  const quillInstanceRef = useRef<Quill | null>(null);

  useEffect(() => {
    props.setValue(localValue);
  }, [localValue]);

  useEffect(() => {
    const container = quillContainerRef.current;
    if (!container || quillInstanceRef.current) return;

    const imageHandler = () => {
      const input = document.createElement('input');
      input.setAttribute('type', 'file');
      input.setAttribute('accept', 'image/*');
      input.click();

      input.onchange = async () => {
        const file = input?.files?.[0];
        if (!file) return;

        toast.info(Lang.key('uploading_image_wait'));

        const formData = new FormData();
        formData.append('file', file);

        try {
          const response = await rpc.imageUpload(formData);
          const quill = quillInstanceRef.current;
          if (response?.url && quill) {
            const range = quill.getSelection();
            if (range)
              quill.insertEmbed(range.index, 'image', response.url);
          }
        } catch (error) {
          toast.error(Lang.key('error_uploading_image'));
        }
      };
    };

    const modules = {
      ...QUILL_MODULES,
      toolbar: {
        ...QUILL_MODULES.toolbar,
        handlers: { image: imageHandler },
      },
    };

    const quill = new Quill(container, {
      theme: 'snow',
      modules,
      formats: QUILL_FORMATS,
      readOnly: false,
      placeholder: 'Введите текст...',
    });

    quillInstanceRef.current = quill;
    quill.clipboard.dangerouslyPasteHTML(localValue || '');

    const onTextChange = () => {
      setLocalValue(quill.root.innerHTML);
    };
    quill.on('text-change', onTextChange);

    setTimeout(() => quill.blur(), 100);

    return () => {
      quill.off('text-change', onTextChange);
      container.innerHTML = '';
      quillInstanceRef.current = null;
    };
  }, []);




  if (props.onlyShow || !props.structure.editable) {

    return <div>
      <DataLabel {...props} />
      <div dangerouslySetInnerHTML={{ __html: localValue }}></div>
      <DataDescription {...props} />
    </div>


  }

  return (
    <div style={{ width: '100%' }}>
      <DataLabel {...props} />
      <div ref={quillContainerRef} />
      <DataDescription {...props} />
    </div>
  );
};
