import React from 'react';
import { EmailTemplate } from '../types';
import { Plus, Edit, Trash2, FileCode, Search, Database, ArrowRightCircle, Code, CopyPlus, Key, HelpCircle, X, Globe, Server, Braces } from 'lucide-react';
import { generateSelectSQL, generateN8nCode, generateTemplateKey } from '../services/storage';

interface Props {
  templates: EmailTemplate[];
  onCreate: () => void;
  onEdit: (t: EmailTemplate) => void;
  onClone: (t: EmailTemplate) => void;
  onDelete: (id: string) => void;
}

const TemplateList: React.FC<Props> = ({ templates, onCreate, onEdit, onClone, onDelete }) => {
  const [search, setSearch] = React.useState('');
  const [showHelp, setShowHelp] = React.useState(false);

  const filtered = templates.filter(t => 
    t.name.toLowerCase().includes(search.toLowerCase()) || 
    t.subject.toLowerCase().includes(search.toLowerCase())
  );

  const copySelectSQL = (t: EmailTemplate, e: React.MouseEvent) => {
    e.stopPropagation();
    const sql = generateSelectSQL(t);
    navigator.clipboard.writeText(sql);
    alert('Query SELECT copiata! Usala nel tuo nodo SQL su n8n.');
  };

  const copyN8nCode = (t: EmailTemplate, e: React.MouseEvent) => {
    e.stopPropagation();
    const code = generateN8nCode(t);
    navigator.clipboard.writeText(code);
    alert('Codice JS copiato! Incollalo nel tuo nodo Code su n8n.');
  };

  const copyTemplateKey = (t: EmailTemplate, e: React.MouseEvent) => {
    e.stopPropagation();
    const key = generateTemplateKey(t.name);
    navigator.clipboard.writeText(key);
    alert(`Chiave Template '${key}' copiata negli appunti!`);
  };

  return (
    <div className="p-8 max-w-7xl mx-auto h-screen flex flex-col">
      <div className="flex justify-between items-center mb-8">
        <div>
          <h1 className="text-3xl font-bold text-slate-900 tracking-tight">Template Email</h1>
          <p className="text-slate-500 mt-1">Gestisci i template HTML per i tuoi flussi di lavoro n8n</p>
        </div>
        <button 
          onClick={onCreate}
          className="bg-brand-600 hover:bg-brand-700 text-white px-5 py-2.5 rounded-lg font-medium flex items-center gap-2 shadow-sm transition-all active:scale-95"
        >
          <Plus size={20} />
          Nuovo Template
        </button>
      </div>

      <div className="flex items-center gap-3 mb-6">
        <div className="relative w-full md:w-96">
          <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <Search className="h-5 w-5 text-slate-400" />
          </div>
          <input 
            type="text"
            placeholder="Cerca template..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-10 w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none text-slate-700 bg-white shadow-sm"
          />
        </div>
        
        <button
          onClick={() => setShowHelp(true)}
          className="p-2 bg-white text-slate-500 border border-slate-200 hover:border-brand-500 hover:text-brand-600 rounded-lg shadow-sm transition-all"
          title="Documentazione API"
        >
          <HelpCircle size={20} />
        </button>
      </div>

      {filtered.length === 0 ? (
        <div className="flex-1 flex flex-col items-center justify-center border-2 border-dashed border-slate-200 rounded-2xl bg-slate-50">
          <div className="bg-white p-4 rounded-full shadow-sm mb-4">
            <FileCode className="h-8 w-8 text-slate-400" />
          </div>
          <h3 className="text-lg font-medium text-slate-900">Nessun template trovato</h3>
          <p className="text-slate-500 mt-1 max-w-sm text-center">Inizia creando il tuo primo template email HTML per l'automazione.</p>
          <button 
            onClick={onCreate}
            className="mt-6 text-brand-600 font-medium hover:text-brand-800"
          >
            Creane uno ora &rarr;
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 overflow-y-auto pb-8 custom-scrollbar">
          {filtered.map(t => (
            <div 
              key={t.id}
              onClick={() => onEdit(t)}
              className="bg-white rounded-xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow cursor-pointer group flex flex-col h-60"
            >
              <div className="p-5 flex-1">
                <div className="flex justify-between items-start mb-2">
                  <h3 className="font-bold text-lg text-slate-800 group-hover:text-brand-600 transition-colors line-clamp-1" title={t.name}>
                    {t.name}
                  </h3>
                  <span className="text-xs bg-slate-100 text-slate-500 px-2 py-1 rounded">
                    {new Date(t.updatedAt).toLocaleDateString('it-IT')}
                  </span>
                </div>
                <p className="text-sm text-slate-500 line-clamp-2 mb-3 h-10">
                  {t.description || 'Nessuna descrizione fornita.'}
                </p>
                <div className="text-xs text-slate-400 mb-1">Oggetto:</div>
                <div className="text-sm text-slate-700 font-medium bg-slate-50 p-2 rounded truncate border border-slate-100">
                  {t.subject}
                </div>
                <div className="mt-3 flex flex-wrap gap-1">
                   {t.variables.slice(0, 3).map(v => (
                     <span key={v} className="text-[10px] bg-brand-50 text-brand-600 px-1.5 py-0.5 rounded border border-brand-100">
                       {'{{' + v + '}}'}
                     </span>
                   ))}
                   {t.variables.length > 3 && (
                     <span className="text-[10px] text-slate-400 px-1 py-0.5">+ {t.variables.length - 3} altri</span>
                   )}
                </div>
              </div>
              <div className="border-t border-slate-100 p-3 flex justify-between bg-slate-50/50 rounded-b-xl gap-2">
                <div className="flex gap-1">
                   <button 
                    onClick={(e) => copySelectSQL(t, e)}
                    className="flex items-center gap-1 text-xs font-medium text-slate-600 hover:text-brand-600 px-2 py-1 rounded hover:bg-white border border-transparent hover:border-slate-200 transition-all shadow-sm"
                    title="Copia query SELECT"
                  >
                    <ArrowRightCircle size={14} />
                    SQL
                  </button>
                  <button 
                    onClick={(e) => copyN8nCode(t, e)}
                    className="flex items-center gap-1 text-xs font-medium text-slate-600 hover:text-purple-600 px-2 py-1 rounded hover:bg-white border border-transparent hover:border-slate-200 transition-all shadow-sm"
                    title="Copia Codice JS n8n"
                  >
                    <Code size={14} />
                    JS
                  </button>
                  <button 
                    onClick={(e) => copyTemplateKey(t, e)}
                    className="flex items-center gap-1 text-xs font-medium text-slate-600 hover:text-orange-600 px-2 py-1 rounded hover:bg-white border border-transparent hover:border-slate-200 transition-all shadow-sm"
                    title="Copia Chiave Template"
                  >
                    <Key size={14} />
                    Key
                  </button>
                </div>
                <div className="flex gap-1">
                  <button 
                    onClick={(e) => { e.stopPropagation(); onClone(t); }}
                    className="p-1.5 text-slate-500 hover:text-blue-600 hover:bg-white rounded shadow-sm transition-all"
                    title="Clona Template"
                  >
                    <CopyPlus size={16} />
                  </button>
                  <button 
                    onClick={(e) => { e.stopPropagation(); onEdit(t); }}
                    className="p-1.5 text-slate-500 hover:text-brand-600 hover:bg-white rounded shadow-sm transition-all"
                    title="Modifica"
                  >
                    <Edit size={16} />
                  </button>
                  <button 
                    onClick={(e) => { e.stopPropagation(); onDelete(t.id); }}
                    className="p-1.5 text-slate-500 hover:text-red-600 hover:bg-white rounded shadow-sm transition-all"
                    title="Elimina"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* API Documentation Modal */}
      {showHelp && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4 animate-in fade-in duration-200">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-3xl flex flex-col max-h-[90vh] overflow-hidden">
            
            {/* Modal Header */}
            <div className="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-slate-50">
              <div>
                <h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
                  <Globe className="text-brand-600" size={24} />
                  Guida Integrazione API
                </h2>
                <p className="text-sm text-slate-500">Come inviare email esternamente</p>
              </div>
              <button 
                onClick={() => setShowHelp(false)}
                className="p-2 hover:bg-slate-200 rounded-full text-slate-500 transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            {/* Modal Content */}
            <div className="p-6 overflow-y-auto custom-scrollbar space-y-6">
              
              <div className="prose prose-sm text-slate-600">
                <p>
                  Dopo aver definito il template, la mail può essere inviata tramite l'endpoint API 'https://ap.site.unisa.it/api/v1/webhooks/NxUftpB17tWeJIZmzN4wl'
                </p>
                <p className="font-bold text-slate-700 mt-4">PARAMETRI DA PASSARE:</p>
              </div>

              {/* Endpoint */}
              <div className="space-y-2">
                <label className="text-xs font-bold text-slate-500 uppercase tracking-wider flex items-center gap-1">
                  <Server size={14} /> API Endpoint (POST)
                </label>
                <div className="bg-slate-900 text-slate-100 p-3 rounded-lg font-mono text-sm break-all">
                  https://ap.site.unisa.it/api/v1/webhooks/NxUftpB17tWeJIZmzN4wl
                </div>
              </div>

              {/* Headers */}
              <div className="space-y-2">
                <label className="text-xs font-bold text-slate-500 uppercase tracking-wider flex items-center gap-1">
                  <Key size={14} /> Header Richiesti
                </label>
                <div className="border border-slate-200 rounded-lg overflow-hidden">
                  <table className="w-full text-sm text-left">
                    <thead className="bg-slate-50 text-slate-600 font-medium border-b border-slate-200">
                      <tr>
                        <th className="px-4 py-2 w-1/3">Chiave Header</th>
                        <th className="px-4 py-2">Valore / Descrizione</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100 text-slate-700">
                      <tr>
                        <td className="px-4 py-3 font-mono text-brand-700">template</td>
                        <td className="px-4 py-3">
                          <span className="font-mono bg-slate-100 px-1 py-0.5 rounded text-xs">&lt;template_key&gt;</span>
                          <span className="block text-xs text-slate-500 mt-1">Recuperabile tramite l'icona Chiave nella card del template. Serve al sistema per recuperare il template corretto.</span>
                        </td>
                      </tr>
                      <tr>
                        <td className="px-4 py-3 font-mono text-brand-700">destinatario</td>
                        <td className="px-4 py-3">
                          <span className="font-mono bg-slate-100 px-1 py-0.5 rounded text-xs">email@esempio.it</span>
                          <span className="block text-xs text-slate-500 mt-1">L'indirizzo email del destinatario.</span>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Body */}
              <div className="space-y-2">
                <label className="text-xs font-bold text-slate-500 uppercase tracking-wider flex items-center gap-1">
                  <Braces size={14} /> Body della Richiesta (JSON)
                </label>
                <p className="text-xs text-slate-500 mb-2">Passa qui i valori delle variabili dinamiche.</p>
                <div className="bg-slate-50 border border-slate-200 rounded-lg p-4 font-mono text-sm text-slate-800">
                  <span className="text-slate-500">{'{'}</span>
                  <div className="pl-4">
                    <span className="text-purple-700">"nome"</span>: <span className="text-green-600">"Mario"</span>,
                  </div>
                  <div className="pl-4">
                     <span className="text-purple-700">"cognome"</span>: <span className="text-green-600">"Rossi"</span>,
                  </div>
                  <div className="pl-4">
                     <span className="text-purple-700">"email"</span>: <span className="text-green-600">"mrossi@unisa.it"</span>
                  </div>
                  <span className="text-slate-500">{'}'}</span>
                </div>
              </div>

            </div>

            {/* Modal Footer */}
            <div className="p-4 bg-slate-50 border-t border-slate-200 flex justify-end">
              <button 
                onClick={() => setShowHelp(false)}
                className="px-4 py-2 bg-brand-600 text-white font-medium rounded hover:bg-brand-700 transition-colors"
              >
                Chiudi Guida
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TemplateList;
