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

import {
  useEffect,
  useState,
} from 'react';

import { useQuill } from 'react-quilljs';

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';

export const HTMLData = (props: ItemDataProps) => {
  const [localValue, setLocalValue] = useState(props.getValue());

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

  // Image upload handler
  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);
        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'));
      }
    };
  };

  // Initialize Quill with react-quilljs
  const { quill, quillRef } = useQuill({
    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'],
        ],
        handlers: {
          image: imageHandler,
        },
      },
    },
    formats: [
      'font', 'header', 'bold', 'italic', 'underline', 'strike', 'blockquote',
      'list', 'bullet', 'indent', 'link', 'image', 'script', 'direction',
      'size', 'color', 'background', 'align'
    ],
    readOnly: false,
    placeholder: 'Введите текст...',
  });

  // Set initial content and handle changes
  useEffect(() => {
    if (quill) {
      // Set initial content
      quill.clipboard.dangerouslyPasteHTML(localValue || '');

      // Handle text changes
      quill.on('text-change', () => {
        const content = quill.root.innerHTML;
        setLocalValue(content);
      });

      // Remove focus after initialization
      setTimeout(() => {
        quill.blur();
      }, 100);
    }
  }, [quill]);




  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={quillRef} />
      <DataDescription {...props} />
    </div>
  );
};
