import { useState, useEffect } from 'react';
import { Drawer, Timeline, Space, Tag, Typography, Button, Popconfirm, Input, message, Spin, Grid } from 'antd';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { api } from '@/lib/api';
import type { EmailTemplateVersion } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;
const { TextArea } = Input;

interface VersionHistoryDrawerProps {
  open: boolean;
  templateId: string;
  templateName: string;
  onClose: () => void;
  onRollbackSuccess: () => void;
}

export default function VersionHistoryDrawer({
  open,
  templateId,
  templateName,
  onClose,
  onRollbackSuccess,
}: VersionHistoryDrawerProps) {
  const [versions, setVersions] = useState<EmailTemplateVersion[]>([]);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [loading, setLoading] = useState(false);
  const [rollbackNotes, setRollbackNotes] = useState('');
  const [rollingBack, setRollingBack] = useState<number | null>(null);

  useEffect(() => {
    if (open) {
      fetchVersions();
    }
  }, [open, templateId]);

  const fetchVersions = async () => {
    setLoading(true);
    try {
      const { data } = await api.get<EmailTemplateVersion[]>(`/email-templates/${templateId}/versions`);
      setVersions(data);
    } catch {
      message.error('Failed to load version history');
    } finally {
      setLoading(false);
    }
  };

  const handleRollback = async (versionNumber: number) => {
    setRollingBack(versionNumber);
    try {
      await api.post(`/email-templates/${templateId}/rollback`, {
        versionNumber,
        changeNotes: rollbackNotes || `Rolled back to version ${versionNumber}`,
      });
      message.success(`Rolled back to version ${versionNumber}`);
      setRollbackNotes('');
      onRollbackSuccess();
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { error?: string } } })?.response?.data?.error ||
        'Rollback failed';
      message.error(msg);
    } finally {
      setRollingBack(null);
    }
  };

  return (
    <Drawer
      title={`Version History: ${templateName}`}
      open={open}
      onClose={onClose}
      width={isMobile ? '100%' : 600}
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: 40 }}>
          <Spin size="large" />
        </div>
      ) : (
        <Timeline>
          {versions.map((version) => (
            <Timeline.Item key={version.id}>
              <Space direction="vertical" size="small" style={{ width: '100%' }}>
                <Space>
                  <Tag color="blue">v{version.versionNumber}</Tag>
                  <Text type="secondary">{dayjs(version.createdAt).fromNow()}</Text>
                  <Text type="secondary">({dayjs(version.createdAt).format('YYYY-MM-DD HH:mm:ss')})</Text>
                </Space>

                <div style={{ marginTop: 4 }}>
                  <Text strong>Subject:</Text>
                  <div style={{ marginTop: 4, padding: 8, backgroundColor: '#f5f5f5', borderRadius: 4 }}>
                    <Text>{version.subjectLine}</Text>
                  </div>
                </div>

                {version.changeNotes && (
                  <div style={{ marginTop: 4 }}>
                    <Text strong>Notes:</Text>
                    <div style={{ marginTop: 4 }}>
                      <Text italic>{version.changeNotes}</Text>
                    </div>
                  </div>
                )}

                <Space style={{ marginTop: 8 }}>
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    Created by {version.createdBy.name || version.createdBy.email}
                  </Text>
                </Space>

                <Space style={{ marginTop: 8 }}>
                  <Popconfirm
                    title="Rollback to this version?"
                    description={
                      <div style={{ marginTop: 8 }}>
                        <Text>This will create a new version with this content.</Text>
                        <TextArea
                          rows={3}
                          placeholder="Change notes (optional)"
                          value={rollbackNotes}
                          onChange={(e) => setRollbackNotes(e.target.value)}
                          style={{ marginTop: 8 }}
                        />
                      </div>
                    }
                    onConfirm={() => handleRollback(version.versionNumber)}
                    okText="Rollback"
                    cancelText="Cancel"
                  >
                    <Button
                      size="small"
                      type="primary"
                      loading={rollingBack === version.versionNumber}
                    >
                      Rollback to v{version.versionNumber}
                    </Button>
                  </Popconfirm>
                </Space>
              </Space>
            </Timeline.Item>
          ))}
        </Timeline>
      )}

      {!loading && versions.length === 0 && (
        <div style={{ textAlign: 'center', padding: 40 }}>
          <Text type="secondary">No version history available</Text>
        </div>
      )}
    </Drawer>
  );
}
