import { useMemo, useRef } from "react";
import ReactQuill from "react-quill-new";
import "react-quill-new/dist/quill.snow.css";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";

interface Props {
  value: string;
  onChange: (val: string) => void;
  placeholder?: string;
  minHeight?: number;
}

export default function RichEmailEditor({ value, onChange, placeholder, minHeight = 280 }: Props) {
  const quillRef = useRef<any>(null);
  const { toast } = useToast();

  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;
      try {
        const ext = file.name.split(".").pop() || "png";
        const path = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
        const { error: upErr } = await supabase.storage
          .from("email-images")
          .upload(path, file, { contentType: file.type, upsert: false });
        if (upErr) throw upErr;
        const { data: { publicUrl } } = supabase.storage.from("email-images").getPublicUrl(path);
        const editor = quillRef.current?.getEditor?.();
        const range = editor?.getSelection(true);
        editor?.insertEmbed(range?.index ?? 0, "image", publicUrl, "user");
        editor?.setSelection((range?.index ?? 0) + 1, 0);
      } catch (err: any) {
        toast({ variant: "destructive", title: "Image upload failed", description: err.message });
      }
    };
  };

  const modules = useMemo(() => ({
    toolbar: {
      container: [
        [{ header: [1, 2, 3, false] }],
        [{ font: [] }, { size: [] }],
        ["bold", "italic", "underline", "strike"],
        [{ color: [] }, { background: [] }],
        [{ align: [] }],
        [{ list: "ordered" }, { list: "bullet" }],
        ["blockquote", "link", "image"],
        ["clean"],
      ],
      handlers: { image: imageHandler },
    },
  }), []);

  return (
    <div className="bg-background rounded-md">
      <ReactQuill
        ref={quillRef}
        theme="snow"
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        modules={modules}
        style={{ minHeight }}
      />
    </div>
  );
}
