import type { CSSProperties, FormEvent } from 'react';
import { useEffect, useRef, useState } from 'react';

const cardStyle: CSSProperties = {
  backgroundColor: 'var(--card-bg)',
  backgroundImage: `
    linear-gradient(to right, var(--card-grid-color) 1px, transparent 1px),
    linear-gradient(to bottom, var(--card-grid-color) 1px, transparent 1px)
  `,
  backgroundSize: '20px 20px',
};

export function WaitlistForm() {
  const [email, setEmail] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [done, setDone] = useState(false);
  const [focused, setFocused] = useState(false);

  const inputRef = useRef<HTMLInputElement>(null);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const isValid = email.trim().length > 0 && email.includes('@');

  useEffect(() => {
    const vv = window.visualViewport;
    if (!vv) return;

    const reset = () => {
      window.scrollTo(0, 0);
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
    };

    vv.addEventListener('resize', reset);
    vv.addEventListener('scroll', reset);
    return () => {
      vv.removeEventListener('resize', reset);
      vv.removeEventListener('scroll', reset);
    };
  }, []);

  const handleFocus = () => setFocused(true);

  const handleBlur = () => {
    setFocused(false);
    window.scrollTo(0, 0);
  };

  const handleSubmit = async (ev: FormEvent) => {
    ev.preventDefault();
    inputRef.current?.blur();
    const trimmed = email.trim();
    if (!trimmed || isSubmitting) return;

    setIsSubmitting(true);
    try {
      await fetch('https://alpha.officer.dev/api/waitlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: trimmed }),
      });
      setDone(true);
    } catch {
      setDone(true);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div
      ref={wrapperRef}
      className="rounded-xl border-2 border-duck-dark/30 shadow-lg p-5 transition-all duration-300 ease-out"
      style={{
        ...cardStyle,
        ...(focused && window.innerWidth < 768 ? { position: 'fixed', bottom: '40%', top: 'auto', left: '50%', transform: 'translateX(-50%)', zIndex: 50, width: wrapperRef.current?.offsetWidth } : {}),
      }}
    >
      {done ? (
        <div className="text-center">
          <h2 className="text-2xl font-bold text-duck-dark mb-2">You're on the list!</h2>
          <div className="text-sm text-duck-dark/60">
            <p>
              We'll notify <strong>{email}</strong> when Officer is ready.
            </p>
          </div>
        </div>
      ) : (
        <>
          <h2 className="text-2xl font-bold text-duck-dark mb-2">Join the Waitlist</h2>
          <p className="text-sm text-duck-dark/60 mb-6">
            Be the first to know when Officer launches.
          </p>
          <form onSubmit={handleSubmit} className="flex flex-col gap-2">
            <input
              ref={inputRef}
              type="email"
              name="email"
              value={email}
              onChange={(ev) => setEmail(ev.target.value)}
              onFocus={handleFocus}
              onBlur={handleBlur}
              placeholder="you@example.com"
              className="flex-1 h-10 rounded-md border border-input bg-background px-4 py-2.5 text-base text-duck-dark placeholder:text-muted-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
            />
            <button
              type="submit"
              disabled={!isValid || isSubmitting}
              className="w-full bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold px-6 py-2.5 rounded-lg transition-all duration-200 hover:scale-105 cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
            >
              {isSubmitting ? 'Joining...' : 'Join'}
            </button>
          </form>
        </>
      )}
    </div>
  );
}
