import { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Button,
  Space,
  Typography,
  message,
  Spin,
  Tag,
  Grid,
  Result,
  theme,
  Input,
  Tabs,
  Table,
} 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';

const { Text } = Typography;

export default function EmailTemplateEditorPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  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 [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();

  useEffect(() => {
    const fetchTemplate = async () => {
      try {
        const { data } = await api.get<EmailTemplate>(`/email-templates/${id}`);
        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');
        navigate('/app/email-templates');
      } finally {
        setLoading(false);
      }
    };
    fetchTemplate();
  }, [id, navigate]);

  const handleSave = useCallback(async () => {
    if (!template) return;
    setSaving(true);
    try {
      const { data: updated } = await api.put<EmailTemplate>(`/email-templates/${id}`, {
        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, id, 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 processTemplate = (content: string, data: Record<string, string>): string => {
    let processed = content;
    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 (
      <Result
        status="warning"
        title="Desktop Required"
        subTitle="The email template editor requires a desktop browser."
        extra={
          <Button type="primary" onClick={() => navigate('/app/email-templates')}>
            Back to Templates
          </Button>
        }
      />
    );
  }

  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);

  const variableColumns = [
    {
      title: 'Variable',
      dataIndex: 'key',
      key: 'key',
      render: (key: string) => <Text code>{'{{' + key + '}}'}</Text>,
    },
    {
      title: 'Label',
      dataIndex: 'label',
      key: 'label',
    },
    {
      title: 'Description',
      dataIndex: 'description',
      key: 'description',
      render: (desc: string | null) => <Text type="secondary">{desc || '—'}</Text>,
    },
    {
      title: 'Required',
      dataIndex: 'isRequired',
      key: 'isRequired',
      render: (isRequired: boolean) => (isRequired ? <Tag color="red">Required</Tag> : <Tag>Optional</Tag>),
    },
  ];

  return (
    <div style={{ height: '100vh', display: 'flex', flexDirection: 'column', backgroundColor: token.colorBgContainer }}>
      {/* Top Toolbar */}
      <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={() => navigate('/app/email-templates')}
          />
          <Text strong>{template.name}</Text>
          <Tag color={getCategoryColor(template.category)}>{template.category}</Tag>
          {template.isSystem && <Tag color="blue">SYSTEM</Tag>}
        </Space>
        <Space>
          <Button onClick={() => setTestModalOpen(true)} icon={<SendOutlined />}>
            Test Email
          </Button>
          <Button type="primary" loading={saving} onClick={handleSave} icon={<SaveOutlined />}>
            Save
          </Button>
        </Space>
      </div>

      {/* Subject Line Input */}
      <div style={{ padding: '12px 16px', borderBottom: `1px solid ${token.colorBorderSecondary}` }}>
        <Input
          value={subjectLine}
          onChange={(e) => setSubjectLine(e.target.value)}
          placeholder="Email Subject Line (use {{VARIABLES}})"
          prefix={<MailOutlined />}
          size="large"
        />
      </div>

      {/* Main Editor Layout */}
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* HTML Editor */}
        <div style={{ flex: '0 0 40%', borderRight: `1px solid ${token.colorBorderSecondary}`, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '8px 12px', borderBottom: `1px solid ${token.colorBorderSecondary}`, backgroundColor: token.colorBgLayout }}>
            <Text strong>HTML Content</Text>
          </div>
          <div style={{ flex: 1 }}>
            <Editor
              height="100%"
              language="html"
              theme="vs-dark"
              value={htmlContent}
              onChange={(value) => setHtmlContent(value || '')}
              options={{
                minimap: { enabled: false },
                fontSize: 14,
                wordWrap: 'on',
                lineNumbers: 'on',
                scrollBeyondLastLine: false,
              }}
            />
          </div>
        </div>

        {/* Text Editor */}
        <div style={{ flex: '0 0 40%', borderRight: `1px solid ${token.colorBorderSecondary}`, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '8px 12px', borderBottom: `1px solid ${token.colorBorderSecondary}`, backgroundColor: token.colorBgLayout }}>
            <Text strong>Plain Text Content</Text>
          </div>
          <div style={{ flex: 1 }}>
            <Editor
              height="100%"
              language="plaintext"
              theme="vs-dark"
              value={textContent}
              onChange={(value) => setTextContent(value || '')}
              options={{
                minimap: { enabled: false },
                fontSize: 14,
                wordWrap: 'on',
                lineNumbers: 'on',
                scrollBeyondLastLine: false,
              }}
            />
          </div>
        </div>

        {/* Right Panel - Variables & Preview */}
        <div style={{ flex: '0 0 20%', display: 'flex', flexDirection: 'column', backgroundColor: token.colorBgContainer }}>
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            style={{ flex: 1, display: 'flex', flexDirection: 'column' }}
            items={[
              {
                key: 'variables',
                label: 'Variables',
                children: (
                  <div style={{ padding: 12, height: '100%', overflow: 'auto' }}>
                    <Table
                      dataSource={template.variables}
                      columns={variableColumns}
                      rowKey="id"
                      size="small"
                      pagination={false}
                    />
                    <div style={{ marginTop: 16 }}>
                      <Text strong>Sample Data (for preview):</Text>
                      {template.variables.map((v) => (
                        <div key={v.key} style={{ marginTop: 8 }}>
                          <Text type="secondary" style={{ fontSize: 12 }}>
                            {v.label}
                          </Text>
                          <Input
                            size="small"
                            value={sampleData[v.key] || ''}
                            onChange={(e) => setSampleData({ ...sampleData, [v.key]: e.target.value })}
                            placeholder={v.sampleValue || ''}
                          />
                        </div>
                      ))}
                    </div>
                  </div>
                ),
              },
              {
                key: 'htmlPreview',
                label: 'HTML Preview',
                children: (
                  <div style={{ height: '100%', padding: 12 }}>
                    <iframe
                      srcDoc={processedHtml}
                      style={{
                        width: '100%',
                        height: '100%',
                        border: `1px solid ${token.colorBorder}`,
                        borderRadius: 4,
                      }}
                      sandbox="allow-same-origin"
                      title="HTML Preview"
                    />
                  </div>
                ),
              },
              {
                key: 'textPreview',
                label: 'Text Preview',
                children: (
                  <div style={{ height: '100%', padding: 12, overflow: 'auto' }}>
                    <pre
                      style={{
                        whiteSpace: 'pre-wrap',
                        fontFamily: 'monospace',
                        fontSize: 12,
                        lineHeight: 1.5,
                        padding: 12,
                        backgroundColor: token.colorBgLayout,
                        borderRadius: 4,
                        border: `1px solid ${token.colorBorder}`,
                      }}
                    >
                      {processedText}
                    </pre>
                  </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>
  );
}
