'use client';

import { useState, useEffect, useCallback } from 'react';
import { useTournament } from '@/hooks/useTournament';
import { InviteRSVP, Player } from '@/lib/types';

export default function InvitePage() {
  const { tournament } = useTournament(5000);
  const [invites, setInvites] = useState<InviteRSVP[]>([]);
  const [players, setPlayers] = useState<Player[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ name: '', email: '', phone: '', message: '', playerId: '' });

  const fetchInvites = useCallback(async () => {
    if (!tournament) return;
    const res = await fetch(`/api/invite?tournamentId=${tournament.id}`);
    setInvites(await res.json());
  }, [tournament]);

  useEffect(() => {
    fetch('/api/players').then((r) => r.json()).then(setPlayers);
  }, []);

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!tournament || !form.name) return;

    await fetch('/api/invite', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        tournamentId: tournament.id,
        name: form.name,
        email: form.email || undefined,
        phone: form.phone || undefined,
        message: form.message || undefined,
        playerId: form.playerId || undefined,
        status: 'pending',
      }),
    });

    setForm({ name: '', email: '', phone: '', message: '', playerId: '' });
    setShowForm(false);
    fetchInvites();
  };

  const updateStatus = async (id: string, status: InviteRSVP['status']) => {
    await fetch('/api/invite', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id, status }),
    });
    fetchInvites();
  };

  const deleteInvite = async (id: string) => {
    await fetch(`/api/invite?id=${id}`, { method: 'DELETE' });
    fetchInvites();
  };

  const addFromPlayer = (player: Player) => {
    setForm({
      name: `${player.firstName} ${player.lastName}`,
      email: player.email ?? '',
      phone: player.phone ?? '',
      message: `You're invited to ${tournament?.config.name ?? 'our poker tournament'}!`,
      playerId: player.id,
    });
    setShowForm(true);
  };

  const statusColors: Record<string, string> = {
    pending: 'text-yellow-400',
    accepted: 'text-green-400',
    declined: 'text-red-400',
    maybe: 'text-blue-400',
  };

  if (!tournament) {
    return (
      <div className="max-w-4xl mx-auto px-4 py-8 text-center">
        <p className="text-white/60 mb-4">Create a tournament first to send invites.</p>
        <a href="/setup" className="btn-primary">Go to Setup</a>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-3xl font-display font-bold text-poker-gold">Invite / RSVP</h1>
          <p className="text-white/60">{tournament.config.name}</p>
        </div>
        <button onClick={() => setShowForm(true)} className="btn-primary">
          + Send Invite
        </button>
      </div>

      {showForm && (
        <div className="card mb-6">
          <h2 className="text-xl font-semibold mb-4">New Invitation</h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <input className="input-field" placeholder="Name *" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
            <input className="input-field" placeholder="Email" type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
            <input className="input-field" placeholder="Phone" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
            <textarea className="input-field" placeholder="Message" rows={3} value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} />
            <div className="flex gap-2">
              <button type="submit" className="btn-primary">Send Invite</button>
              <button type="button" onClick={() => setShowForm(false)} className="btn-secondary">Cancel</button>
            </div>
          </form>
        </div>
      )}

      <div className="card mb-6">
        <h2 className="text-lg font-semibold mb-3">Quick Add from Members</h2>
        <div className="max-h-40 overflow-y-auto space-y-1">
          {players.slice(0, 20).map((p) => (
            <button
              key={p.id}
              onClick={() => addFromPlayer(p)}
              className="w-full text-left p-2 rounded hover:bg-white/10 text-sm flex justify-between"
            >
              <span>{p.firstName} {p.lastName}</span>
              <span className="text-poker-gold">Invite →</span>
            </button>
          ))}
        </div>
      </div>

      <div className="card">
        <h2 className="text-xl font-semibold mb-4">RSVP List ({invites.length})</h2>
        {invites.length === 0 ? (
          <p className="text-white/50 text-center py-8">No invites sent yet.</p>
        ) : (
          <div className="space-y-3">
            {invites.map((inv) => (
              <div key={inv.id} className="flex flex-wrap items-center justify-between gap-3 p-3 bg-white/5 rounded-lg">
                <div>
                  <div className="font-medium">{inv.name}</div>
                  <div className="text-sm text-white/50">
                    {inv.email ?? inv.phone ?? 'No contact info'}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <span className={`text-sm font-medium capitalize ${statusColors[inv.status]}`}>
                    {inv.status}
                  </span>
                  <select
                    value={inv.status}
                    onChange={(e) => updateStatus(inv.id, e.target.value as InviteRSVP['status'])}
                    className="bg-white/10 border border-white/20 rounded px-2 py-1 text-sm"
                  >
                    <option value="pending">Pending</option>
                    <option value="accepted">Accepted</option>
                    <option value="declined">Declined</option>
                    <option value="maybe">Maybe</option>
                  </select>
                  <button onClick={() => deleteInvite(inv.id)} className="text-red-400 text-sm hover:underline">
                    Delete
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}