import { useState, useEffect } from 'react';
import { Drawer, Form, Input, Button, Tabs, Space, message, Table, Tag, Typography, Grid } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import type { EmailTemplate, EmailTemplateTestLog } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;

interface TestEmailModalProps {
  open: boolean;
  template: EmailTemplate;
  onClose: () => void;
  onSuccess: () => void;
}

export default function TestEmailModal({ open, template, onClose, onSuccess }: TestEmailModalProps) {
  const { user } = useAuthStore();
  const [form] = Form.useForm();
  const [sending, setSending] = useState(false);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [testData, setTestData] = useState<Record<string, string>>({});
  const [testLogs, setTestLogs] = useState<EmailTemplateTestLog[]>([]);
  const [loadingLogs, setLoadingLogs] = useState(false);

  useEffect(() => {
    if (open) {
      // Initialize form with current user email
      form.setFieldsValue({
        recipientEmail: user?.email || '',
      });

      // Initialize test data with sample values
      const initialData: Record<string, string> = {};
      template.variables.forEach((v) => {
        initialData[v.key] = v.sampleValue || '';
      });
      setTestData(initialData);

      // Fetch test logs
      fetchTestLogs();
    }
  }, [open, template, user, form]);

  const fetchTestLogs = async () => {
    setLoadingLogs(true);
    try {
      const { data } = await api.get<EmailTemplateTestLog[]>(`/email-templates/${template.id}/test-logs`, {
        params: { limit: 10 },
      });
      setTestLogs(data);
    } catch {
      // Silently fail - logs are optional
    } finally {
      setLoadingLogs(false);
    }
  };

  const handleSend = async () => {
    try {
      const values = await form.validateFields();
      setSending(true);

      await api.post(`/email-templates/${template.id}/test`, {
        recipientEmail: values.recipientEmail,
        testData,
      });

      onSuccess();
      fetchTestLogs(); // Refresh logs
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { error?: string } } })?.response?.data?.error ||
        'Failed to send test email';
      message.error(msg);
    } finally {
      setSending(false);
    }
  };

  const processTemplate = (content: string): string => {
    let processed = content;
    Object.entries(testData).forEach(([key, value]) => {
      processed = processed.replace(new RegExp(`{{${key}}}`, 'g'), value);
    });
    return processed;
  };

  const renderedHtml = processTemplate(template.htmlContent);
  const renderedText = processTemplate(template.textContent);
  const renderedSubject = processTemplate(template.subjectLine);

  const logColumns: ColumnsType<EmailTemplateTestLog> = [
    {
      title: 'Recipient',
      dataIndex: 'recipientEmail',
      key: 'recipientEmail',
    },
    {
      title: 'Status',
      dataIndex: 'success',
      key: 'success',
      render: (success: boolean) => (
        <Tag color={success ? 'success' : 'error'}>{success ? 'Sent' : 'Failed'}</Tag>
      ),
    },
    {
      title: 'Sent At',
      dataIndex: 'sentAt',
      key: 'sentAt',
      render: (date: string) => dayjs(date).fromNow(),
    },
  ];

  return (
    <Drawer
      title={`Send Test Email: ${template.name}`}
      open={open}
      onClose={onClose}
      width={isMobile ? '95vw' : 900}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      extra={
        <Button type="primary" loading={sending} onClick={handleSend}>
          Send Test Email
        </Button>
      }
    >
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        <Form form={form} layout="vertical">
          <Form.Item
            label="Recipient Email"
            name="recipientEmail"
            rules={[
              { required: true, message: 'Please enter recipient email' },
              { type: 'email', message: 'Please enter a valid email' },
            ]}
          >
            <Input placeholder="Enter email address" />
          </Form.Item>

          <div style={{ marginTop: 16 }}>
            <Text strong>Sample Data (for template variables):</Text>
          </div>

          {template.variables.map((variable) => (
            <Form.Item
              key={variable.key}
              label={
                <Space>
                  <Text>{variable.label}</Text>
                  <Text code style={{ fontSize: 11 }}>
                    {'{{' + variable.key + '}}'}
                  </Text>
                  {variable.isRequired && <Tag color="red" style={{ fontSize: 10 }}>Required</Tag>}
                </Space>
              }
              extra={variable.description}
            >
              <Input
                value={testData[variable.key] || ''}
                onChange={(e) => setTestData({ ...testData, [variable.key]: e.target.value })}
                placeholder={variable.sampleValue || ''}
              />
            </Form.Item>
          ))}
        </Form>

        <div>
          <Text strong>Preview Subject:</Text>
          <div
            style={{
              padding: 8,
              backgroundColor: '#f5f5f5',
              borderRadius: 4,
              marginTop: 8,
              fontWeight: 500,
            }}
          >
            {renderedSubject}
          </div>
        </div>

        <Tabs
          items={[
            {
              key: 'html',
              label: 'HTML Preview',
              children: (
                <iframe
                  srcDoc={renderedHtml}
                  style={{
                    width: '100%',
                    height: 400,
                    border: '1px solid #d9d9d9',
                    borderRadius: 4,
                  }}
                  sandbox="allow-same-origin"
                  title="HTML Preview"
                />
              ),
            },
            {
              key: 'text',
              label: 'Text Preview',
              children: (
                <pre
                  style={{
                    whiteSpace: 'pre-wrap',
                    maxHeight: 400,
                    overflow: 'auto',
                    padding: 12,
                    backgroundColor: '#f5f5f5',
                    borderRadius: 4,
                    fontFamily: 'monospace',
                    fontSize: 12,
                  }}
                >
                  {renderedText}
                </pre>
              ),
            },
            {
              key: 'logs',
              label: `Test History (${testLogs.length})`,
              children: (
                <Table
                  dataSource={testLogs}
                  columns={logColumns}
                  rowKey="id"
                  size="small"
                  loading={loadingLogs}
                  pagination={false}
                  locale={{ emptyText: 'No test emails sent yet' }}
                />
              ),
            },
          ]}
        />
      </Space>
    </Drawer>
  );
}
