import { useState, useEffect, useCallback, useRef } from 'react';
import {
  Table,
  Button,
  Input,
  Select,
  Tag,
  Space,
  Popconfirm,
  message,
  Typography,
  Badge,
  Grid,
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  MailOutlined,
  HistoryOutlined,
} from '@ant-design/icons';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { useOutletContext } from 'react-router-dom';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { api } from '@/lib/api';
import type {
  EmailTemplate,
  EmailTemplatesListResponse,
  EmailTemplatesListParams,
  EmailTemplateCategory,
  PaginationMeta,
  AppOutletContext,
} from '@/types/api';
import TestEmailModal from '@/components/email-templates/TestEmailModal';
import VersionHistoryDrawer from '@/components/email-templates/VersionHistoryDrawer';
import EmailTemplateEditor from '@/components/email-templates/EmailTemplateEditor';

dayjs.extend(relativeTime);

const { Text } = Typography;

const categoryOptions: { value: EmailTemplateCategory | 'ALL'; label: string }[] = [
  { value: 'ALL', label: 'All Categories' },
  { value: 'INFLUENCE', label: 'Influence' },
  { value: 'MAP', label: 'Map' },
  { value: 'SYSTEM', label: 'System' },
];

const activeOptions = [
  { value: 'ALL', label: 'All Status' },
  { value: 'ACTIVE', label: 'Active' },
  { value: 'INACTIVE', label: 'Inactive' },
];

