import { useState } from 'react';
import { Input, Button, Typography, message, Space } from 'antd';
import { MailOutlined, CheckCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useSettingsStore } from '@/stores/settings.store';
import { getErrorMessage } from '@/utils/getErrorMessage';

const { Text } = Typography;

export default function NewsletterSignup() {
  const { settings } = useSettingsStore();
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);

  // Only show if newsletter/listmonk is enabled
  if (settings?.enableNewsletter === false) return null;

  const handleSubscribe = async () => {
    if (!email.trim()) {
      message.warning('Please enter your email');
      return;
    }
    setLoading(true);
    try {
      await axios.post('/api/newsletter/subscribe', { email: email.trim() });
      setSuccess(true);
      setEmail('');
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to subscribe'));
    } finally {
      setLoading(false);
    }
  };

  if (success) {
    return (
      <div style={{ textAlign: 'center', padding: '16px 0' }}>
        <CheckCircleOutlined style={{ color: '#52c41a', fontSize: 20, marginRight: 8 }} />
        <Text style={{ color: 'rgba(255,255,255,0.75)' }}>
          Check your email to confirm your subscription
        </Text>
      </div>
    );
  }

  return (
    <div style={{ textAlign: 'center', padding: '16px 0' }}>
      <Text style={{ color: 'rgba(255,255,255,0.55)', display: 'block', marginBottom: 8, fontSize: 13 }}>
        Stay updated with the latest news
      </Text>
      <Space.Compact style={{ maxWidth: 360, width: '100%' }}>
        <Input
          prefix={<MailOutlined style={{ color: 'rgba(255,255,255,0.3)' }} />}
          placeholder="your@email.com"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          onPressEnter={handleSubscribe}
          disabled={loading}
          style={{ flex: 1 }}
        />
        <Button type="primary" onClick={handleSubscribe} loading={loading}>
          Subscribe
        </Button>
      </Space.Compact>
    </div>
  );
}
