"use client";

import { useState } from "react";

interface RequestContentButtonProps {
  escortId: number;
  escortName: string;
}

export default function RequestContentButton({ escortId, escortName }: RequestContentButtonProps) {
  const [open, setOpen] = useState(false);
  const [type, setType] = useState("photo");
  const [description, setDescription] = useState("");
  const [budget, setBudget] = useState("");
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!description.trim()) return;

    setSending(true);
    try {
      const body = `[Custom Content Request]\nType: ${type}\nBudget: ${budget || "Open"} credits\n\n${description.trim()}`;
      const res = await fetch("/api/messages", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ recipient_id: escortId, body }),
      });
      if (res.ok) {
        setSent(true);
        setTimeout(() => {
          setOpen(false);
          setSent(false);
          setDescription("");
          setBudget("");
          setType("photo");
        }, 2000);
      } else {
        const data = await res.json().catch(() => ({}));
        alert(data.error || "Failed to send request. Please try again.");
      }
    } catch {
      alert("Failed to send request. Please try again.");
    } finally {
      setSending(false);
    }
  }

  return (
    <>
      <button
        onClick={() => setOpen(true)}
        className="inline-flex items-center gap-2 bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-400 hover:to-amber-400 text-black font-semibold px-5 py-2.5 rounded-lg transition-all duration-200 shadow-lg shadow-yellow-500/25 hover:shadow-yellow-500/40 text-sm"
      >
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
        Request Custom Content
      </button>

      {open && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm" onClick={() => setOpen(false)}>
          <div
            className="bg-surface rounded-2xl p-6 max-w-md w-full mx-4 border border-white/10 shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-white">Request Custom Content</h3>
              <button onClick={() => setOpen(false)} className="text-text-muted hover:text-white transition-colors">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {sent ? (
              <div className="text-center py-8">
                <svg className="w-12 h-12 text-green-400 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
                <p className="text-white font-medium">Request sent to {escortName}!</p>
                <p className="text-text-muted text-sm mt-1">They will reply via messages.</p>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-4">
                <p className="text-text-muted text-sm">
                  Request custom content from <span className="text-white font-medium">{escortName}</span>. Your request will be sent as a message.
                </p>

                <div>
                  <label className="block text-sm font-medium text-text-muted mb-1.5">Content Type</label>
                  <div className="grid grid-cols-3 gap-2">
                    {["photo", "video", "custom"].map((t) => (
                      <button
                        key={t}
                        type="button"
                        onClick={() => setType(t)}
                        className={`px-3 py-2 rounded-lg text-sm font-medium transition-all ${
                          type === t
                            ? "bg-gold text-black"
                            : "bg-surface-light text-text-muted hover:text-white"
                        }`}
                      >
                        {t.charAt(0).toUpperCase() + t.slice(1)}
                      </button>
                    ))}
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-muted mb-1.5">Description</label>
                  <textarea
                    rows={3}
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="Describe what you'd like..."
                    required
                    className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-white placeholder-text-muted/50 focus:outline-none focus:ring-2 focus:ring-gold/50 text-sm"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-muted mb-1.5">Budget (credits)</label>
                  <input
                    type="number"
                    min="0"
                    value={budget}
                    onChange={(e) => setBudget(e.target.value)}
                    placeholder="Optional"
                    className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-white placeholder-text-muted/50 focus:outline-none focus:ring-2 focus:ring-gold/50 text-sm"
                  />
                </div>

                <button
                  type="submit"
                  disabled={sending || !description.trim()}
                  className="w-full bg-gold hover:bg-gold-light text-black font-semibold px-4 py-2.5 rounded-lg transition-all duration-200 text-sm disabled:opacity-50"
                >
                  {sending ? "Sending..." : "Send Request"}
                </button>
              </form>
            )}
          </div>
        </div>
      )}
    </>
  );
}
