import { createTRPCClient } from '@/trpc/client';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState, useEffect } from 'solid-js';
import { trpc } from '@/trpc';
import type { InferProcedureOutput } from '@/server/trpc/types';
import { waitlistEvents, initAnalytics, gtag } from '../../pages/analytics';

interface WaitlistFormValues {
  email: string;
  name?: string;
  source: string;
  referralCode?: string;
}

export function WaitlistForm() {
  const [formData, setFormData] = useState<WaitlistFormValues>({
    email: '',
    name: '',
    source: 'organic',
    referralCode: '',
  });
  const [error, setError] = useState<string>('');
  const [submitted, setSubmitted] = useState(false);
  const [referralCode, setReferralCode] = useState<string | null>(null);
  const [processing, setProcessing] = useState(false);
  const [analyticsEvent, setAnalyticsEvent] = useState<string | null>(null);

  const queryClient = useQueryClient();
  const client = createTRPCClient({ baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000' });

  useEffect(() => {
    initAnalytics();
  }, []);

  useEffect(() => {
    if (analyticsEvent && gtag) {
      gtag('event', analyticsEvent, {
        event_category: 'waitlist',
        event_label: formData.email || 'unknown',
        value: 1,
      });
    }
  }, [analyticsEvent, formData.email]);

  const mutation = useMutation<
    InferProcedureOutput<AppRouter, 'waitlistRouter.signup'>,
    Error,
    WaitlistFormValues
  >({
    mutationFn: async (data) => {
      return trpc.waitlistRouter.signup.mutateAsync(data);
    },
    onSuccess: (result) => {
      if (result.referralCode) {
        setReferralCode(result.referralCode);
        setSubmitted(true);
        setAnalyticsEvent('waitlist_signup_success');
      }
      queryClient.invalidateQueries({ queryKey: ['waitlistCount'] });
    },
    onError: (err) => {
      setError(err.message || 'Failed to join waitlist. Please try again.');
      setAnalyticsEvent('waitlist_signup_error');
    },
  });

  const handleSubmit = async (e: Event) => {
    e.preventDefault();
    setError('');
    setSubmitted(false);
    setReferralCode(null);
    setProcessing(true);
    setAnalyticsEvent('waitlist_form_submit');

    if (!formData.email || !formData.email.includes('@')) {
      setError('Please enter a valid email address.');
      setProcessing(false);
      return;
    }

    mutation.mutate(formData);
  };

  const handleChange = (field: keyof WaitlistFormValues, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  return (
    <div class="waitlist-container">
      <div class="waitlist-card">
        <div class="waitlist-header">
          <h1>Join the Waitlist</h1>
          <p class="waitlist-subtitle">
            Be the first to experience Scripter when we launch.
          </p>
        </div>

        {submitted && referralCode ? (
          <div class="waitlist-success">
            <h2>✓ You're on the list!</h2>
            <p>
              Thank you for joining the Scripter waitlist, {formData.email}.
            </p>
            <div class="referral-info">
              <p class="referral-label">Your referral code:</p>
              <div class="referral-code">
                <span class="code-display">{referralCode}</span>
                <button
                  class="copy-btn"
                  onClick={() => {
                    navigator.clipboard.writeText(referralCode);
                  }}
                >
                  Copy
                </button>
              </div>
              <p class="referral-hint">
                Share this code to get an early bonus when we launch!
              </p>
            </div>
          </div>
        ) : (
          <form onSubmit={handleSubmit} class="waitlist-form">
            <div class="form-group">
              <label for="name">
                Full Name <span class="optional">(optional)</span>
              </label>
              <input
                type="text"
                id="name"
                name="name"
                value={formData.name}
                onChange={(e) => handleChange('name', e.target.value)}
                placeholder="Jane Doe"
                maxLength={200}
              />
            </div>

            <div class="form-group">
              <label for="email">Email Address *</label>
              <input
                type="email"
                id="email"
                name="email"
                value={formData.email}
                onChange={(e) => {
                  handleChange('email', e.target.value);
                  waitlistEvents.email_entered(e.target.value);
                }}
                placeholder="jane@example.com"
                required
                autoComplete="email"
              />
            </div>

            <div class="form-group">
              <label for="referralCode">
                Referral Code <span class="optional">(optional)</span>
              </label>
              <input
                type="text"
                id="referralCode"
                name="referralCode"
                value={formData.referralCode}
                onChange={(e) => handleChange('referralCode', e.target.value)}
                placeholder="Enter code if you have one"
                maxLength={20}
              />
            </div>

            <button
              type="submit"
              class="submit-btn"
              disabled={processing || mutation.loading}
              onClick={() => waitlistEvents.submit_attempt()}
            >
              {processing || mutation.loading ? 'Joining...' : 'Join Waitlist'}
            </button>
          </form>
        )}

        {error && <div class="error-message">{error}</div>}

        <p class="privacy-note">
          We respect your privacy. No spam, ever.
        </p>

        <div class="waitlist-footer">
          <p class="waitlist-count">
            {(() => {
              const count = queryClient.getQueryData<number>(['waitlistCount']);
              return count ? `${count.toLocaleString()} people waiting` : 'People waiting';
            })()}
          </p>
        </div>
      </div>
    </div>
  );
}

export default WaitlistForm;
