import React, { useState, useEffect, useCallback } from 'react';
import { EmailTemplate } from '../types';
import { saveTemplate, generateSQL, generateSelectSQL, getTemplates, generateTemplateKey, generateN8nCode } from '../services/storage';
import { generateEmailContent } from '../services/geminiService';
import RichTextEditor from './RichTextEditor';
import { 
  Save, ArrowLeft, Eye, Database, Wand2, Copy, Check, Code 
} from 'lucide-react';

interface Props {
  templateId?: string;
  initialTemplate?: EmailTemplate;
  onBack: () => void;
  onSave: () => void;
}

const DEFAULT_HEADER = `<div style="background-color: #f8fafc; padding: 20px; text-align: center;">
  <h1 style="color: #334155; margin: 0;">My Company</h1>
</div>`;

const DEFAULT_BODY = `<div style="padding: 20px; color: #334155; font-family: sans-serif;">
  <p>Gentile {{first_name}},</p>
  <p>This is a default message body.</p>
</div>`;

const DEFAULT_FOOTER = `<div style="background-color: #f1f5f9; padding: 15px; text-align: center; font-size: 12px; color: #64748b;">
  <p>&copy; 2024 My Company. All rights reserved.</p>
</div>`;

const Editor: React.FC<Props> = ({ initialTemplate, onBack, onSave }) => {
  const [name, setName] = useState(initialTemplate?.name || 'New Template');
  const [description, setDescription] = useState(initialTemplate?.description || '');
  const [subject, setSubject] = useState(initialTemplate?.subject || 'Welcome to our service');
  
  const [header, setHeader] = useState(initialTemplate?.header || DEFAULT_HEADER);
  const [body, setBody] = useState(initialTemplate?.body || DEFAULT_BODY);
  const [footer, setFooter] = useState(initialTemplate?.footer || DEFAULT_FOOTER);
  
  const [activeTab, setActiveTab] = useState<'header' | 'body' | 'footer'>('body');
  const [showSqlModal, setShowSqlModal] = useState(false);
  const [detectedVars, setDetectedVars] = useState<string[]>([]);
  const [isGenerating, setIsGenerating] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [aiPrompt, setAiPrompt] = useState('');
  const [showAiModal, setShowAiModal] = useState(false);
  const [nameError, setNameError] = useState('');

  // Variable detection logic
  const detectVariables = useCallback(() => {
    const regex = /\{\{([\w\d_-]+)\}\}/g;
    const allText = `${subject} ${header} ${body} ${footer}`;
    const matches = [...allText.matchAll(regex)];
    const uniqueVars = Array.from(new Set(matches.map(m => m[1])));
    setDetectedVars(uniqueVars);
  }, [header, body, footer, subject]);

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

  // Clear name error when typing
  useEffect(() => {
    if (nameError) setNameError('');
  }, [name]);

  const handleSave = async () => {
    const newKey = generateTemplateKey(name);
    
    if (!newKey) {
      setNameError('Template name cannot be empty or symbols only.');
      alert('Template name cannot be empty.');
      return;
    }

    setIsSaving(true);
    try {
        // Check for duplicates
        const allTemplates = await getTemplates();
        const isDuplicate = allTemplates.some(t => {
            // Exclude current template if we are editing
            if (initialTemplate && t.id === initialTemplate.id) return false;
            return generateTemplateKey(t.name) === newKey;
        });

        if (isDuplicate) {
            setNameError('A template with this name already exists.');
            alert('A template with this name (or resulting ID) already exists. Please choose a unique name.');
            setIsSaving(false);
            return;
        }

        const newTemplate: EmailTemplate = {
            id: initialTemplate?.id || crypto.randomUUID(),
            name,
            description,
            subject,
            header,
            body,
            footer,
            variables: detectedVars,
            updatedAt: new Date().toISOString()
        };
        await saveTemplate(newTemplate);
        onSave();
    } catch (e) {
        alert("Failed to save template. Check server logs.");
    } finally {
        setIsSaving(false);
    }
  };

  const handleAiGenerate = async () => {
    if (!aiPrompt.trim()) return;
    setIsGenerating(true);
    try {
      const generated = await generateEmailContent(aiPrompt, activeTab);
      if (activeTab === 'header') setHeader(generated);
      if (activeTab === 'body') setBody(generated);
      if (activeTab === 'footer') setFooter(generated);
      setShowAiModal(false);
      setAiPrompt('');
    } catch (e) {
      alert("Error generating content. Please check API Key configuration.");
    } finally {
      setIsGenerating(false);
    }
  };

  const tempTemplateObj = { 
    id: initialTemplate?.id || 'PREVIEW', 
    name, 
    description, 
    subject, 
    header, 
    body, 
    footer, 
    variables: detectedVars, 
    updatedAt: '' 
  };

  const currentInsertSql = showSqlModal ? generateSQL(tempTemplateObj) : '';
  const currentSelectSql = showSqlModal ? generateSelectSQL(tempTemplateObj) : '';
  const currentN8nCode = showSqlModal ? generateN8nCode(tempTemplateObj) : '';

  const getActiveContent = () => {
    switch (activeTab) {
      case 'header': return header;
      case 'body': return body;
      case 'footer': return footer;
    }
  };

  const setActiveContent = (val: string) => {
    switch (activeTab) {
      case 'header': setHeader(val); break;
      case 'body': setBody(val); break;
      case 'footer': setFooter(val); break;
    }
  };

  return (
    <div className="flex flex-col h-screen bg-slate-50">
      {/* Top Bar */}
      <header className="bg-white border-b border-slate-200 px-6 py-4 flex items-center justify-between sticky top-0 z-20 shrink-0">
        <div className="flex items-center gap-4">
          <button onClick={onBack} className="p-2 hover:bg-slate-100 rounded-full text-slate-500">
            <ArrowLeft size={20} />
          </button>
          <div>
            <h1 className="text-xl font-bold text-slate-800">
              {initialTemplate ? 'Edit Template' : 'Create Template'}
            </h1>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <button 
            onClick={() => setShowSqlModal(true)}
            className="flex items-center gap-2 px-4 py-2 text-slate-600 bg-white border border-slate-300 rounded-lg hover:bg-slate-50 font-medium transition-colors"
          >
            <Database size={18} />
            Integration
          </button>
          <button 
            onClick={handleSave}
            disabled={isSaving}
            className={`flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 font-medium transition-colors shadow-sm ${isSaving ? 'opacity-70 cursor-wait' : ''}`}
          >
            <Save size={18} />
            {isSaving ? 'Saving...' : 'Save Template'}
          </button>
        </div>
      </header>

      <div className="flex flex-1 overflow-hidden">
        {/* Left: Inputs */}
        <div className="w-1/2 flex flex-col border-r border-slate-200 bg-white overflow-y-auto custom-scrollbar">
          
          <div className="p-6 space-y-6">
            {/* Metadata */}
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-1">Template Name</label>
                <input 
                  type="text" 
                  value={name}
                  onChange={e => setName(e.target.value)}
                  className={`w-full px-3 py-2 border rounded-md focus:ring-2 focus:ring-brand-500 outline-none bg-white ${nameError ? 'border-red-500 focus:border-red-500' : 'border-slate-300 focus:border-brand-500'}`}
                  placeholder="e.g., Welcome Email"
                />
                {nameError && <p className="text-red-500 text-xs mt-1">{nameError}</p>}
                <p className="text-xs text-slate-400 mt-1">Must be unique. Used to generate the database key: <span className="font-mono bg-slate-100 px-1">{generateTemplateKey(name) || '...'}</span></p>
              </div>
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-1">Email Subject</label>
                <input 
                  type="text" 
                  value={subject}
                  onChange={e => setSubject(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-300 rounded-md focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none bg-white"
                  placeholder="Subject line... (supports {{placeholders}})"
                />
              </div>
            </div>

            {/* Variable Manager */}
            <div className="bg-slate-50 p-4 rounded-lg border border-slate-200">
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-bold text-slate-500 uppercase tracking-wider">Active Variables</span>
                <span className="text-xs text-slate-400">Auto-detected from text</span>
              </div>
              <div className="flex flex-wrap gap-2">
                {detectedVars.length === 0 && <span className="text-sm text-slate-400 italic">No variables detected yet. Type {'{{name}}'} to add one.</span>}
                {detectedVars.map(v => (
                  <span key={v} className="px-2 py-1 bg-brand-100 text-brand-700 text-sm rounded border border-brand-200 font-mono">
                    {`{{${v}}}`}
                  </span>
                ))}
              </div>
            </div>

            {/* Tabs */}
            <div className="flex border-b border-slate-200">
              {(['header', 'body', 'footer'] as const).map((tab) => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={`px-4 py-2 font-medium text-sm capitalize ${
                    activeTab === tab 
                      ? 'text-brand-600 border-b-2 border-brand-600' 
                      : 'text-slate-500 hover:text-slate-700'
                  }`}
                >
                  {tab}
                </button>
              ))}
            </div>

            {/* Editor Area */}
            <div className="relative">
              <div className="flex justify-between items-center mb-2">
                <label className="text-sm font-semibold text-slate-700">Content Editor</label>
                <div className="flex gap-2">
                   <button 
                    onClick={() => setShowAiModal(true)}
                    className="text-xs flex items-center gap-1 text-purple-600 hover:text-purple-700 font-medium bg-purple-50 px-2 py-1 rounded"
                  >
                    <Wand2 size={14} />
                    Generate with AI
                  </button>
                </div>
              </div>
              
              <div className="h-[400px]">
                <RichTextEditor
                  key={activeTab} // Force remount on tab change to sync contentEditable
                  value={getActiveContent()}
                  onChange={setActiveContent}
                  placeholder={`Design your ${activeTab} here...`}
                  className="h-full shadow-sm"
                />
              </div>

              <p className="mt-2 text-xs text-slate-500">
                Use the "Variable" button in the toolbar to insert placeholders like {'{{name}}'}.
              </p>
            </div>
          </div>
        </div>

        {/* Right: Live Preview */}
        <div className="w-1/2 bg-slate-100 flex flex-col overflow-hidden">
          <div className="p-3 bg-white border-b border-slate-200 flex justify-between items-center shadow-sm z-10 shrink-0">
            <span className="font-semibold text-slate-600 flex items-center gap-2">
              <Eye size={18} /> Live Preview
            </span>
            <div className="text-xs text-slate-400">
              Renders as standard HTML
            </div>
          </div>
          {/* Scrollable container: flex-1 ensures it takes available space, overflow-y-auto enables scrolling */}
          <div className="flex-1 p-8 overflow-y-auto custom-scrollbar">
            {/* mx-auto centers the card without using flexbox on the parent which can cause scroll issues */}
            <div className="w-full max-w-2xl bg-white shadow-xl rounded-lg overflow-hidden min-h-[600px] flex flex-col mx-auto">
               {/* Simulate Subject Line in Preview */}
               <div className="bg-slate-50 border-b border-slate-100 p-4">
                  <span className="text-xs font-bold text-slate-400 uppercase">Subject:</span>
                  <p className="text-sm font-medium text-slate-800">{subject.replace(/\{\{([\w\d_-]+)\}\}/g, (match, p1) => `<span class="bg-yellow-100 text-yellow-800 px-1 rounded">${match}</span>`)}</p>
               </div>
               
               {/* Email Content */}
               <div dangerouslySetInnerHTML={{ __html: header }} />
               <div dangerouslySetInnerHTML={{ __html: body }} className="flex-1" />
               <div dangerouslySetInnerHTML={{ __html: footer }} />
            </div>
          </div>
        </div>
      </div>

      {/* SQL Modal */}
      {showSqlModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-4xl p-6 flex flex-col max-h-[90vh]">
             <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-bold text-slate-800 flex items-center gap-2">
                  <Database size={20} className="text-brand-600"/>
                  Integration Details
                </h3>
                <button onClick={() => setShowSqlModal(false)} className="text-slate-400 hover:text-slate-600">
                  <span className="text-2xl">&times;</span>
                </button>
             </div>
             
             <div className="space-y-8 overflow-y-auto px-1 pb-4">
                {/* INSERT Section */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2 block">1. Setup (Run once in DB)</label>
                    <div className="relative">
                      <pre className="bg-slate-900 text-slate-100 p-4 rounded-lg overflow-x-auto text-sm font-mono custom-scrollbar h-40">
                        {currentInsertSql}
                      </pre>
                      <button 
                        onClick={() => navigator.clipboard.writeText(currentInsertSql)}
                        className="absolute top-2 right-2 p-2 bg-slate-700 text-white rounded hover:bg-slate-600"
                        title="Copy INSERT SQL"
                      >
                        <Copy size={16} />
                      </button>
                    </div>
                  </div>

                  <div>
                     <label className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2 block">2. Fetch (n8n SQL Node)</label>
                     <div className="relative">
                      <pre className="bg-slate-800 text-slate-50 p-4 rounded-lg overflow-x-auto text-sm font-mono custom-scrollbar h-40">
                        {currentSelectSql}
                      </pre>
                      <button 
                        onClick={() => navigator.clipboard.writeText(currentSelectSql)}
                        className="absolute top-2 right-2 p-2 bg-slate-600 text-white rounded hover:bg-slate-500"
                        title="Copy SELECT SQL"
                      >
                        <Copy size={16} />
                      </button>
                    </div>
                  </div>
                </div>

                {/* n8n Code Section */}
                <div>
                   <label className="text-xs font-bold text-purple-600 uppercase tracking-wider mb-2 flex items-center gap-2">
                     <Code size={16} />
                     3. Populate (n8n Code Node)
                   </label>
                   <div className="relative">
                    <pre className="bg-slate-50 border border-slate-200 text-slate-700 p-4 rounded-lg overflow-x-auto text-sm font-mono custom-scrollbar max-h-60">
                      {currentN8nCode}
                    </pre>
                    <button 
                      onClick={() => navigator.clipboard.writeText(currentN8nCode)}
                      className="absolute top-2 right-2 p-2 bg-white border border-slate-200 text-slate-600 rounded hover:bg-slate-50 shadow-sm"
                      title="Copy JS Code"
                    >
                      <Copy size={16} />
                    </button>
                  </div>
                   <p className="text-xs text-slate-500 mt-2">
                     Paste this into a <strong>Code Node</strong> connected after your SQL node. Replace <code>REPLACE_WITH_VALUE</code> with your actual data variables (e.g. <code>$('NodeName').item.json.name</code>).
                   </p>
                </div>
             </div>
          </div>
        </div>
      )}

      {/* AI Modal */}
      {showAiModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg p-6">
             <h3 className="text-lg font-bold text-slate-800 mb-2 flex items-center gap-2">
               <Wand2 className="text-purple-600"/>
               AI Content Generator
             </h3>
             <p className="text-sm text-slate-600 mb-4">
               Describe what you want for the <strong>{activeTab}</strong> section. 
               The AI will generate HTML code with placeholders.
             </p>
             <textarea 
               className="w-full h-32 border border-slate-300 rounded p-3 text-sm focus:ring-2 focus:ring-purple-500 outline-none mb-4"
               placeholder="e.g., Write a polite notification that the user's password has been changed successfully. Include a placeholder for the user's name."
               value={aiPrompt}
               onChange={(e) => setAiPrompt(e.target.value)}
             />
             <div className="flex justify-end gap-3">
               <button 
                 onClick={() => setShowAiModal(false)}
                 className="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded"
               >
                 Cancel
               </button>
               <button 
                 onClick={handleAiGenerate}
                 disabled={isGenerating || !aiPrompt}
                 className={`px-4 py-2 bg-purple-600 text-white rounded hover:bg-purple-700 flex items-center gap-2 ${isGenerating ? 'opacity-70' : ''}`}
               >
                 {isGenerating ? 'Generating...' : 'Generate HTML'}
                 {!isGenerating && <Wand2 size={16} />}
               </button>
             </div>
             {!process.env.API_KEY && (
               <p className="mt-3 text-xs text-red-500">
                 Note: API_KEY not detected in environment. This feature requires a Gemini API key.
               </p>
             )}
          </div>
        </div>
      )}
    </div>
  );
};

export default Editor;
