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

import MarketingButton from './MarketingButton';
import { buyerTypes, contactMethods, incoterms, inquiryTypes } from './marketingData';

type InquiryType = 'request_samples' | 'get_a_quote' | 'partner_with_us' | 'contact_message';
type BuyerType = 'roaster' | 'importer' | 'distributor' | 'specialty_buyer' | 'wholesaler' | 'other';
type ContactMethod = 'email' | 'phone' | 'whatsapp';
type Incoterm = 'fob' | 'cif' | 'cfr' | 'exw' | 'dap' | 'other';

type Props = {
  initialInquiryType?: string;
};

type InquiryState = {
  inquiry_type: InquiryType;
  full_name: string;
  email: string;
  phone: string;
  company_name: string;
  country: string;
  buyer_type: BuyerType;
  message: string;
  target_volume_kg: string;
  incoterm: Incoterm;
  preferred_contact_method: ContactMethod;
};

const defaultState: InquiryState = {
  inquiry_type: 'request_samples',
  full_name: '',
  email: '',
  phone: '',
  company_name: '',
  country: '',
  buyer_type: 'importer',
  message: '',
  target_volume_kg: '',
  incoterm: 'fob',
  preferred_contact_method: 'email',
};

const allowedInquiryTypes = new Set(['request_samples', 'get_a_quote', 'partner_with_us', 'contact_message']);

export default function InquiryForm({ initialInquiryType }: Props) {
  const [form, setForm] = useState<InquiryState>(defaultState);
  const [errorMessage, setErrorMessage] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    if (initialInquiryType && allowedInquiryTypes.has(initialInquiryType)) {
      setForm((current) => ({
        ...current,
        inquiry_type: initialInquiryType as InquiryType,
      }));
    }
  }, [initialInquiryType]);

  const title = useMemo(() => {
    const currentType = inquiryTypes.find((item) => item.value === form.inquiry_type);
    return currentType ? currentType.label : 'Inquiry';
  }, [form.inquiry_type]);

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

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

    if (!form.full_name.trim() || !form.email.trim() || !form.company_name.trim() || !form.country.trim() || !form.message.trim()) {
      setErrorMessage('Please complete name, email, company, country, and message.');
      return;
    }

    setIsSubmitting(true);

    try {
      await axios.post('/contact-form/inquiry', {
        data: {
          ...form,
          target_volume_kg: form.target_volume_kg ? Number(form.target_volume_kg) : null,
        },
      });
      setSuccessMessage(`Thank you. Your ${title.toLowerCase()} request has been received and our team will respond shortly.`);
      setForm((current) => ({
        ...defaultState,
        inquiry_type: current.inquiry_type,
      }));
    } catch (error) {
      console.error('Inquiry submission failed', error);
      setErrorMessage('Your request could not be submitted right now. Please try again or email info@alemdesta.com.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="rounded-[2rem] border border-[#1F3A2D]/10 bg-white p-6 shadow-[0_24px_80px_rgba(20,38,29,0.08)] md:p-8">
      <div className="mb-6">
        <p className="text-sm font-semibold uppercase tracking-[0.35em] text-[#9FB06F]">Buyer inquiry</p>
        <h3 className="font-brand-display mt-3 text-3xl text-[#1F3A2D]">{title}</h3>
        <p className="mt-3 max-w-2xl text-sm leading-7 text-[#556257]">
          Share your sourcing goals and we will tailor a response around origins, order size, process, and export handling.
        </p>
      </div>

      <form className="space-y-4" onSubmit={onSubmit}>
        <div className="grid gap-4 md:grid-cols-2">
          <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
            Inquiry type
            <select className="coffee-input" name="inquiry_type" value={form.inquiry_type} onChange={onChange}>
              {inquiryTypes.map((item) => (
                <option key={item.value} value={item.value}>
                  {item.label}
                </option>
              ))}
            </select>
          </label>
          <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
            Buyer type
            <select className="coffee-input" name="buyer_type" value={form.buyer_type} onChange={onChange}>
              {buyerTypes.map((item) => (
                <option key={item.value} value={item.value}>
                  {item.label}
                </option>
              ))}
            </select>
          </label>
        </div>

        <div className="grid gap-4 md:grid-cols-2">
          <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
            Full name
            <input className="coffee-input" name="full_name" placeholder="Your name" value={form.full_name} onChange={onChange} />
          </label>
          <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
            Email
            <input className="coffee-input" name="email" type="email" placeholder="you@company.com" value={form.email} onChange={onChange} />
          </label>
        </div>

        <div className="grid gap-4 md:grid-cols-2">
          <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
            Phone / WhatsApp
            <input className="coffee-input" name="phone" placeholder="Contact number" value={form.phone} onChange={onChange} />
          </label>
          <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
            Preferred contact method
            <select className="coffee-input" name="preferred_contact_method" value={form.preferred_contact_method} onChange={onChange}>
              {contactMethods.map((item) => (
                <option key={item.value} value={item.value}>
                  {item.label}
                </option>
              ))}
            </select>
          </label>
        </div>

        <div className="grid gap-4 md:grid-cols-2">
          <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
            Company name
            <input className="coffee-input" name="company_name" placeholder="Company" value={form.company_name} onChange={onChange} />
          </label>
          <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
            Country
            <input className="coffee-input" name="country" placeholder="Country" value={form.country} onChange={onChange} />
          </label>
        </div>

        <div className="grid gap-4 md:grid-cols-2">
          <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
            Target volume (kg)
            <input
              className="coffee-input"
              min="0"
              name="target_volume_kg"
              placeholder="Optional"
              type="number"
              value={form.target_volume_kg}
              onChange={onChange}
            />
          </label>
          <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
            Preferred Incoterm
            <select className="coffee-input" name="incoterm" value={form.incoterm} onChange={onChange}>
              {incoterms.map((item) => (
                <option key={item.value} value={item.value}>
                  {item.label}
                </option>
              ))}
            </select>
          </label>
        </div>

        <label className="space-y-2 text-sm font-medium text-[#1F3A2D]">
          Message
          <textarea
            className="coffee-input min-h-[160px] resize-y pt-3"
            name="message"
            placeholder="Tell us the origins, process style, order timing, or partnership goals you are exploring."
            value={form.message}
            onChange={onChange}
          />
        </label>

        <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <p className="text-sm text-[#667367]">Submissions are routed to the admin inquiry queue for follow-up.</p>
          <MarketingButton className="w-full md:w-auto" type="submit">
            {isSubmitting ? 'Sending request...' : 'Submit inquiry'}
          </MarketingButton>
        </div>

        {errorMessage ? <p className="text-sm text-red-600">{errorMessage}</p> : null}
        {successMessage ? (
          <div className="rounded-2xl border border-[#9FB06F]/30 bg-[#EEF3E7] px-4 py-3 text-sm text-[#1F3A2D]">{successMessage}</div>
        ) : null}
      </form>
    </div>
  );
}
