"use client";

import React, { useEffect, useState, useRef } from 'react';
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import Link from '@tiptap/extension-link';
import TextAlign from '@tiptap/extension-text-align';
import Color from '@tiptap/extension-color';
import { TextStyle } from '@tiptap/extension-text-style';
import ImageExtension from '@tiptap/extension-image';
import { upload } from '@vercel/blob/client';
import {
  Bold, Italic, Underline as UnderlineIcon, Strikethrough,
  List, ListOrdered, Link as LinkIcon, RemoveFormatting,
  Image as ImageIcon, Code, Loader2
} from 'lucide-react';

interface WysiwygFieldProps {
  value: string;
  onChange: (value: string) => void;
}

export function WysiwygField({ value, onChange }: WysiwygFieldProps) {
  const [isClient, setIsClient] = useState(false);
  const [isUploadingImage, setIsUploadingImage] = useState(false);
  const [linkModalOpen, setLinkModalOpen] = useState(false);
  const [linkUrl, setLinkUrl] = useState('');
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setIsClient(true);
  }, []);

  const editor = useEditor({
    extensions: [
      StarterKit.configure({
        heading: { levels: [1, 2, 3, 4] },
        link: false, // Disable bundled version to avoid conflicts
        underline: false, // Disable bundled version to avoid conflicts
      }),
      Underline,
      ImageExtension.configure({
        inline: true,
        allowBase64: true,
        HTMLAttributes: {
          class: 'rounded-md max-w-full h-auto',
        },
      }),
      Link.configure({
        openOnClick: false,
        HTMLAttributes: {
          class: 'text-[#3B82F6] underline cursor-pointer',
        },
      }),
      TextAlign.configure({
        types: ['heading', 'paragraph'],
      }),
      TextStyle,
      Color,
    ],
    content: value || '',
    onUpdate: ({ editor }) => {
      onChange(editor.getHTML());
    },
    editorProps: {
      attributes: {
        class: 'prose-article max-w-none focus:outline-none min-h-[200px] p-4 bg-white text-gray-900 rounded-b-md border border-gray-200 border-t-0',
        style: 'color: #111827;',
      },
    },
  });

  useEffect(() => {
    if (editor && value !== editor.getHTML()) {
      editor.commands.setContent(value || '');
    }
  }, [value, editor]);

  if (!isClient) return <div className="min-h-[250px] w-full bg-white rounded-md animate-pulse border border-gray-200" />;
  if (!editor) return null;

  const toggleLink = () => {
    const previousUrl = editor.getAttributes('link').href;
    setLinkUrl(previousUrl || '');
    setLinkModalOpen(true);
  };

  const handleSaveLink = () => {
    if (linkUrl === '') {
      editor.chain().focus().extendMarkRange('link').unsetLink().run();
    } else {
      editor.chain().focus().extendMarkRange('link').setLink({ href: linkUrl }).run();
    }
    setLinkModalOpen(false);
  };

  const handleRemoveLink = () => {
    editor.chain().focus().extendMarkRange('link').unsetLink().run();
    setLinkModalOpen(false);
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const getToken = () => {
      if (typeof window === 'undefined') return '';
      const params = new URLSearchParams(window.location.search);
      return params.get('token') || '';
    };

    setIsUploadingImage(true);
    try {
      const ext = file.name.split('.').pop() || 'bin';
      const timestamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);
      const cleanName = file.name.replace(/\.[^.]+$/, '').replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 50);
      const pathname = `websites/editor/images/${cleanName}_${timestamp}.${ext}`;
      const token = getToken();

      const blob = await upload(pathname, file, {
        access: 'public',
        handleUploadUrl: '/api/editor/upload',
        clientPayload: JSON.stringify({ token }),
      });

      editor.chain().focus().setImage({ src: blob.url }).run();
    } catch (err) {
      console.error('Failed to upload image:', err);
      alert('Failed to upload image.');
    } finally {
      setIsUploadingImage(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const ToolbarBtn = ({ isActive = false, onClick, children, title, disabled = false }: any) => (
    <button
      type="button"
      disabled={disabled}
      onClick={(e) => { e.preventDefault(); e.stopPropagation(); onClick(); }}
      title={title}
      className="p-1.5 rounded transition-colors disabled:opacity-50"
      style={{
        backgroundColor: isActive ? '#E5E7EB' : 'transparent',
        color: isActive ? '#111827' : '#4B5563',
        border: 'none',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        cursor: disabled ? 'not-allowed' : 'pointer'
      }}
      onMouseEnter={(e) => {
        if (!isActive && !disabled) {
          e.currentTarget.style.backgroundColor = '#F3F4F6';
          e.currentTarget.style.color = '#111827';
        }
      }}
      onMouseLeave={(e) => {
        if (!isActive && !disabled) {
          e.currentTarget.style.backgroundColor = 'transparent';
          e.currentTarget.style.color = '#4B5563';
        }
      }}
    >
      {children}
    </button>
  );

  return (
    <div className="flex flex-col w-full bg-white rounded-md border border-gray-200 overflow-hidden relative">
      <input type="file" accept="image/*" ref={fileInputRef} onChange={handleImageUpload} style={{ display: 'none' }} />
      
      {/* Inject prose-article CSS for the editor preview sidebar specifically */}
      <style>{`
        .prose-article h1 { font-size: 2.25rem !important; font-weight: 700 !important; line-height: 1.3; margin-top: 1rem; margin-bottom: 0.5rem; }
        .prose-article h2 { font-size: 1.875rem !important; font-weight: 700 !important; line-height: 1.3; margin-top: 1rem; margin-bottom: 0.5rem; }
        .prose-article h3 { font-size: 1.5rem !important; font-weight: 600 !important; line-height: 1.4; margin-top: 0.75rem; margin-bottom: 0.4rem; }
        .prose-article h4 { font-size: 1.25rem !important; font-weight: 600 !important; line-height: 1.4; margin-top: 0.5rem; margin-bottom: 0.3rem; }
        .prose-article p { margin-bottom: 1rem; line-height: 1.6; }
        .prose-article strong, .prose-article b { font-weight: 700 !important; }
        .prose-article ul { list-style-type: disc; padding-left: 1.5rem; margin-bottom: 1rem; }
        .prose-article ol { list-style-type: decimal; padding-left: 1.5rem; margin-bottom: 1rem; }
        .prose-article li { margin-bottom: 0.25rem; line-height: 1.6; }
        .prose-article a { color: #3B82F6; text-decoration: underline; }
      `}</style>

      {linkModalOpen && (
        <div className="fixed inset-0 z-[100000] flex items-center justify-center bg-black/40 backdrop-blur-sm">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-sm overflow-hidden animate-in fade-in zoom-in-95 duration-200">
            <div className="px-5 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
              <h3 className="font-semibold text-gray-900">Insert Link</h3>
              <button onClick={() => setLinkModalOpen(false)} className="text-gray-400 hover:text-gray-600 transition-colors">
                ✕
              </button>
            </div>
            <div className="p-5">
              <label className="block text-sm font-medium text-gray-700 mb-1.5">URL</label>
              <input
                type="url"
                autoFocus
                value={linkUrl}
                onChange={(e) => setLinkUrl(e.target.value)}
                placeholder="https://example.com"
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all text-gray-900 bg-white"
                onKeyDown={(e) => {
                  if (e.key === 'Enter') handleSaveLink();
                  if (e.key === 'Escape') setLinkModalOpen(false);
                }}
              />
            </div>
            <div className="px-5 py-4 border-t border-gray-100 bg-gray-50 flex justify-end gap-2">
              <button 
                onClick={handleRemoveLink}
                className="px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50 rounded-lg transition-colors mr-auto"
              >
                Remove
              </button>
              <button 
                onClick={() => setLinkModalOpen(false)}
                className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-200 rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button 
                onClick={handleSaveLink}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors shadow-sm"
              >
                Save
              </button>
            </div>
          </div>
        </div>
      )}

      <div className="flex flex-wrap items-center bg-gray-50 border-b border-gray-200 p-1 gap-0.5">
        <select
          value={
            editor.isActive('heading', { level: 1 }) ? 'h1' :
            editor.isActive('heading', { level: 2 }) ? 'h2' :
            editor.isActive('heading', { level: 3 }) ? 'h3' :
            editor.isActive('heading', { level: 4 }) ? 'h4' : 'p'
          }
          onChange={(e) => {
            const val = e.target.value;
            if (val === 'p') editor.chain().focus().setParagraph().run();
            else if (val === 'h1') editor.chain().focus().toggleHeading({ level: 1 }).run();
            else if (val === 'h2') editor.chain().focus().toggleHeading({ level: 2 }).run();
            else if (val === 'h3') editor.chain().focus().toggleHeading({ level: 3 }).run();
            else if (val === 'h4') editor.chain().focus().toggleHeading({ level: 4 }).run();
          }}
          className="bg-transparent border-none text-gray-700 text-sm font-medium py-1.5 px-3 outline-none cursor-pointer hover:bg-gray-200 rounded-sm appearance-none"
        >
          <option value="p">Styles</option>
          <option value="h1">Heading 1</option>
          <option value="h2">Heading 2</option>
          <option value="h3">Heading 3</option>
          <option value="h4">Heading 4</option>
          <option value="p">Paragraph</option>
        </select>

        <div className="w-px h-6 bg-gray-300 mx-1" />

        <ToolbarBtn title="Bold" isActive={editor.isActive('bold')} onClick={() => editor.chain().focus().toggleBold().run()}>
          <Bold size={16} />
        </ToolbarBtn>
        <ToolbarBtn title="Italic" isActive={editor.isActive('italic')} onClick={() => editor.chain().focus().toggleItalic().run()}>
          <Italic size={16} />
        </ToolbarBtn>
        <ToolbarBtn title="Underline" isActive={editor.isActive('underline')} onClick={() => editor.chain().focus().toggleUnderline().run()}>
          <UnderlineIcon size={16} />
        </ToolbarBtn>
        <ToolbarBtn title="Strikethrough" isActive={editor.isActive('strike')} onClick={() => editor.chain().focus().toggleStrike().run()}>
          <Strikethrough size={16} />
        </ToolbarBtn>

        <div className="w-px h-6 bg-gray-300 mx-1" />

        <ToolbarBtn title="Numbered List" isActive={editor.isActive('orderedList')} onClick={() => editor.chain().focus().toggleOrderedList().run()}>
          <ListOrdered size={16} />
        </ToolbarBtn>
        <ToolbarBtn title="Bullet List" isActive={editor.isActive('bulletList')} onClick={() => editor.chain().focus().toggleBulletList().run()}>
          <List size={16} />
        </ToolbarBtn>
        
        <div className="w-px h-6 bg-gray-300 mx-1" />

        <ToolbarBtn title="Link" isActive={editor.isActive('link')} onClick={toggleLink}>
          <LinkIcon size={16} />
        </ToolbarBtn>
        <ToolbarBtn title="Clear Formatting" onClick={() => editor.chain().focus().clearNodes().unsetAllMarks().run()}>
          <RemoveFormatting size={16} />
        </ToolbarBtn>
        <ToolbarBtn title="Upload Image" disabled={isUploadingImage} onClick={() => fileInputRef.current?.click()}>
          {isUploadingImage ? <Loader2 size={16} className="animate-spin text-blue-500" /> : <ImageIcon size={16} />}
        </ToolbarBtn>
        <ToolbarBtn title="Code Block" isActive={editor.isActive('codeBlock')} onClick={() => editor.chain().focus().toggleCodeBlock().run()}>
          <Code size={16} />
        </ToolbarBtn>
      </div>

      <EditorContent editor={editor} className="puck-richtext-editor" />
    </div>
  );
}
