import { useState, useEffect, useCallback } from 'react';
import { useOutletContext } from 'react-router-dom';
import {
  Button,
  Space,
  Typography,
  message,
  Spin,
  Tag,
  Grid,
  Result,
  theme,
  Input,
  Tabs,
  App,
} from 'antd';
import {
  ArrowLeftOutlined,
  SaveOutlined,
  SendOutlined,
  MailOutlined,
} from '@ant-design/icons';
import Editor from '@monaco-editor/react';
import { api } from '@/lib/api';
import type { EmailTemplate, EmailTemplateCategory } from '@/types/api';
import TestEmailModal from '@/components/email-templates/TestEmailModal';
import VariablesPanel from '@/components/email-templates/VariablesPanel';

const { Text } = Typography;

interface EmailTemplateEditorProps {
  templateId: string;
  onClose: () => void;
}

export default function EmailTemplateEditor({
  templateId,
  onClose,
}: EmailTemplateEditorProps) {
  const [template, setTemplate] = useState<EmailTemplate | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [subjectLine, setSubjectLine] = useState('');
  const [htmlContent, setHtmlContent] = useState('');
  const [textContent, setTextContent] = useState('');
  const [activeEditorTab, setActiveEditorTab] = useState<'html' | 'text'>('html');
  const [activeTab, setActiveTab] = useState('variables');
  const [testModalOpen, setTestModalOpen] = useState(false);
  const [sampleData, setSampleData] = useState<Record<string, string>>({});
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { token } = theme.useToken();
  const { modal } = App.useApp();
  const { setPageHeader } = useOutletContext<{ setPageHeader: (config: { fullBleed: boolean } | null) => void }>();

  // Enable fullBleed mode on mount, disable on unmount
  useEffect(() => {
    setPageHeader({ fullBleed: true });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  useEffect(() => {
    const fetchTemplate = async () => {
      try {
        const { data } = await api.get<EmailTemplate>(`/email-templates/${templateId}`);
        setTemplate(data);
        setSubjectLine(data.subjectLine);
        setHtmlContent(data.htmlContent);
        setTextContent(data.textContent);

        // Initialize sample data from variables
        const initialSampleData: Record<string, string> = {};
        data.variables.forEach((v) => {
          initialSampleData[v.key] = v.sampleValue || '';
        });
        setSampleData(initialSampleData);
      } catch {
        message.error('Failed to load template');
        onClose();
      } finally {
        setLoading(false);
      }
    };
    fetchTemplate();
  }, [templateId, onClose]);

  const handleSave = useCallback(async () => {
    if (!template) return;
    setSaving(true);
    try {
      const { data: updated } = await api.put<EmailTemplate>(`/email-templates/${templateId}`, {
        subjectLine,
        htmlContent,
        textContent,
      });
      setTemplate(updated);
      message.success('Template saved successfully');
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { error?: string } } })?.response?.data?.error ||
        'Failed to save template';
      message.error(msg);
    } finally {
      setSaving(false);
    }
  }, [template, templateId, subjectLine, htmlContent, textContent]);

  // Keyboard shortcut for saving (Ctrl+S)
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        handleSave();
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [handleSave]);

  const handleClose = () => {
    // Check if there are unsaved changes
    if (template && (
      subjectLine !== template.subjectLine ||
      htmlContent !== template.htmlContent ||
      textContent !== template.textContent
    )) {
      modal.confirm({
        title: 'Unsaved Changes',
        content: 'You have unsaved changes. Are you sure you want to discard them?',
        okText: 'Discard',
        cancelText: 'Continue Editing',
        okType: 'danger',
        onOk: () => onClose(),
      });
    } else {
      onClose();
    }
  };

  const processTemplate = (content: string, data: Record<string, string>): string => {
    let processed = content;

    // Process VIDEO variables first (render as card preview)
    if (template) {
      template.variables.forEach((variable) => {
        if (variable.type === 'VIDEO' && variable.videoId) {
          const mediaApiUrl = import.meta.env.VITE_MEDIA_API_URL || 'http://localhost:4100';
          const thumbUrl = `${mediaApiUrl}/api/videos/${variable.videoId}/thumbnail`;
          const videoHtml = `
            <div style="max-width: 480px; margin: 16px auto;">
              <div style="border-radius: 8px; overflow: hidden; background: #1b2838;">
                <div style="position: relative;">
                  <img src="${thumbUrl}" alt="Video thumbnail" style="width: 100%; display: block;" />
                  <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 48px; height: 48px; background: rgba(0,0,0,0.5); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                    <span style="color: #fff; font-size: 20px;">&#9654;</span>
                  </div>
                </div>
                <div style="padding: 12px 16px;">
                  <div style="color: #fff; font-size: 15px; font-weight: 600;">Video #${variable.videoId}</div>
                  <div style="color: #8899aa; font-size: 12px; margin-top: 4px;">Duration &bull; Quality &bull; Views</div>
                  <div style="margin-top: 10px; text-align: center;">
                    <span style="display: inline-block; padding: 8px 20px; background: #9d4edd; color: #fff; border-radius: 6px; font-size: 13px; font-weight: 600;">&#9654; Watch Video</span>
                  </div>
                </div>
              </div>
              <p style="margin-top: 6px; font-size: 11px; color: #999; text-align: center;">
                Recipients see a thumbnail card with a "Watch Video" button
              </p>
            </div>
          `;
          processed = processed.replace(
            new RegExp(`\\{\\{${variable.key}\\}\\}`, 'g'),
            videoHtml
          );
        }
      });
    }

    // Process TEXT variables
    Object.entries(data).forEach(([key, value]) => {
      processed = processed.replace(new RegExp(`{{${key}}}`, 'g'), value);
    });

    return processed;
  };

  const getCategoryColor = (category: EmailTemplateCategory): string => {
    const colors: Record<EmailTemplateCategory, string> = {
      INFLUENCE: 'blue',
      MAP: 'green',
      SYSTEM: 'purple',
    };
    return colors[category];
  };

  if (isMobile) {
    return (
      <div style={{ padding: 24 }}>
        <Result
          status="warning"
          title="Desktop Required"
          subTitle="The email template editor requires a desktop browser."
          extra={
            <Button type="primary" onClick={onClose}>
              Back to Templates
            </Button>
          }
        />
      </div>
    );
  }

  if (loading || !template) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
      </div>
    );
  }

  const processedHtml = processTemplate(htmlContent, sampleData);
  const processedText = processTemplate(textContent, sampleData);

  return (
    <div style={{
      height: 'calc(100vh - 64px)',
      display: 'flex',
      flexDirection: 'column',
      backgroundColor: token.colorBgContainer,
    }}>
      {/* Top Toolbar with Subject Line */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '8px 16px',
          borderBottom: `1px solid ${token.colorBorderSecondary}`,
          flexShrink: 0,
        }}
      >
        <Space>
          <Button
            type="text"
            icon={<ArrowLeftOutlined />}
            onClick={handleClose}
          />
          <Text strong>{template.name}</Text>
          <Tag color={getCategoryColor(template.category)}>{template.category}</Tag>
          {template.isSystem && <Tag color="blue">SYSTEM</Tag>}
        </Space>

        <div style={{ flex: 1, maxWidth: 600, margin: '0 24px' }}>
          <Input
            value={subjectLine}
            onChange={(e) => setSubjectLine(e.target.value)}
            placeholder="Subject Line (use {{VARIABLES}})"
            prefix={<MailOutlined />}
            size="small"
          />
        </div>

        <Space>
          <Button onClick={() => setTestModalOpen(true)} icon={<SendOutlined />}>
            Test
          </Button>
          <Button type="primary" loading={saving} onClick={handleSave} icon={<SaveOutlined />}>
            Save
          </Button>
        </Space>
      </div>

      {/* Main Editor Layout - 60/40 Tabbed */}
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* Left: Tabbed Editors (60%) */}
        <div
          style={{
            flex: '0 0 60%',
            borderRight: `1px solid ${token.colorBorderSecondary}`,
            display: 'flex',
            flexDirection: 'column',
          }}
        >
          <Tabs
            activeKey={activeEditorTab}
            onChange={(key) => setActiveEditorTab(key as 'html' | 'text')}
            style={{ flex: 1, display: 'flex', flexDirection: 'column' }}
            tabBarStyle={{ margin: 0, paddingLeft: 12, backgroundColor: token.colorBgLayout, minHeight: 38 }}
            size="small"
            items={[
              {
                key: 'html',
                label: 'HTML Content',
                children: (
                  <Editor
                    height="calc(100vh - 110px)"
                    language="html"
                    theme="vs-dark"
                    value={htmlContent}
                    onChange={(value) => setHtmlContent(value || '')}
                    options={{
                      minimap: { enabled: false },
                      fontSize: 14,
                      wordWrap: 'on',
                      lineNumbers: 'on',
                      scrollBeyondLastLine: false,
                    }}
                  />
                ),
              },
              {
                key: 'text',
                label: 'Plain Text Content',
                children: (
                  <Editor
                    height="calc(100vh - 110px)"
                    language="plaintext"
                    theme="vs-dark"
                    value={textContent}
                    onChange={(value) => setTextContent(value || '')}
                    options={{
                      minimap: { enabled: false },
                      fontSize: 14,
                      wordWrap: 'on',
                      lineNumbers: 'on',
                      scrollBeyondLastLine: false,
                    }}
                  />
                ),
              },
            ]}
          />
        </div>

        {/* Right: Utilities Panel (40%) */}
        <div
          style={{
            flex: '0 0 40%',
            display: 'flex',
            flexDirection: 'column',
            backgroundColor: token.colorBgContainer,
          }}
        >
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            style={{ flex: 1, display: 'flex', flexDirection: 'column' }}
            tabBarStyle={{ margin: 0, paddingLeft: 12, minHeight: 38 }}
            size="small"
            items={[
              {
                key: 'variables',
                label: 'Variables',
                children: (
                  <VariablesPanel
                    template={template}
                    sampleData={sampleData}
                    onSampleDataChange={setSampleData}
                  />
                ),
              },
              {
                key: 'htmlPreview',
                label: 'HTML Preview',
                children: (
                  <iframe
                    srcDoc={processedHtml}
                    style={{
                      width: '100%',
                      height: 'calc(100vh - 110px)',
                      border: 'none',
                      display: 'block',
                    }}
                    sandbox="allow-same-origin"
                    title="HTML Preview"
                  />
                ),
              },
              {
                key: 'textPreview',
                label: 'Text Preview',
                children: (
                  <pre
                    style={{
                      whiteSpace: 'pre-wrap',
                      fontFamily: 'monospace',
                      fontSize: 12,
                      lineHeight: 1.5,
                      padding: 16,
                      backgroundColor: token.colorBgLayout,
                      margin: 0,
                      height: 'calc(100vh - 110px)',
                      overflow: 'auto',
                      boxSizing: 'border-box',
                    }}
                  >
                    {processedText}
                  </pre>
                ),
              },
              {
                key: 'splitPreview',
                label: 'Split Preview',
                children: (
                  <div
                    style={{
                      display: 'flex',
                      flexDirection: 'column',
                      height: 'calc(100vh - 110px)',
                      gap: 8,
                    }}
                  >
                    <div style={{ flex: '1 1 60%', display: 'flex', flexDirection: 'column' }}>
                      <div
                        style={{
                          padding: '4px 8px',
                          backgroundColor: token.colorBgLayout,
                          borderBottom: `1px solid ${token.colorBorder}`,
                          flexShrink: 0,
                        }}
                      >
                        <Text strong style={{ fontSize: 11 }}>
                          HTML
                        </Text>
                      </div>
                      <iframe
                        srcDoc={processedHtml}
                        style={{
                          flex: 1,
                          width: '100%',
                          border: 'none',
                          display: 'block',
                        }}
                        sandbox="allow-same-origin"
                        title="HTML Preview"
                      />
                    </div>
                    <div style={{ flex: '1 1 40%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
                      <div
                        style={{
                          padding: '4px 8px',
                          backgroundColor: token.colorBgLayout,
                          borderBottom: `1px solid ${token.colorBorder}`,
                          flexShrink: 0,
                        }}
                      >
                        <Text strong style={{ fontSize: 11 }}>
                          Plain Text
                        </Text>
                      </div>
                      <pre
                        style={{
                          whiteSpace: 'pre-wrap',
                          fontFamily: 'monospace',
                          fontSize: 11,
                          lineHeight: 1.4,
                          padding: 8,
                          backgroundColor: token.colorBgLayout,
                          margin: 0,
                          flex: 1,
                          overflow: 'auto',
                        }}
                      >
                        {processedText}
                      </pre>
                    </div>
                  </div>
                ),
              },
            ]}
          />
        </div>
      </div>

      {/* Test Email Modal */}
      {testModalOpen && (
        <TestEmailModal
          open={testModalOpen}
          template={template}
          onClose={() => setTestModalOpen(false)}
          onSuccess={() => {
            message.success('Test email sent successfully');
            setTestModalOpen(false);
          }}
        />
      )}
    </div>
  );
}
