import { useState, useRef } from 'react';
import { Editor } from '@tinymce/tinymce-react';
import axios from 'axios';
import { useAuth } from '../context/AuthContext';
import { useNavigate, useLocation } from 'react-router-dom';

export default function DocumentEditor() {
  const location = useLocation();
  const stateData = location.state as { initialHtml?: string, initialTitle?: string, documentId?: number } || {};
  
  const [title, setTitle] = useState(stateData.initialTitle || 'Untitled Document');
  const [workflowType, setWorkflowType] = useState('none');
  const [allowDownload, setAllowDownload] = useState(true);
  const [previewContent, setPreviewContent] = useState<string | null>(null);
  const editorRef = useRef<any>(null);
  const { token, user } = useAuth();
  const navigate = useNavigate();

  const handleSave = async () => {
    if (!editorRef.current) return;
    const content = editorRef.current.getContent();
    if (!title.trim() || !content.trim()) return alert("Title and content are required.");
    
    try {
      if (stateData.documentId) {
        await axios.put(`/api/documents/${stateData.documentId}`, {
          title,
          content,
        }, { headers: { Authorization: `Bearer ${token}` } });
        alert("Document updated securely.");
      } else {
        await axios.post('/api/documents', {
          title,
          content,
          workflowType,
          allowDownload
        }, { headers: { Authorization: `Bearer ${token}` } });
        alert("Document saved securely.");
      }
      
      navigate('/dashboard');
    } catch (err) {
      alert("Failed to save document");
    }
  };

  return (
    <div className="bg-[#f8fafc] font-body-md text-[#0f172a] min-h-screen flex flex-col selection:bg-[#8083ff] selection:text-[#0d0096] -mt-5 -mx-3 absolute w-full left-0 top-0 z-50">
      
      {/* TopNavBar Strategy: Transactional/Task-Focused context suppresses the global nav. Custom Editor Header used instead. */}
      <header className="bg-[#f8fafc]/40 backdrop-blur-xl border-b border-black/10 fixed top-0 w-full z-50 h-16 flex items-center justify-between px-8 shadow-sm">
        <div className="flex items-center gap-4 flex-1">
          <button onClick={() => navigate('/dashboard')} className="flex items-center gap-2 text-[#475569] hover:text-[#0f172a] transition-all active:scale-95 group bg-transparent border-none">
            <span className="material-symbols-outlined font-bold">arrow_back</span>
            <span className="font-semibold text-[14px]">Back</span>
          </button>
          <div className="h-6 w-[1px] bg-[#464554]/20 mx-2"></div>
          <div className="relative group max-w-md w-full">
            <input 
              className="bg-transparent border-none focus:ring-0 text-[24px] text-[#c0c1ff] font-bold w-full p-0 cursor-text outline-none" 
              placeholder="Untitled Document" 
              type="text" 
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              style={{ fontFamily: 'Outfit, sans-serif' }}
            />
            <div className="absolute bottom-0 left-0 w-0 h-[2px] bg-[#c0c1ff] transition-all duration-300 group-hover:w-full"></div>
          </div>
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2 px-3 py-1 bg-[#f1f5f9] rounded-full border border-black/5">
            <div className="w-2 h-2 rounded-full bg-[#4edea3] animate-pulse"></div>
            <span className="font-semibold text-[12px] text-[#475569]">Status: Drafting</span>
          </div>
          <button 
            onClick={() => {
              if (editorRef.current) {
                setPreviewContent(editorRef.current.getContent());
              }
            }}
            className="px-6 py-2 rounded-lg bg-[#f1f5f9] text-[#0f172a] border border-black/10 hover:bg-[#e2e8f0] transition-all font-semibold cursor-pointer"
          >
            Preview
          </button>
          <button 
            onClick={handleSave}
            className="px-6 py-2 rounded-lg bg-[#c0c1ff] text-[#1000a9] font-bold hover:shadow-[0_0_15px_rgba(192,193,255,0.4)] transition-all active:scale-95 border-none cursor-pointer"
          >
            Save Document
          </button>
        </div>
      </header>

      {/* Main Workspace */}
      <main className="flex-1 flex mt-16 overflow-hidden h-[calc(100vh-64px)]">
        
        {/* Editor Canvas */}
        <div className="flex-1 bg-[#e2e8f0] custom-scrollbar overflow-y-auto p-8 relative flex justify-center">
          {/* Simulated Paper Document */}
          <div className="w-full max-w-[850px] min-h-[1100px] bg-white rounded-lg document-shadow p-0 mb-24 relative transition-transform duration-500 hover:scale-[1.005] overflow-visible">
            
            <div className="w-full h-full">
               <Editor
                  apiKey="kqv7xewrztabss4weljnwqravluoo9phh73n29of8z6tf6jb"
                  onInit={(_evt, editor) => editorRef.current = editor}
                  initialValue={stateData.initialHtml ? `<h1 style="text-align: center;">${title}</h1>${stateData.initialHtml}` : `<h1 style="text-align: center;">${title || 'Document Title'}</h1><p>Start drafting your formal document here...</p>`}
                  init={{
                    height: 1100,
                    menubar: false,
                    plugins: [
                      'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
                      'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
                      'insertdatetime', 'media', 'table', 'wordcount', 'emoticons', 'directionality', 'save', 'pagebreak'
                    ],
                    toolbar: [
                      'code save print | cut copy paste | undo redo | searchreplace | visualblocks | charmap pagebreak emoticons',
                      'bold italic underline strikethrough | subscript superscript | numlist bullist outdent indent | blockquote | alignleft aligncenter alignright alignjustify | link unlink anchor | image media table | ltr rtl',
                      'styles blocks fontfamily fontsize | forecolor backcolor | removeformat fullscreen'
                    ],
                    toolbar_mode: 'wrap',
                    content_style: 'body { font-family:Inter,Helvetica,Arial,sans-serif; font-size:16px; padding: 2rem; color: #334155; }',
                    skin: 'oxide',
                    content_css: 'default'
                  }}
                />
            </div>

            {/* Subtle Brand Watermark */}
            <div className="absolute bottom-12 right-12 opacity-10 grayscale pointer-events-none">
              <span className="text-[24px] font-bold text-slate-900" style={{ fontFamily: 'Outfit, sans-serif' }}>Signwell</span>
            </div>
          </div>
        </div>

        {/* Right Workflow Sidebar */}
        <aside className="w-80 glass-panel border-l border-black/10 flex flex-col p-6 z-10 custom-scrollbar overflow-y-auto shrink-0">
          <div className="flex items-center gap-2 mb-8">
            <span className="material-symbols-outlined text-[#c0c1ff]" style={{ fontVariationSettings: "'FILL' 1" }}>history_edu</span>
            <h2 className="text-[24px] font-semibold text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>Signature Workflow</h2>
          </div>

          <div className="space-y-6 flex-1">
            <div className="space-y-4">
              <label className="block">
                <span className="font-semibold text-[14px] text-[#475569] mb-2 block">Workflow Type</span>
                <select 
                  className="w-full bg-[#f1f5f9] border-slate-300 rounded-lg focus:border-[#c0c1ff] focus:ring-2 focus:ring-[#c0c1ff]/20 text-[#0f172a] text-[16px] transition-all p-2 outline-none"
                  value={workflowType}
                  onChange={(e) => setWorkflowType(e.target.value)}
                >
                  <option value="none">External Signer Only</option>
                  <option value="pre-sign">Admin signs BEFORE sending</option>
                  <option value="post-sign">Admin signs AFTER signer</option>
                </select>
              </label>
            </div>

            <div className="h-[1px] bg-black/5 w-full"></div>

            {/* Settings Toggles */}
            <div className="space-y-4">
              <div className="flex items-center justify-between group cursor-pointer" onClick={() => setAllowDownload(!allowDownload)}>
                <div className="flex flex-col">
                  <span className="font-semibold text-[14px] text-[#0f172a]">Allow Download</span>
                  <span className="text-[10px] text-[#475569]">Signers can save PDF</span>
                </div>
                <button className={`w-10 h-5 rounded-full p-0.5 transition-colors relative duration-300 border-none ${allowDownload ? 'bg-[#4edea3]' : 'bg-[#e2e8f0]'}`}>
                  <div className={`toggle-dot w-4 h-4 bg-white rounded-full transition-transform duration-300 ${allowDownload ? 'translate-x-5' : 'translate-x-0'}`}></div>
                </button>
              </div>
            </div>

            <div className="h-[1px] bg-black/5 w-full"></div>

            {/* Signature Placeholders */}
            <div className="space-y-2">
              <span className="font-semibold text-[14px] text-[#475569] block">Signer Fields</span>
              <div className="flex flex-wrap gap-2">
                {['[SIGNATURE FIELD]', '[NAME FIELD]', '[DATE FIELD]', '[INITIALS FIELD]', '[ADDRESS FIELD]', '[CHECKBOX FIELD]'].map(field => (
                  <button 
                    key={field}
                    onClick={() => {
                      if (editorRef.current) {
                        editorRef.current.execCommand('mceInsertContent', false, `<span class="signwell-placeholder" data-field="${field}" style="background-color: #c0c1ff; color: #1000a9; padding: 2px 6px; border-radius: 4px; font-weight: bold; cursor: pointer;">${field}</span>&nbsp;`);
                      }
                    }}
                    className="px-2 py-1 bg-white border border-slate-300 rounded text-[#0f172a] text-[10px] hover:bg-[#c0c1ff] hover:text-[#1000a9] transition-colors"
                  >
                    {field.replace(/[\[\]]/g, '')}
                  </button>
                ))}
              </div>
            </div>

            <div className="space-y-2">
              <span className="font-semibold text-[14px] text-[#475569] block">Requestor Fields</span>
              <div className="flex flex-wrap gap-2">
                {['[Requestor SIGNATURE]', '[Requestor NAME]', '[Requestor DATE]', '[Requestor INITIALS]'].map(field => (
                  <button 
                    key={field}
                    onClick={() => {
                      if (editorRef.current) {
                        editorRef.current.execCommand('mceInsertContent', false, `<span class="signwell-placeholder" data-field="${field}" style="background-color: #4edea3; color: #005236; padding: 2px 6px; border-radius: 4px; font-weight: bold; cursor: pointer;">${field}</span>&nbsp;`);
                      }
                    }}
                    className="px-2 py-1 bg-white border border-slate-300 rounded text-[#0f172a] text-[10px] hover:bg-[#4edea3] hover:text-[#005236] transition-colors"
                  >
                    {field.replace(/[\[\]]/g, '')}
                  </button>
                ))}
              </div>
            </div>

            {/* Admin Preview Card */}
            <div className="mt-8 p-4 rounded-xl bg-[#8083ff]/10 border border-[#c0c1ff]/20">
              <div className="flex items-center gap-3 mb-2">
                <div className="w-10 h-10 rounded-full border-2 border-[#c0c1ff]/30 bg-[#8083ff] flex items-center justify-center font-bold text-[#0d0096]">
                  {user?.firstName?.[0] || 'A'}
                </div>
                <div>
                  <p className="font-semibold text-[14px] text-[#c0c1ff]">{user?.firstName} {user?.lastName}</p>
                  <p className="text-[10px] text-[#475569]">Signwell Admin</p>
                </div>
              </div>
              <div className="flex gap-2 mt-3">
                <span className="px-2 py-0.5 rounded bg-[#4edea3]/20 text-[#4edea3] text-[10px] font-bold">Active Session</span>
              </div>
            </div>
          </div>

        </aside>
      </main>

      {/* Preview Modal */}
      {previewContent && (
        <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-[100] flex items-center justify-center p-8">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden">
            <div className="flex justify-between items-center p-6 border-b border-gray-100">
              <h2 className="text-2xl font-bold text-gray-800">Preview: {title}</h2>
              <button onClick={() => setPreviewContent(null)} className="text-gray-400 hover:text-gray-600 border-none bg-transparent cursor-pointer">
                <span className="material-symbols-outlined text-[28px]">close</span>
              </button>
            </div>
            <div className="p-8 overflow-y-auto bg-gray-50 flex-1 text-gray-800 font-sans">
              <div className="bg-white p-12 shadow-sm rounded-lg border border-gray-100 min-h-full" dangerouslySetInnerHTML={{ __html: previewContent }} />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
