"use client";

import { useState, useEffect } from "react";

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

interface CamRates {
  group_rate?: number;
  private_rate?: number;
  free_max_minutes?: number;
  category?: string;
}

export default function LiveCamRequestButton({
  escortId,
  escortName,
}: LiveCamRequestButtonProps) {
  const [open, setOpen] = useState(false);
  const [date, setDate] = useState("");
  const [time, setTime] = useState("");
  const [message, setMessage] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState("");
  const [camRates, setCamRates] = useState<CamRates | null>(null);
  const [loadingRates, setLoadingRates] = useState(false);

  useEffect(() => {
    if (!open) return;
    setLoadingRates(true);
    fetch(`/api/livecam/settings?user_id=${escortId}`)
      .then((res) => res.json())
      .then((data) => {
        if (data.data) setCamRates(data.data);
      })
      .catch(() => {
        // Rates not available
      })
      .finally(() => setLoadingRates(false));
  }, [open, escortId]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!date || !time) {
      setError("Please select a date and time.");
      return;
    }

    const requestedAt = new Date(`${date}T${time}`);
    if (requestedAt <= new Date()) {
      setError("Please select a future date and time.");
      return;
    }

    setSubmitting(true);
    setError("");

    try {
      const res = await fetch("/api/livecam/request", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          escort_user_id: escortId,
          requested_at: requestedAt.toISOString(),
          message: message.trim(),
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to send request");
      }

      setSuccess(true);
      setTimeout(() => {
        setOpen(false);
        setSuccess(false);
        setDate("");
        setTime("");
        setMessage("");
      }, 3000);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong");
    } finally {
      setSubmitting(false);
    }
  }

  const minDate = new Date().toISOString().split("T")[0];

  return (
    <>
      <button
        onClick={() => setOpen(true)}
        className="inline-flex items-center gap-2 bg-purple-600 hover:bg-purple-700 text-white px-4 py-2.5 rounded-lg font-medium transition-colors shadow-lg shadow-purple-600/20"
      >
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
          />
        </svg>
        Request LiveCam
      </button>

      {open && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
          <div className="bg-surface rounded-xl border border-surface-light p-6 w-full max-w-md mx-4 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-text">
                Request LiveCam Session
              </h3>
              <button
                onClick={() => setOpen(false)}
                className="text-text-muted hover:text-text 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>

            {success ? (
              <div className="bg-green-900/20 border border-green-800 rounded-lg p-6 text-center">
                <svg className="w-12 h-12 mx-auto text-green-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <p className="text-green-400 font-semibold">Request Sent!</p>
                <p className="text-text-muted text-sm mt-1">
                  {escortName} will be notified and can accept or decline your request.
                </p>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-4">
                {/* Paid service warning */}
                <div className="bg-amber-900/20 border border-amber-700/30 rounded-lg p-3 flex items-start gap-3">
                  <svg className="w-5 h-5 text-amber-400 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                  </svg>
                  <div>
                    <p className="text-amber-400 text-sm font-medium">Paid Service</p>
                    <p className="text-text-muted text-xs mt-0.5">
                      This is a paid service. The escort will be notified of your request and
                      credits will be charged when the session begins.
                    </p>
                  </div>
                </div>

                {/* Escort cam rates */}
                {loadingRates ? (
                  <div className="bg-surface-light rounded-lg p-3 text-center">
                    <p className="text-text-muted text-sm">Loading rates...</p>
                  </div>
                ) : camRates ? (
                  <div className="bg-surface-light rounded-lg p-3">
                    <p className="text-sm font-medium text-text mb-2">
                      {escortName}&apos;s LiveCam Rates
                    </p>
                    <div className="grid grid-cols-2 gap-2 text-sm">
                      {camRates.group_rate != null && Number(camRates.group_rate) > 0 && (
                        <div>
                          <p className="text-text-muted text-xs">Group Rate</p>
                          <p className="text-primary font-semibold">
                            {camRates.group_rate} credits/min
                          </p>
                        </div>
                      )}
                      {camRates.private_rate != null && Number(camRates.private_rate) > 0 && (
                        <div>
                          <p className="text-text-muted text-xs">Private Rate</p>
                          <p className="text-primary font-semibold">
                            {camRates.private_rate} credits/min
                          </p>
                        </div>
                      )}
                      {camRates.free_max_minutes != null && (
                        <div>
                          <p className="text-text-muted text-xs">Free Preview</p>
                          <p className="text-primary font-semibold">
                            {camRates.free_max_minutes} min
                          </p>
                        </div>
                      )}
                      {camRates.category && (
                        <div>
                          <p className="text-text-muted text-xs">Category</p>
                          <p className="text-text font-medium">
                            {camRates.category}
                          </p>
                        </div>
                      )}
                    </div>
                  </div>
                ) : (
                  <div className="bg-surface-light rounded-lg p-3">
                    <p className="text-text-muted text-sm">
                      Rates will be shared by {escortName} when they respond to your request.
                    </p>
                  </div>
                )}

                {/* Date picker */}
                <div>
                  <label className="block text-sm font-medium text-text mb-1">
                    Preferred Date
                  </label>
                  <input
                    type="date"
                    value={date}
                    onChange={(e) => setDate(e.target.value)}
                    required
                    min={minDate}
                    className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-purple-500"
                  />
                </div>

                {/* Time picker */}
                <div>
                  <label className="block text-sm font-medium text-text mb-1">
                    Preferred Time
                  </label>
                  <input
                    type="time"
                    value={time}
                    onChange={(e) => setTime(e.target.value)}
                    required
                    className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-purple-500"
                  />
                </div>

                {/* Message */}
                <div>
                  <label className="block text-sm font-medium text-text mb-1">
                    Message (optional)
                  </label>
                  <textarea
                    rows={3}
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    maxLength={1000}
                    placeholder="Let them know what you have in mind..."
                    className="w-full bg-background border border-surface-light rounded-lg px-4 py-3 text-text placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-purple-500 resize-none"
                  />
                </div>

                {error && (
                  <div className="bg-red-900/20 border border-red-800 rounded-lg p-3 text-red-400 text-sm">
                    {error}
                  </div>
                )}

                <button
                  type="submit"
                  disabled={submitting || !date || !time}
                  className="w-full bg-purple-600 hover:bg-purple-700 disabled:opacity-50 text-white py-3 rounded-lg font-semibold transition-colors"
                >
                  {submitting ? "Sending Request..." : "Send LiveCam Request"}
                </button>
              </form>
            )}
          </div>
        </div>
      )}
    </>
  );
}
