'use client';

import { useState, useEffect } from 'react';

const EMOJIS = ['😀', '😎', '🤓', '🥳', '🦊', '🐱', '🐶', '🦄', '🌟', '🔥', '💜', '🎮'];

interface JoinFormProps {
  roomSlug: string;
  onJoin: (name: string, emoji: string) => void;
}

export default function JoinForm({ roomSlug, onJoin }: JoinFormProps) {
  const [name, setName] = useState('');
  const [emoji, setEmoji] = useState('');
  const [isLoaded, setIsLoaded] = useState(false);

  // Load saved user info from localStorage
  useEffect(() => {
    let loadedEmoji = '';
    try {
      const stored = localStorage.getItem('rmaps_user');
      if (stored) {
        const user = JSON.parse(stored);
        if (user.name) setName(user.name);
        if (user.emoji) {
          setEmoji(user.emoji);
          loadedEmoji = user.emoji;
        }
      }
    } catch {
      // Ignore parse errors
    }
    // Set random emoji if none loaded
    if (!loadedEmoji) {
      setEmoji(EMOJIS[Math.floor(Math.random() * EMOJIS.length)]);
    }
    setIsLoaded(true);
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (name.trim()) {
      onJoin(name.trim(), emoji);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-4 bg-rmaps-dark">
      <div className="room-panel rounded-2xl p-6 max-w-sm w-full">
        <div className="text-center mb-6">
          <h1 className="text-2xl font-bold text-white mb-2">Join Room</h1>
          <p className="text-white/60 text-sm">
            You're joining <span className="text-rmaps-primary font-medium">/{roomSlug}</span>
          </p>
        </div>

        {/* Quick join option if user already has saved info */}
        {isLoaded && name && (
          <div className="mb-6 p-4 bg-rmaps-primary/10 border border-rmaps-primary/30 rounded-lg">
            <p className="text-white/60 text-sm mb-3 text-center">Welcome back!</p>
            <button
              type="button"
              onClick={() => onJoin(name.trim(), emoji)}
              className="w-full btn-primary py-3 flex items-center justify-center gap-2"
            >
              <span className="text-xl">{emoji}</span>
              <span>Join as {name}</span>
            </button>
            <p className="text-white/40 text-xs text-center mt-2">
              Or customize below
            </p>
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Emoji picker */}
          <div>
            <label className="block text-white/60 text-sm mb-2">Pick your avatar</label>
            <div className="flex flex-wrap gap-2 justify-center">
              {EMOJIS.map((e) => (
                <button
                  key={e}
                  type="button"
                  onClick={() => setEmoji(e)}
                  className={`w-10 h-10 rounded-full text-xl flex items-center justify-center transition-all ${
                    emoji === e
                      ? 'bg-rmaps-primary scale-110'
                      : 'bg-white/10 hover:bg-white/20'
                  }`}
                >
                  {e}
                </button>
              ))}
            </div>
          </div>

          {/* Name input */}
          <div>
            <label className="block text-white/60 text-sm mb-2">Your name</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Enter your name"
              className="w-full px-4 py-3 rounded-lg bg-white/10 border border-white/20 text-white placeholder-white/40 focus:border-rmaps-primary focus:outline-none"
              maxLength={20}
              autoFocus
            />
          </div>

          {/* Preview */}
          <div className="flex items-center justify-center gap-3 py-3 bg-white/5 rounded-lg">
            <div className="w-12 h-12 rounded-full bg-rmaps-primary/30 flex items-center justify-center text-2xl">
              {emoji}
            </div>
            <span className="text-white font-medium">
              {name || 'Your Name'}
            </span>
          </div>

          {/* Submit */}
          <button
            type="submit"
            disabled={!name.trim()}
            className="w-full btn-primary py-3 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            Join Room
          </button>
        </form>

        {/* Location sharing note */}
        <p className="text-white/40 text-xs text-center mt-4">
          Location sharing is optional and can be toggled anytime
        </p>
      </div>
    </div>
  );
}
