"use client";

import { useState } from "react";
import { useSession } from "next-auth/react";
import Link from "next/link";

const CATEGORIES = [
  { value: "no-show", label: "No-show" },
  { value: "boundary-violation", label: "Boundary Violation" },
  { value: "aggression", label: "Aggression or Threats" },
  { value: "harassment", label: "Harassment" },
  { value: "fraud", label: "Fraud or Scam" },
  { value: "substance-abuse", label: "Substance Abuse" },
  { value: "excellent-experience", label: "Excellent Experience" },
  { value: "professional", label: "Professional & Respectful" },
  { value: "other", label: "Other" },
] as const;

export default function IncidentReportPage() {
  const { data: session } = useSession();
  const [type, setType] = useState<"positive" | "negative">("negative");
  const [category, setCategory] = useState("");
  const [description, setDescription] = useState("");
  const [severity, setSeverity] = useState(3);
  const [hoverSeverity, setHoverSeverity] = useState<number | null>(null);
  const [reportedIdAw, setReportedIdAw] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    // Tell the user WHY the form refused to submit instead of returning
    // silently — prior behaviour left users staring at a non-responsive
    // button when a category wasn't selected.
    if (!category) {
      setError("Please choose a category before submitting.");
      return;
    }
    if (!description.trim()) {
      setError("Please describe the issue in the description box.");
      return;
    }

    setSubmitting(true);
    setError(null);

    try {
      const res = await fetch("/api/safety/report", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          type,
          category,
          description: description.trim(),
          severity,
          reported_id_aw: reportedIdAw.trim() || null,
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        setError(data.error || "Failed to submit report");
        return;
      }

      setSubmitted(true);
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  if (!session?.user) {
    return (
      <div className="max-w-2xl mx-auto">
        <div className="bg-surface rounded-lg p-8 text-center">
          <h1 className="text-2xl font-bold mb-4">Incident Report</h1>
          <p className="text-text-muted mb-4">Please log in to file a report.</p>
          <Link
            href="/login"
            className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors"
          >
            Log In
          </Link>
        </div>
      </div>
    );
  }

  if (submitted) {
    return (
      <div className="max-w-2xl mx-auto">
        <div className="bg-surface rounded-lg p-8 text-center">
          <div className="w-20 h-20 rounded-full bg-green-500/20 flex items-center justify-center mx-auto mb-4">
            <svg className="w-10 h-10 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
            </svg>
          </div>
          <h1 className="text-2xl font-bold mb-2">Report Submitted</h1>
          <p className="text-text-muted">
            Thank you for helping keep our community safe. Your report has been filed
            confidentially and will be reviewed by our safety team.
          </p>
          <Link
            href="/safety"
            className="inline-block mt-6 bg-surface-light hover:bg-surface-light/80 text-text px-6 py-2.5 rounded-lg font-semibold transition-colors"
          >
            Back to Safety
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-text mb-2">Incident Report</h1>
        <p className="text-text-muted">
          File a confidential safety report. Your identity is protected &mdash; only
          administrators can see who filed this report.
        </p>
      </div>

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

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Report Type */}
        <div className="bg-surface rounded-lg p-6">
          <label className="block text-sm font-medium text-text mb-3">Report Type</label>
          <div className="flex gap-3">
            <button
              type="button"
              onClick={() => setType("negative")}
              className={`flex-1 py-3 rounded-lg font-semibold text-sm border transition-colors ${
                type === "negative"
                  ? "bg-red-500/20 border-red-500/50 text-red-400"
                  : "bg-surface-light border-surface-light text-text-muted hover:border-red-500/30"
              }`}
            >
              Negative Incident
            </button>
            <button
              type="button"
              onClick={() => setType("positive")}
              className={`flex-1 py-3 rounded-lg font-semibold text-sm border transition-colors ${
                type === "positive"
                  ? "bg-green-500/20 border-green-500/50 text-green-400"
                  : "bg-surface-light border-surface-light text-text-muted hover:border-green-500/30"
              }`}
            >
              Positive Experience
            </button>
          </div>
        </div>

        {/* Reported User (optional) */}
        <div className="bg-surface rounded-lg p-6">
          <label className="block text-sm font-medium text-text mb-2">
            User Profile ID <span className="text-text-muted font-normal">(optional)</span>
          </label>
          <input
            type="text"
            value={reportedIdAw}
            onChange={(e) => setReportedIdAw(e.target.value)}
            placeholder="The profile ID of the person involved"
            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-primary"
          />
        </div>

        {/* Category */}
        <div className="bg-surface rounded-lg p-6">
          <label className="block text-sm font-medium text-text mb-2">Category</label>
          <select
            value={category}
            onChange={(e) => setCategory(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-primary"
          >
            <option value="">Select a category...</option>
            {CATEGORIES.map((cat) => (
              <option key={cat.value} value={cat.value}>
                {cat.label}
              </option>
            ))}
          </select>
        </div>

        {/* Description */}
        <div className="bg-surface rounded-lg p-6">
          <label className="block text-sm font-medium text-text mb-2">Description</label>
          <textarea
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            required
            rows={5}
            placeholder="Please describe what happened..."
            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-primary resize-none"
          />
          <p className="text-text-muted text-xs mt-1">
            Be as detailed as possible. Include dates, times, and any relevant context.
          </p>
        </div>

        {/* Severity */}
        <div className="bg-surface rounded-lg p-6">
          <label className="block text-sm font-medium text-text mb-3">
            Severity
            <span className="text-text-muted font-normal ml-2">
              {severity === 1 && "(Minor)"}
              {severity === 2 && "(Low)"}
              {severity === 3 && "(Moderate)"}
              {severity === 4 && "(Serious)"}
              {severity === 5 && "(Critical)"}
            </span>
          </label>
          <div className="flex items-center gap-2">
            {[1, 2, 3, 4, 5].map((star) => (
              <button
                key={star}
                type="button"
                onClick={() => setSeverity(star)}
                onMouseEnter={() => setHoverSeverity(star)}
                onMouseLeave={() => setHoverSeverity(null)}
                className="p-1 transition-transform hover:scale-110"
              >
                <svg
                  className={`w-8 h-8 transition-colors ${
                    star <= (hoverSeverity ?? severity)
                      ? type === "positive"
                        ? "text-green-400"
                        : "text-yellow-400"
                      : "text-surface-light"
                  }`}
                  fill="currentColor"
                  viewBox="0 0 20 20"
                >
                  <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                </svg>
              </button>
            ))}
          </div>
        </div>

        {/* Anonymous Notice */}
        <div className="bg-gold/10 border border-gold/30 rounded-lg p-4 flex items-start gap-3">
          <svg className="w-5 h-5 text-gold shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
          </svg>
          <div>
            <p className="text-gold font-semibold text-sm">Your report is anonymous</p>
            <p className="text-text-muted text-sm mt-1">
              The reported user will never see who filed this report. Only platform
              administrators have access to reporter information.
            </p>
          </div>
        </div>

        <button
          type="submit"
          disabled={submitting || !category || !description.trim()}
          className="w-full bg-primary hover:bg-primary-dark text-white py-3 rounded-lg font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {submitting ? "Submitting..." : "Submit Report"}
        </button>
      </form>
    </div>
  );
}
