import axios from 'axios';
import React, { useState } from 'react';

import MarketingButton from './MarketingButton';

type Props = {
  source?: string;
  compact?: boolean;
};

type NewsletterState = {
  email: string;
  full_name: string;
  company_name: string;
  country: string;
};

const initialState: NewsletterState = {
  email: '',
  full_name: '',
  company_name: '',
  country: '',
};

export default function NewsletterForm({ source = 'home_footer', compact = false }: Props) {
  const [form, setForm] = useState<NewsletterState>(initialState);
  const [errorMessage, setErrorMessage] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setForm((current) => ({
      ...current,
      [event.target.name]: event.target.value,
    }));
  };

  const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setErrorMessage('');
    setSuccessMessage('');

    if (!form.email.trim()) {
      setErrorMessage('Email is required.');
      return;
    }

    setIsSubmitting(true);

    try {
      await axios.post('/contact-form/newsletter', {
        data: {
          ...form,
          source,
        },
      });
      setSuccessMessage('Thank you. You have been added to our coffee export updates list.');
      setForm(initialState);
    } catch (error) {
      console.error('Newsletter subscription failed', error);
      setErrorMessage('Subscription could not be completed right now. Please try again shortly.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form className="space-y-3" onSubmit={onSubmit}>
      {!compact && (
        <div className="grid gap-3 md:grid-cols-2">
          <input
            className="h-12 rounded-2xl border border-white/15 bg-white/10 px-4 text-sm text-white placeholder:text-white/55 focus:outline-none focus:ring-2 focus:ring-[#9FB06F]"
            name="full_name"
            placeholder="Name"
            value={form.full_name}
            onChange={onChange}
          />
          <input
            className="h-12 rounded-2xl border border-white/15 bg-white/10 px-4 text-sm text-white placeholder:text-white/55 focus:outline-none focus:ring-2 focus:ring-[#9FB06F]"
            name="company_name"
            placeholder="Company"
            value={form.company_name}
            onChange={onChange}
          />
        </div>
      )}
      <div className={`grid gap-3 ${compact ? 'md:grid-cols-[minmax(0,1fr)_auto]' : 'md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]'}`}>
        <input
          className="h-12 rounded-2xl border border-white/15 bg-white/10 px-4 text-sm text-white placeholder:text-white/55 focus:outline-none focus:ring-2 focus:ring-[#9FB06F]"
          name="email"
          placeholder="Email address"
          type="email"
          value={form.email}
          onChange={onChange}
        />
        {compact ? (
          <MarketingButton className="w-full md:w-auto" type="submit">
            {isSubmitting ? 'Subscribing...' : 'Subscribe'}
          </MarketingButton>
        ) : (
          <input
            className="h-12 rounded-2xl border border-white/15 bg-white/10 px-4 text-sm text-white placeholder:text-white/55 focus:outline-none focus:ring-2 focus:ring-[#9FB06F]"
            name="country"
            placeholder="Country"
            value={form.country}
            onChange={onChange}
          />
        )}
      </div>
      {!compact && (
        <MarketingButton className="w-full md:w-auto" type="submit">
          {isSubmitting ? 'Subscribing...' : 'Subscribe to updates'}
        </MarketingButton>
      )}
      {errorMessage ? <p className="text-sm text-[#f8caca]">{errorMessage}</p> : null}
      {successMessage ? <p className="text-sm text-[#d9c08e]">{successMessage}</p> : null}
    </form>
  );
}
