"use client";

import { useReducer, FormEvent } from "react";

interface WaitlistFormProps {
  className?: string;
  onSuccess?: () => void;
}

type State = {
  email: string;
  name: string;
  referralSource: string;
  isSubmitting: boolean;
  error: string | null;
  success: boolean;
};

type Action =
  | { type: "SET_EMAIL"; value: string }
  | { type: "SET_NAME"; value: string }
  | { type: "SET_REFERRAL_SOURCE"; value: string }
  | { type: "SET_SUBMITTING"; value: boolean }
  | { type: "SET_ERROR"; value: string | null }
  | { type: "SUBMIT_SUCCESS" };

const initialState: State = {
  email: "",
  name: "",
  referralSource: "",
  isSubmitting: false,
  error: null,
  success: false,
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_EMAIL":
      return { ...state, email: action.value };
    case "SET_NAME":
      return { ...state, name: action.value };
    case "SET_REFERRAL_SOURCE":
      return { ...state, referralSource: action.value };
    case "SET_SUBMITTING":
      return { ...state, isSubmitting: action.value };
    case "SET_ERROR":
      return { ...state, error: action.value };
    case "SUBMIT_SUCCESS":
      return { ...state, email: "", name: "", referralSource: "", success: true };
  }
}

export default function WaitlistForm({ className = "", onSuccess }: WaitlistFormProps) {
  const [state, dispatch] = useReducer(reducer, initialState);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    dispatch({ type: "SET_SUBMITTING", value: true });
    dispatch({ type: "SET_ERROR", value: null });

    try {
      const res = await fetch("/api/waitlist", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: state.email.trim(),
          name: state.name.trim() || undefined,
          referral_source: state.referralSource || undefined,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || "Failed to join waitlist");
      }

      dispatch({ type: "SUBMIT_SUCCESS" });
      onSuccess?.();
    } catch (err) {
      dispatch({
        type: "SET_ERROR",
        value: err instanceof Error ? err.message : "Something went wrong",
      });
    } finally {
      dispatch({ type: "SET_SUBMITTING", value: false });
    }
  };

  if (state.success) {
    return (
      <div className={`bg-gradient-to-br from-[#1a4d2e]/10 to-[#2d6a4f]/5 rounded-2xl p-8 text-center border border-[#6b8f71]/20 ${className}`}>
        <div className="w-16 h-16 bg-[#1a4d2e]/10 rounded-full flex items-center justify-center mx-auto mb-4">
          <svg className="w-8 h-8 text-[#1a4d2e]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
          </svg>
        </div>
        <h3 className="text-2xl font-bold text-[#1a1a1a] mb-2" style={{ fontFamily: "var(--font-fraunces)" }}>
          You&apos;re on the list!
        </h3>
        <p className="text-[#6b8f71]">
          We&apos;ll be in touch soon with early access details.
        </p>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className={`space-y-4 ${className}`}>
      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <label htmlFor="name" className="block text-sm font-medium text-[#1a1a1a] mb-2">
            Full Name
          </label>
          <input aria-label="Your Name"
            type="text"
            id="name"
            value={state.name}
            onChange={(e) => dispatch({ type: "SET_NAME", value: e.target.value })}
            placeholder="Your name"
            className="w-full px-4 py-3 rounded-xl border border-[#6b8f71]/30 bg-white text-[#1a1a1a] placeholder-[#888] focus:outline-none focus:ring-2 focus:ring-[#1a4d2e]/50 focus:border-[#1a4d2e] transition-all"
          />
        </div>
        <div>
          <label htmlFor="email" className="block text-sm font-medium text-[#1a1a1a] mb-2">
            Email Address <span className="text-[#c97a3e]">*</span>
          </label>
          <input aria-label="You@farm.com"
            type="email"
            id="email"
            value={state.email}
            onChange={(e) => dispatch({ type: "SET_EMAIL", value: e.target.value })}
            placeholder="you@farm.com"
            required
            className="w-full px-4 py-3 rounded-xl border border-[#6b8f71]/30 bg-white text-[#1a1a1a] placeholder-[#888] focus:outline-none focus:ring-2 focus:ring-[#1a4d2e]/50 focus:border-[#1a4d2e] transition-all"
          />
        </div>
      </div>

      <div>
        <label htmlFor="referral" className="block text-sm font-medium text-[#1a1a1a] mb-2">
          How did you hear about us?
        </label>
        <select aria-label="Referral"
          id="referral"
          value={state.referralSource}
          onChange={(e) => dispatch({ type: "SET_REFERRAL_SOURCE", value: e.target.value })}
          className="w-full px-4 py-3 rounded-xl border border-[#6b8f71]/30 bg-white text-[#1a1a1a] focus:outline-none focus:ring-2 focus:ring-[#1a4d2e]/50 focus:border-[#1a4d2e] transition-all"
        >
          <option value="">Select an option</option>
          <option value="google">Google Search</option>
          <option value="social">Social Media</option>
          <option value="friend">Friend or Colleague</option>
          <option value="event">Industry Event</option>
          <option value="podcast">Podcast</option>
          <option value="blog">Blog or Article</option>
          <option value="other">Other</option>
        </select>
      </div>

      {state.error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-xl text-red-700 text-sm">
          {state.error}
        </div>
      )}

      <button
        type="submit"
        disabled={state.isSubmitting || !state.email}
        className="w-full px-6 py-4 bg-gradient-to-r from-[#1a4d2e] to-[#2d6a4f] text-white rounded-xl font-semibold text-lg hover:from-[#2d6a4f] hover:to-[#1a4d2e] transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-[#1a4d2e]/20"
      >
        {state.isSubmitting ? (
          <span className="flex items-center justify-center gap-2">
            <svg className="animate-spin h-5 w-5" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
            </svg>
            Joining...
          </span>
        ) : (
          "Join the Waitlist"
        )}
      </button>

      <p className="text-xs text-[#888] text-center">
        We respect your privacy. No spam, ever.
      </p>
    </form>
  );
}