export default function EmailTemplatesPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [templates, setTemplates] = useState<EmailTemplate[]>([]);
  const [pagination, setPagination] = useState<PaginationMeta>({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const searchTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
  const [categoryFilter, setCategoryFilter] = useState<EmailTemplateCategory | 'ALL'>('ALL');
  const [activeFilter, setActiveFilter] = useState<'ALL' | 'ACTIVE' | 'INACTIVE'>('ALL');
  const [testModalOpen, setTestModalOpen] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<EmailTemplate | null>(null);
  const [versionDrawerOpen, setVersionDrawerOpen] = useState(false);
  const [editingTemplateId, setEditingTemplateId] = useState<string | null>(null);

  const handleSearchChange = (value: string) => {
    setSearch(value);
    clearTimeout(searchTimerRef.current);
    searchTimerRef.current = setTimeout(() => setDebouncedSearch(value), 300);
  };

  useEffect(() => {
    return () => clearTimeout(searchTimerRef.current);
  }, []);

  const fetchTemplates = useCallback(
    async (params?: EmailTemplatesListParams) => {
      setLoading(true);
      try {
        const { data } = await api.get<EmailTemplatesListResponse>('/email-templates', {
          params: {
            page: params?.page ?? 1,
            limit: params?.limit ?? 20,
            search: params?.search ?? (debouncedSearch || undefined),
            category: categoryFilter !== 'ALL' ? categoryFilter : undefined,
            isActive: activeFilter !== 'ALL' ? activeFilter === 'ACTIVE' : undefined,
          },
        });
        setTemplates(data.templates);
        setPagination(data.pagination);
      } catch {
        message.error('Failed to load templates');
      } finally {
        setLoading(false);
      }
    },
    [debouncedSearch, categoryFilter, activeFilter]
  );

  useEffect(() => {
    fetchTemplates({ page: 1 });
  }, [debouncedSearch, categoryFilter, activeFilter]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleTableChange = (pag: TablePaginationConfig) => {
    fetchTemplates({ page: pag.current ?? 1, limit: pag.pageSize ?? 20 });
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/email-templates/${id}`);
      message.success('Template deleted');
      fetchTemplates();
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { error?: string } } })?.response?.data?.error ||
        'Failed to delete template';
      message.error(msg);
    }
  };

  const openTestEmailModal = (template: EmailTemplate) => {
    setSelectedTemplate(template);
    setTestModalOpen(true);
  };

  const openVersionDrawer = (template: EmailTemplate) => {
    setSelectedTemplate(template);
    setVersionDrawerOpen(true);
  };

  const openEditor = (template: EmailTemplate) => {
    setEditingTemplateId(template.id);
  };

  const closeEditor = () => {
    setEditingTemplateId(null);
    fetchTemplates(); // Refresh list when returning
  };

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

  const columns: ColumnsType<EmailTemplate> = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (name, record) => (
        <Space direction="vertical" size={0}>
          <Space>
            <Text strong>{name}</Text>
            {record.isSystem && <Tag color="blue">SYSTEM</Tag>}
          </Space>
          <Text type="secondary" style={{ fontSize: 12 }}>
            {record.key}
          </Text>
        </Space>
      ),
    },
    {
      title: 'Category',
      dataIndex: 'category',
      key: 'category',
      responsive: ['md'],
      render: (category: EmailTemplateCategory) => (
        <Tag color={getCategoryColor(category)}>{category}</Tag>
      ),
    },
    {
      title: 'Subject',
      dataIndex: 'subjectLine',
      key: 'subject',
      responsive: ['lg'],
      render: (subject: string) => (
        <Text ellipsis style={{ maxWidth: 300 }}>
          {subject.length > 50 ? `${subject.slice(0, 50)}...` : subject}
        </Text>
      ),
    },
    {
      title: 'Active',
      dataIndex: 'isActive',
      key: 'isActive',
      responsive: ['md'],
      render: (isActive: boolean) => (
        <Badge status={isActive ? 'success' : 'default'} text={isActive ? 'Active' : 'Inactive'} />
      ),
    },
    {
      title: 'Updated',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      responsive: ['md'],
      render: (date: string) => dayjs(date).fromNow(),
    },
    {
      title: 'Actions',
      key: 'actions',
      fixed: 'right',
      width: 280,
      render: (_, record) => (
        <Space wrap>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => openEditor(record)}
          >
            Edit
          </Button>
          <Button
            type="link"
            size="small"
            icon={<MailOutlined />}
            onClick={() => openTestEmailModal(record)}
          >
            Test
          </Button>
          <Button
            type="link"
            size="small"
            icon={<HistoryOutlined />}
            onClick={() => openVersionDrawer(record)}
          >
            Versions
          </Button>
          {!record.isSystem && (
            <Popconfirm
              title="Delete template?"
              description="This action cannot be undone."
              onConfirm={() => handleDelete(record.id)}
            >
              <Button type="link" size="small" danger icon={<DeleteOutlined />}>
                Delete
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  useEffect(() => {
    setPageHeader({ title: 'Email Templates' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  // If editing a template, show the editor instead of the list
  if (editingTemplateId) {
    return (
      <EmailTemplateEditor
        templateId={editingTemplateId}
        onClose={closeEditor}
      />
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginBottom: 16 }}>
        <Input
          placeholder="Search by name or key..."
          prefix={<SearchOutlined />}
          value={search}
          onChange={(e) => handleSearchChange(e.target.value)}
          style={{ width: isMobile ? '100%' : 200 }}
          allowClear
          size="small"
        />
        <Select
          value={categoryFilter}
          onChange={setCategoryFilter}
          options={categoryOptions}
          style={{ width: 150 }}
          size="small"
        />
        <Select
          value={activeFilter}
          onChange={setActiveFilter}
          options={activeOptions}
          style={{ width: 120 }}
          size="small"
        />
      </div>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        <Table
          columns={columns}
          dataSource={templates}
          rowKey="id"
          loading={loading}
          onChange={handleTableChange}
          pagination={{
            current: pagination.page,
            pageSize: pagination.limit,
            total: pagination.total,
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} templates`,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          scroll={{ x: 'max-content' }}
        />
      </Space>

      {selectedTemplate && (
        <TestEmailModal
          open={testModalOpen}
          template={selectedTemplate}
          onClose={() => {
            setTestModalOpen(false);
            setSelectedTemplate(null);
          }}
          onSuccess={() => {
            message.success('Test email sent successfully');
            setTestModalOpen(false);
            setSelectedTemplate(null);
          }}
        />
      )}

      {selectedTemplate && (
        <VersionHistoryDrawer
          open={versionDrawerOpen}
          templateId={selectedTemplate.id}
          templateName={selectedTemplate.name}
          onClose={() => {
            setVersionDrawerOpen(false);
            setSelectedTemplate(null);
          }}
          onRollbackSuccess={() => {
            fetchTemplates();
            setVersionDrawerOpen(false);
            setSelectedTemplate(null);
          }}
        />
      )}
    </div>
  );
}
