import { useEffect, useState, useRef } from 'react';
import { supabase } from './supabaseClient';
import toast from 'react-hot-toast';
import ImageGallery from './ImageGallery';
import SubjectScorer from '../components/SubjectScorer';

const Templates = ({ userId = '' }: { userId?: string }) => {
  const [templates, setTemplates]             = useState<any[]>([]);
  const [selectedTemplate, setSelectedTemplate] = useState<any>(null);
  const [loading, setLoading]                 = useState(true);
  const [isUploading, setIsUploading]         = useState(false);
  const [showGallery, setShowGallery]         = useState(false);
  const [showPreview, setShowPreview]         = useState(true);
  const savedSelection = useRef<{ start: number; end: number } | null>(null);

  // Image configuration modal states
  const [isAltModalOpen, setIsAltModalOpen]   = useState(false);
  const [tempImageUrl, setTempImageUrl]       = useState('');
  const [insertMode, setInsertMode]           = useState<'header' | 'cursor'>('cursor');
  const [altText, setAltText]                 = useState('');
  const [imageWidth, setImageWidth]           = useState('600');
  const [imageAlignment, setImageAlignment]   = useState('center');
  const [imageShape, setImageShape]           = useState('0px');

  useEffect(() => { fetchTemplates(); }, []);

  const fetchTemplates = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase.from('templates').select('*').order('created_at');
      if (error) throw error;
      setTemplates(data || []);
    } catch (err: any) {
      console.error('Fetch Error:', err.message);
    } finally {
      setLoading(false);
    }
  };

  const insertTag = (tag: string) => {
    const textarea = document.getElementById('template-body') as HTMLTextAreaElement;
    if (!textarea || !selectedTemplate) return;
    const start = textarea.selectionStart;
    const end   = textarea.selectionEnd;
    const text  = selectedTemplate.content_body || '';
    setSelectedTemplate({ ...selectedTemplate, content_body: text.substring(0, start) + tag + text.substring(end) });
    setTimeout(() => {
      textarea.focus();
      textarea.setSelectionRange(start + tag.length, start + tag.length);
    }, 0);
  };

  const prependTag = (tag: string) => {
    if (!selectedTemplate) return;
    setSelectedTemplate({ ...selectedTemplate, content_body: tag + '\n' + (selectedTemplate.content_body || '') });
  };

  const openGallery = () => {
    const textarea = document.getElementById('template-body') as HTMLTextAreaElement;
    if (textarea) savedSelection.current = { start: textarea.selectionStart, end: textarea.selectionEnd };
    setShowGallery(true);
  };

  // Gallery intercept → image config modal
  const handleGalleryInsert = (url: string, mode: 'header' | 'cursor') => {
    setTempImageUrl(url);
    setInsertMode(mode);
    setAltText('');
    setImageWidth('600');
    setImageAlignment('center');
    setImageShape('0px');
    setShowGallery(false);
    setIsAltModalOpen(true);
  };

  const handleDragOver = (e: React.DragEvent<HTMLTextAreaElement>) => e.preventDefault();

  const handleDrop = async (e: React.DragEvent<HTMLTextAreaElement>) => {
    e.preventDefault();
    const file = e.dataTransfer.files[0];
    if (!file) return;
    if (!['image/png', 'image/jpeg', 'image/jpg'].includes(file.type)) {
      toast.error('Please upload a valid image file (PNG or JPG only).');
      return;
    }
    if (file.size > 400 * 1024) {
      toast.error('File is too large. Please upload an image smaller than 400 KB.');
      return;
    }
    const textarea = e.currentTarget;
    savedSelection.current = { start: textarea.selectionStart, end: textarea.selectionEnd };
    setIsUploading(true);
    try {
      const folder   = userId || 'default';
      const fileExt  = file.name.split('.').pop();
      const fileName = `${Math.random().toString(36).substring(2)}_${Date.now()}.${fileExt}`;
      const path     = `${folder}/${fileName}`;
      const { error: uploadError } = await supabase.storage.from('template-images').upload(path, file);
      if (uploadError) throw uploadError;
      const { data } = supabase.storage.from('template-images').getPublicUrl(path);
      setTempImageUrl(data.publicUrl);
      setInsertMode('cursor');
      setAltText('');
      setImageWidth('600');
      setImageAlignment('center');
      setImageShape('0px');
      setIsAltModalOpen(true);
    } catch (err: any) {
      toast.error('Error uploading image: ' + err.message);
    } finally {
      setIsUploading(false);
    }
  };

  // Apply configured image tag into the template body
  const finalizeImageInsertion = () => {
    const finalAlt   = altText.trim() || 'Template Image';
    const maxWidth   = imageWidth ? `${imageWidth}px` : '600px';
    const imgTag     = `<div style="text-align:${imageAlignment};margin:15px 0 20px 0;"><img src="${tempImageUrl}" alt="${finalAlt}" style="width:100%;max-width:${maxWidth};height:auto;border-radius:${imageShape};display:inline-block;" /></div>`;
    if (insertMode === 'header') {
      prependTag(imgTag);
    } else {
      const sel = savedSelection.current;
      if (sel && selectedTemplate) {
        const text       = selectedTemplate.content_body || '';
        const newContent = text.substring(0, sel.start) + imgTag + text.substring(sel.end);
        setSelectedTemplate({ ...selectedTemplate, content_body: newContent });
        setTimeout(() => {
          const textarea = document.getElementById('template-body') as HTMLTextAreaElement;
          if (textarea) { textarea.focus(); const pos = sel.start + imgTag.length; textarea.setSelectionRange(pos, pos); }
        }, 0);
      } else {
        insertTag(imgTag);
      }
    }
    savedSelection.current = null;
    setIsAltModalOpen(false);
    setTempImageUrl('');
  };

  const handleSave = async () => {
    if (!selectedTemplate.title) { toast.error('Please enter a title.'); return; }
    try {
      const payload = {
        title:        selectedTemplate.title,
        subject_line: selectedTemplate.subject_line,
        content_body: selectedTemplate.content_body,
        ...(userId ? { user_id: userId } : {}),
      };
      const { error } = selectedTemplate.id
        ? await supabase.from('templates').update(payload).eq('id', selectedTemplate.id)
        : await supabase.from('templates').insert([payload]);
      if (error) throw error;
      toast.success('Template saved successfully.');
      fetchTemplates();
      setSelectedTemplate(null);
    } catch (err: any) {
      toast.error('Error saving: ' + err.message);
    }
  };

  if (loading) return <div className="p-10 text-slate-400 italic">Loading Library...</div>;

  return (
    <div className="w-full space-y-6">

      {/* ── IMAGE GALLERY MODAL ── */}
      {showGallery && (
        <ImageGallery
          userId={userId}
          onInsert={handleGalleryInsert}
          onClose={() => setShowGallery(false)}
        />
      )}

      {/* ── IMAGE CONFIGURATION MODAL ── */}
      {isAltModalOpen && (
        <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-[2rem] border border-slate-100 shadow-2xl p-8 max-w-md w-full space-y-5">
            <div>
              <h3 className="text-xl font-serif italic text-slate-800">Image Layout Options</h3>
              <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 mt-1">Configure before inserting</p>
            </div>

            {/* Preview thumbnail */}
            {tempImageUrl && (
              <div className="rounded-xl overflow-hidden border border-slate-100 bg-slate-50 flex items-center justify-center max-h-32">
                <img src={tempImageUrl} alt="preview" className="max-h-32 max-w-full object-contain" />
              </div>
            )}

            <div className="space-y-1">
              <label className="text-[10px] font-black uppercase text-slate-500 ml-1">Alt-Text Description</label>
              <input
                type="text"
                value={altText}
                onChange={e => setAltText(e.target.value)}
                placeholder="e.g., Q3 Promotion Campaign Graphic"
                className="w-full p-2.5 bg-slate-50 border border-slate-100 rounded-xl outline-none text-slate-800 focus:border-blue-500 text-sm"
                onKeyDown={e => { if (e.key === 'Enter') finalizeImageInsertion(); }}
                autoFocus
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-1">
                <label className="text-[10px] font-black uppercase text-slate-500 ml-1">Max Width (px)</label>
                <input
                  type="number"
                  value={imageWidth}
                  onChange={e => setImageWidth(e.target.value)}
                  placeholder="600"
                  className="w-full p-2.5 bg-slate-50 border border-slate-100 rounded-xl outline-none text-sm font-bold text-slate-800"
                />
              </div>
              <div className="space-y-1">
                <label className="text-[10px] font-black uppercase text-slate-500 ml-1">Alignment</label>
                <select
                  value={imageAlignment}
                  onChange={e => setImageAlignment(e.target.value)}
                  className="w-full p-2.5 bg-slate-50 border border-slate-100 rounded-xl outline-none text-sm text-slate-800 font-medium cursor-pointer"
                >
                  <option value="center">Centered</option>
                  <option value="left">Left Aligned</option>
                  <option value="right">Right Aligned</option>
                </select>
              </div>
            </div>

            <div className="space-y-1">
              <label className="text-[10px] font-black uppercase text-slate-500 ml-1">Corner Shape</label>
              <div className="grid grid-cols-4 gap-2">
                {[
                  { label: 'Square', value: '0px' },
                  { label: 'Soft', value: '12px' },
                  { label: 'Round', value: '24px' },
                  { label: 'Circle', value: '50%' },
                ].map(opt => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setImageShape(opt.value)}
                    className={`py-2 text-[9px] font-black uppercase tracking-wider rounded-xl border transition-all ${imageShape === opt.value ? 'bg-blue-600 text-white border-blue-600' : 'bg-slate-50 text-slate-500 border-slate-100 hover:bg-slate-100'}`}
                  >
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>

            <div className="flex gap-3 pt-2">
              <button
                onClick={finalizeImageInsertion}
                className="flex-grow bg-blue-600 text-white py-3.5 rounded-2xl font-black text-[10px] uppercase tracking-widest hover:bg-blue-700 transition-all shadow-lg shadow-blue-500/10"
              >
                Insert Image
              </button>
              <button
                onClick={() => { setIsAltModalOpen(false); savedSelection.current = null; }}
                className="px-6 bg-slate-100 text-slate-400 py-3.5 rounded-2xl font-black text-[10px] uppercase tracking-widest hover:bg-slate-200 transition-all"
              >
                Discard
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── HEADER ── */}
      <header className="flex justify-between items-center bg-white p-6 rounded-3xl border border-slate-100 shadow-sm">
        <div>
          <h2 className="text-3xl font-serif italic text-slate-800">Template Library</h2>
          <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 mt-1">Manage Networking Notices</p>
        </div>
        <div className="flex items-center gap-3">
          {selectedTemplate && (
            <button
              onClick={() => setShowPreview(v => !v)}
              className={`px-4 py-2.5 rounded-2xl font-black text-[10px] uppercase tracking-widest transition-all border ${showPreview ? 'bg-indigo-50 text-indigo-600 border-indigo-100 hover:bg-indigo-100' : 'bg-slate-50 text-slate-400 border-slate-100 hover:bg-slate-100'}`}
            >
              {showPreview ? '⊡ Hide Preview' : '⊞ Live Preview'}
            </button>
          )}
          <button
            onClick={() => setSelectedTemplate({ title: '', subject_line: '', content_body: '' })}
            className="bg-blue-600 text-white px-6 py-3 rounded-2xl font-black text-[10px] uppercase tracking-widest hover:bg-blue-700 transition-all"
          >
            + New Template
          </button>
        </div>
      </header>

      {/* ── MAIN WORKSPACE ── */}
      <div className="flex gap-6 items-start">

        {/* SIDEBAR */}
        <div className="bg-white rounded-[2rem] border border-slate-100 shadow-sm overflow-hidden flex-shrink-0 w-56 flex flex-col" style={{ minHeight: 600 }}>
          <div className="px-4 py-3 border-b border-slate-50">
            <p className="text-[9px] font-black uppercase tracking-widest text-slate-400">{templates.length} Template{templates.length !== 1 ? 's' : ''}</p>
          </div>
          <div className="flex-grow overflow-y-auto p-3 space-y-1.5">
            {templates.map(t => (
<div
                key={t.id}
                onClick={() => setSelectedTemplate(t)}
                className={`group/item flex items-center justify-between p-3 rounded-2xl border transition-all cursor-pointer ${selectedTemplate?.id === t.id ? 'border-blue-500 bg-blue-50' : 'border-transparent hover:bg-slate-50'}`}
              >
                <div className="min-w-0 flex-1 pr-2">
                  <p className="font-bold text-slate-900 text-sm truncate">{t.title}</p>
                  <p className="text-[9px] text-slate-400 truncate uppercase mt-0.5">{t.subject_line || 'No Subject'}</p>
                </div>
                <button
                  onClick={async (e) => {
                    e.stopPropagation();
                    if (!window.confirm(`Delete "${t.title}"?`)) return;
                    try {
                      const { error } = await supabase.from('templates').delete().eq('id', t.id);
                      if (error) throw error;
                      toast.success('Deleted.');
                      if (selectedTemplate?.id === t.id) setSelectedTemplate(null);
                      fetchTemplates();
                    } catch (err: any) {
                      toast.error(err.message);
                    }
                  }}
                  className="p-1.5 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-xl opacity-0 group-hover/item:opacity-100 transition-all flex-shrink-0"
                  title="Delete Template"
                >
                  🗑️
                </button>
              </div>

            ))}
          </div>
        </div>

        {/* EDITOR + PREVIEW */}
        <div className="flex-1 min-w-0">
          {selectedTemplate ? (
            <div className={`flex gap-5 ${showPreview ? 'items-start' : ''}`}>

              {/* EDITOR PANE */}
              <div className="bg-white rounded-[2rem] border border-slate-100 shadow-xl p-7 flex flex-col" style={{ minHeight: 640, flex: showPreview ? '0 0 50%' : '1' }}>
                <div className="space-y-4 flex-grow flex flex-col">

                  {/* Title + Subject */}
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-1">
                      <label className="text-[10px] font-black uppercase text-slate-400 ml-1">Internal Title</label>
                      <input
                        className="w-full p-3 bg-slate-50 border border-slate-100 rounded-xl outline-none font-bold text-slate-800"
                        value={selectedTemplate.title}
                        onChange={e => setSelectedTemplate({ ...selectedTemplate, title: e.target.value })}
                      />
                    </div>
                    <div className="space-y-1">
                      <label className="text-[10px] font-black uppercase text-slate-400 ml-1">Subject Line</label>
                      <input
                        className="w-full p-3 bg-slate-50 border border-slate-100 rounded-xl outline-none text-slate-800"
                        value={selectedTemplate.subject_line}
                        onChange={e => setSelectedTemplate({ ...selectedTemplate, subject_line: e.target.value })}
                      />
                      <SubjectScorer subject={selectedTemplate.subject_line || ''} />
                    </div>
                  </div>

                  {/* Toolbar + Textarea */}
                  <div className="space-y-2 flex-grow flex flex-col">
                    <div className="flex justify-between items-center flex-wrap gap-2">
                      <div>
                        <label className="text-[10px] font-black uppercase text-slate-400 ml-1">Message Body</label>
                        <p className="text-[10px] text-slate-400 italic ml-1 mt-0.5">Drag & drop images directly into the text area below.</p>
                      </div>
                      <div className="flex gap-2 flex-wrap">
                        <select
                          defaultValue=""
                          onChange={e => { if (e.target.value) { insertTag(e.target.value); e.target.value = ''; } }}
                          className="px-2 py-1 bg-green-50 text-green-700 rounded text-[10px] font-bold border border-green-100 hover:bg-green-100 transition-colors outline-none cursor-pointer"
                        >
                          <option value="" disabled>Salutation…</option>
                          <option value="Dear &#123;first_name&#125; &#123;last_name&#125;,">Dear [First] [Last],</option>
                          <option value="Dear Mr. &#123;last_name&#125;,">Dear Mr. [Last],</option>
                          <option value="Dear Ms. &#123;last_name&#125;,">Dear Ms. [Last],</option>
                          <option value="Hello &#123;first_name&#125;,">Hello [First],</option>
                          <option value="Hi &#123;first_name&#125;,">Hi [First],</option>
                        </select>
                        <button
                          onClick={openGallery}
                          className="px-2 py-1 bg-purple-50 text-purple-700 rounded text-[10px] font-bold border border-purple-100 hover:bg-purple-100 transition-colors"
                        >
                          🖼 Image Gallery
                        </button>
                      </div>
                    </div>
                    <textarea
                      id="template-body"
                      className={`w-full flex-grow p-5 bg-slate-50 border border-slate-100 rounded-3xl outline-none font-mono text-sm leading-relaxed transition-all resize-none ${isUploading ? 'opacity-50 cursor-wait' : ''}`}
                      value={selectedTemplate.content_body || ''}
                      onChange={e => setSelectedTemplate({ ...selectedTemplate, content_body: e.target.value })}
                      onDragOver={handleDragOver}
                      onDrop={handleDrop}
                      disabled={isUploading}
                      placeholder={isUploading ? 'Uploading image…' : 'Type your HTML or plain-text here. Drag & drop an image to upload and insert it.'}
                      style={{ minHeight: 340 }}
                    />
                  </div>

                  {/* Save / Cancel */}
                  <div className="flex gap-4 pt-2">
                    <button onClick={handleSave} className="flex-grow bg-slate-900 text-white py-4 rounded-2xl font-black text-xs uppercase tracking-widest hover:bg-black transition-all">Save Template</button>
                    <button onClick={() => setSelectedTemplate(null)} className="px-8 bg-slate-100 text-slate-400 py-4 rounded-2xl font-black text-xs uppercase tracking-widest hover:bg-slate-200 transition-all">Cancel</button>
                  </div>
                </div>
              </div>

              {/* LIVE PREVIEW PANE */}
              {showPreview && (
                <div className="bg-white rounded-[2rem] border border-slate-100 shadow-xl flex flex-col overflow-hidden" style={{ minHeight: 640, flex: '0 0 calc(50% - 20px)' }}>
                  <div className="px-6 py-3.5 border-b border-slate-100 flex items-center gap-2 flex-shrink-0">
                    <span className="w-2.5 h-2.5 rounded-full bg-red-300" />
                    <span className="w-2.5 h-2.5 rounded-full bg-yellow-300" />
                    <span className="w-2.5 h-2.5 rounded-full bg-green-300" />
                    <span className="text-[10px] font-black uppercase tracking-widest text-slate-400 ml-2">Live Email Preview</span>
                    {selectedTemplate.subject_line && (
                      <span className="ml-auto text-[10px] text-slate-400 italic truncate max-w-[160px]">{selectedTemplate.subject_line}</span>
                    )}
                  </div>
                  <div className="flex-1 overflow-y-auto bg-slate-100 p-4">
                    <div
                      className="bg-white mx-auto rounded-xl shadow-sm overflow-hidden"
                      style={{ maxWidth: 600, minHeight: 400, fontFamily: 'Georgia, serif', fontSize: 15, lineHeight: 1.7, color: '#1e293b' }}
                    >
                      {selectedTemplate.content_body?.trim() ? (
                        <div
                          className="p-8"
                          dangerouslySetInnerHTML={{ __html: selectedTemplate.content_body }}
                        />
                      ) : (
                        <div className="p-8 flex items-center justify-center h-64 text-slate-300 italic text-sm">
                          Your email will render here as you type…
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}

            </div>
          ) : (
            <div className="bg-white rounded-[2rem] border border-slate-100 shadow-xl flex items-center justify-center text-slate-300 italic font-serif" style={{ minHeight: 500 }}>
              Select a template from the left to begin editing.
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Templates;

export const handleDelete = async (e: any, templateId: string, templateTitle: string, selectedTemplate: any, setSelectedTemplate: any, fetchTemplates: any) => {
  e.stopPropagation();
  if (!window.confirm(`Are you sure you want to permanently delete "${templateTitle}"?`)) return;
  try {
    const { error } = await supabase.from('templates').delete().eq('id', templateId);
    if (error) throw error;
    toast.success('Template deleted successfully.');
    if (selectedTemplate?.id === templateId) setSelectedTemplate(null);
    fetchTemplates();
  } catch (err: any) {
    toast.error('Error deleting template: ' + err.message);
  }
};
