import { useState, useEffect, useCallback } from 'react'
import type { DashboardData } from './types';
import { Mail, Trash2, Download, Upload, Plus, Pencil, Globe, Save } from 'lucide-react'

import { toast } from "sonner"
import GrapesEditor from './components/common/GrapesEditor'
import { SettingsLayout, SettingsHeader, SettingCard, ModernCardHeader, AdminButton, SecondaryButton, HeaderSaveStatus } from './components/ui/settings-ui';
import { useSettingsManager, type ModuleData } from './hooks/use-settings-manager';

interface Template {
  id: number
  name: string
  created_at: string
  updated_at: string
  content_json?: string
  content_html?: string
}

export default function EmailTemplates({ data: rootData }: { data: DashboardData }) {
  const [templates, setTemplates] = useState<Template[]>([])
  const [isEditing, setIsEditing] = useState(false)
  const [activeTemplate, setActiveTemplate] = useState<Template | null>(null)
  const [templateName, setTemplateName] = useState('')
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [sendingTest, setSendingTest] = useState(false)

  const {
    settings,
    updateSetting,
    handleSave: handleSaveSettings,
    saveStatus,
    hasUnsavedChanges,
    isSaving
  } = useSettingsManager<{ emailDomains: string[] }>({
    rootData,
    moduleData: rootData?.emailTemplatesData as unknown as ModuleData,
    initialSettings: {
      emailDomains: []
    }
  });

  const apiRestUrl = rootData?.global?.apiRestUrl || '';
  const wpRestNonce = rootData?.global?.wpRestNonce || '';

  const fetchTemplates = useCallback(async () => {
    if (!apiRestUrl) return;
    setLoading(true)
    try {
      const res = await fetch(`${apiRestUrl}/email-templates`, {
        headers: {
          'X-WP-Nonce': wpRestNonce
        }
      })
      const json = await res.json()
      if (json.success) {
        setTemplates(Array.isArray(json.templates) ? json.templates : [])
      } else {
        toast.error(json.message || 'Failed to fetch templates')
      }
    } catch {
      toast.error('Connection error')
    } finally {
      setLoading(false)
    }
  }, [apiRestUrl, wpRestNonce]);

  const handleAdd = useCallback(() => {
    setActiveTemplate(null)
    setTemplateName('')
    setIsEditing(true)
  }, []);

  // Initial load and URL handling
  useEffect(() => {
    const timer = setTimeout(() => {
      fetchTemplates()

      const params = new URLSearchParams(window.location.search);
      const action = params.get('action');
      const id = params.get('id');

      if (action === 'create') {
        handleAdd();
      } else if (action === 'edit' && id && apiRestUrl) {
        const loadInitial = async () => {
          try {
            const res = await fetch(`${apiRestUrl}/email-templates/${id}`, {
              headers: {
                'X-WP-Nonce': wpRestNonce
              }
            });
            const json = await res.json();
            if (json.success) {
              setActiveTemplate(json.data);
              setTemplateName(json.data.name);
              setIsEditing(true);
            }
          } catch (e: unknown) {
            console.error("Failed to load initial template from URL", (e as Error).message);
          }
        };
        loadInitial();
      } else {
        setIsEditing(false);
        setActiveTemplate(null);
      }
    }, 0);
    return () => clearTimeout(timer);
  }, [apiRestUrl, wpRestNonce, fetchTemplates, handleAdd, rootData.global.section])

  // Lock page scroll when editor is open
  useEffect(() => {
    const targets = [
      document.body,
      document.getElementById('wpcontent'),
      document.getElementById('wpbody-content'),
      document.getElementById('wpbody'),
    ].filter(Boolean) as HTMLElement[];

    if (isEditing) {
      targets.forEach(el => {
        el.style.overflow = 'hidden';
        el.style.height = '100vh';
      });
    } else {
      targets.forEach(el => {
        el.style.overflow = '';
        el.style.height = '';
      });
    }
    return () => {
      targets.forEach(el => {
        el.style.overflow = '';
        el.style.height = '';
      });
    };
  }, [isEditing]);

  // Update URL on state change
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    if (isEditing) {
      if (activeTemplate) {
        params.set('action', 'edit');
        params.set('id', activeTemplate.id.toString());
      } else {
        params.set('action', 'create');
        params.delete('id');
      }
    } else {
      params.delete('action');
      params.delete('id');
    }
    const newUrl = `${window.location.pathname}?${params.toString()}`;
    window.history.pushState({}, '', newUrl);
  }, [isEditing, activeTemplate]);

  const dStat = rootData?.domainStatus || window.wawpDashboardData?.domainStatus;
  const cSec = rootData?.global?.section || window.wawpDashboardData?.currentSection;
  if (dStat && dStat !== 'active' && cSec !== 'account') return null;

  const handleEdit = async (template: Template) => {
    setLoading(true)
    try {
      const res = await fetch(`${apiRestUrl}/email-templates/${template.id}`, {
        headers: {
          'X-WP-Nonce': wpRestNonce
        }
      })
      const json = await res.json()
      if (json.success) {
        setActiveTemplate(json.data)
        setTemplateName(json.data.name)
        setIsEditing(true)
      } else {
        toast.error(json.message || 'Failed to load template')
      }
    } catch {
      toast.error('Connection error')
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (id: number) => {
    if (!confirm('Are you sure you want to delete this template?')) return

    try {
      const res = await fetch(`${apiRestUrl}/email-templates/${id}`, {
        method: 'DELETE',
        headers: {
          'X-WP-Nonce': wpRestNonce
        }
      })
      const json = await res.json()
      if (json.success) {
        toast.success('Template deleted')
        fetchTemplates()
      } else {
        toast.error(json.message || 'Delete failed')
      }
    } catch {
      toast.error('Connection error')
    }
  }

  const handleSave = async (json: string, html: string) => {
    if (!templateName) {
      toast.error('Please enter a template name')
      return
    }

    setSaving(true)
    try {
      const payload = {
        id: activeTemplate?.id,
        name: templateName,
        content_json: json,
        content_html: html
      }

      const res = await fetch(`${apiRestUrl}/email-templates`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': wpRestNonce
        },
        body: JSON.stringify(payload)
      })
      const jsonRes = await res.json()
      if (jsonRes.success) {
        toast.success('Template saved successfully')
        setIsEditing(false)
        fetchTemplates()
      } else {
        toast.error(jsonRes.message || 'Save failed')
      }
    } catch {
      toast.error('Connection error')
    } finally {
      setSaving(false)
    }
  }

  const handleSendTest = async (html: string, email: string) => {
    if (!email) {
      toast.error('Recipient email address is required');
      return;
    }

    setSendingTest(true)
    try {
      const res = await fetch(`${apiRestUrl}/email-templates/test`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': wpRestNonce
        },
        body: JSON.stringify({
          email,
          name: templateName || 'Test Template',
          content_html: html
        })
      })
      const json = await res.json()
      if (json.success) {
        toast.success(json.message || 'Test email sent')
      } else {
        toast.error(json.message || 'Failed to send test email')
      }
    } catch {
      toast.error('Connection error')
    } finally {
      setSendingTest(false)
    }
  }

  const handleExport = (template: Template) => {
    const dataStr = JSON.stringify(template);
    const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
    const exportFileDefaultName = `wawp-template-${template.name.toLowerCase().replace(/\s+/g, '-')}.json`;

    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
    toast.success('Template exported successfully');
  };

  const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    input.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = async (event) => {
        try {
          const content = JSON.parse(event.target?.result as string);
          if (content.name && (content.content_json || content.content_html)) {
            setActiveTemplate(null);
            setTemplateName(`${content.name} (Imported)`);
            setActiveTemplate({
              ...content,
              id: 0,
              name: `${content.name} (Imported)`
            });
            setIsEditing(true);
            toast.success('Template imported successfully');
          } else {
            toast.error('Invalid template file format');
          }
        } catch (err) {
          toast.error('Error reading template file: ' + (err as Error).message);
        }
      };
      reader.readAsText(file);
    };
    input.click();
  };

  if (isEditing) {
    return (
      <div className="fixed inset-0 z-[9999] flex flex-col bg-white overflow-hidden">
        <GrapesEditor
          initialContentJson={activeTemplate?.content_json}
          initialContentHtml={activeTemplate?.content_html}
          onSave={handleSave}
          onBack={() => setIsEditing(false)}
          saving={saving}
          templateName={templateName}
          onNameChange={setTemplateName}
          showNameInput={true}
          height="100vh"
          onSendTest={handleSendTest}
          sendingTest={sendingTest}
        />
      </div>
    )
  }

  return (
    <SettingsLayout>
      <SettingsHeader
        title="Email Templates"
        description="Manage your reusable email designs"
      >
        <HeaderSaveStatus status={saveStatus} />
        <AdminButton
          disabled={!hasUnsavedChanges || isSaving}
          onClick={() => handleSaveSettings()}
          className="bg-[#004449] hover:bg-[#003338] text-white font-black uppercase tracking-widest text-[10px]"
          icon={Save}
        >
          {isSaving ? 'Saving...' : 'Save Changes'}
        </AdminButton>
      </SettingsHeader>

      <div className="space-y-6">
        <SettingCard>
          <ModernCardHeader
            icon={Mail}
            title="Saved Email Designs"
            description="A library of your custom email templates ready for campaign use."
            rightAction={
              <div className="flex items-center gap-2">
                <SecondaryButton
                  onClick={handleImport}
                  className="bg-white border-emerald-500/20 text-emerald-600 hover:bg-emerald-50 uppercase tracking-widest"
                  icon={Upload}
                >
                  Import
                </SecondaryButton>
                <AdminButton
                  onClick={handleAdd}
                  className="bg-emerald-500 hover:bg-emerald-600 text-white shadow-md shadow-emerald-500/10 uppercase tracking-widest"
                  icon={Plus}
                >
                  New Template
                </AdminButton>
              </div>
            }
          />

          <div className="p-1">
            {loading ? (
              <div className="flex flex-col items-center justify-center py-24 space-y-4">
                <div className="w-12 h-12 border-4 border-emerald-500/20 border-t-emerald-500 rounded-full animate-spin" />
                <p className="text-sm font-medium text-slate-400">Syncing your templates...</p>
              </div>
            ) : templates.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-24 px-6 text-center">
                <div className="w-12 h-12 bg-slate-50 rounded-[5px] flex items-center justify-center mb-6">
                  <Mail className="w-6 h-6 text-slate-300" />
                </div>
                <h3 className="text-lg font-bold text-slate-900 mb-2 uppercase tracking-tight">No templates yet</h3>
                <p className="text-xs font-medium text-slate-500 max-w-sm mb-8">
                  Click the "New Template" button to get started.
                </p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-1">
                {templates.map(template => (
                  <div key={template.id} className="group relative bg-white border border-[#dcdcde] rounded-[5px] px-6 py-5 hover:border-[#004449]/30 transition-all duration-300 flex flex-col justify-between min-h-[160px] overflow-hidden">
                    <div className="relative z-10">
                      {/* Header Row */}
                      <div className="flex items-start justify-between gap-4 mb-4">
                        <div className="flex-1 flex gap-2 min-w-0">
                          <Mail size={20} className="text-slate-800 opacity-70 shrink-0 mt-0.5 group-hover:text-[#004449] transition-all" />
                          <div className="flex-1 min-w-0">
                            <div className="text-base md:text-lg font-bold text-slate-800 leading-tight">
                              <h4 className="truncate !m-0 !p-0 !border-none !bg-transparent group-hover:text-[#004449] transition-colors">
                                {template.name}
                              </h4>
                            </div>
                            <div className="text-[11px] font-black text-slate-400 mt-1.5 uppercase tracking-widest">
                              Updated {new Date(template.updated_at).toLocaleDateString()}
                            </div>
                          </div>
                        </div>

                        <div className="flex items-center gap-1 shrink-0">
                          <button
                            onClick={() => handleExport(template)}
                            className="p-2 bg-slate-50 hover:bg-slate-100 border border-slate-100 rounded-[5px] text-slate-400 hover:text-slate-600 transition-colors"
                            title="Export Template"
                          >
                            <Download className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => handleDelete(template.id)}
                            className="p-2 bg-rose-50/30 hover:bg-rose-50 border border-rose-100/50 rounded-[5px] text-slate-400 hover:text-rose-500 transition-colors"
                            title="Delete"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </div>
                    </div>

                    <div className="relative z-10">
                      <AdminButton
                        onClick={() => handleEdit(template)}
                        className="w-full bg-[#004449]/5 group-hover:bg-[#004449] group-hover:text-white text-[#004449] border border-[#004449]/10 font-black uppercase tracking-widest text-[10px] py-3 rounded-[5px] transition-all"
                        icon={Pencil}
                      >
                        Edit Template
                      </AdminButton>
                    </div>

                    {/* Subtle pattern background / Gradient */}
                    <div className="absolute -right-6 -bottom-6 w-32 h-32 bg-[#004449]/5 rounded-full blur-2xl group-hover:bg-[#004449]/10 transition-colors pointer-events-none" />
                  </div>
                ))}
              </div>
            )}
          </div>
        </SettingCard>

        <SettingCard className="p-0 overflow-hidden">
          <ModernCardHeader
            title="Email Domain Suggestions"
            description="Manage the list of domains shown in the email autocomplete suggestions across your forms."
            icon={Globe}
          />
          <div className="p-6 md:p-8">
            <textarea
              value={Array.isArray(settings.emailDomains) ? settings.emailDomains.join(', ') : (settings.emailDomains as string || '')}
              onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => updateSetting('emailDomains', e.target.value.split(',').map(d => d.trim()).filter(d => d))}
              className="w-full p-4 bg-slate-50/50 border border-slate-200 rounded-[5px] focus:ring-2 focus:ring-[#004449] focus:bg-white outline-none text-sm font-bold shadow-none transition-all h-24"
              placeholder="gmail.com, yahoo.com, outlook.com..."
            />
            <p className="text-[10px] text-slate-400 font-medium mt-3 px-1 italic">Note: Separate domains with commas. These will appear as suggestions when users start typing their email.</p>
          </div>
        </SettingCard>
      </div>
    </SettingsLayout>
  )
}
