"use client";

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

const POSES = [
  "Hold up 3 fingers",
  "Touch your nose with your right hand",
  "Give a thumbs up with your left hand",
  "Make a peace sign",
  "Point to your ear",
  "Hold your hand flat under your chin",
  "Cover one eye with your hand",
  "Touch your forehead with two fingers",
  "Make an OK sign with your hand",
  "Hold up your pinky finger",
];

function getRandomPose(): string {
  return POSES[Math.floor(Math.random() * POSES.length)];
}

type VerifyStatus = "idle" | "uploading" | "submitted" | "both_verified";

export default function MutualVerificationPage() {
  const { data: session } = useSession();
  const [pose, setPose] = useState<string>(getRandomPose);
  const [file, setFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [partnerIdAw, setPartnerIdAw] = useState("");
  const [status, setStatus] = useState<VerifyStatus>("idle");
  const [error, setError] = useState<string | null>(null);
  const [partnerVerified, setPartnerVerified] = useState(false);

  const refreshPose = useCallback(() => {
    setPose(getRandomPose());
    setFile(null);
    setPreview(null);
  }, []);

  function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const selected = e.target.files?.[0];
    if (!selected) return;
    setFile(selected);
    const reader = new FileReader();
    reader.onload = () => setPreview(reader.result as string);
    reader.readAsDataURL(selected);
  }

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

    setStatus("uploading");
    setError(null);

    try {
      const formData = new FormData();
      formData.append("selfie", file);
      formData.append("pose", pose);
      formData.append("partner_id_aw", partnerIdAw.trim());

      const res = await fetch("/api/safety/verify", {
        method: "POST",
        body: formData,
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || "Verification failed");
        setStatus("idle");
        return;
      }

      if (data.both_verified) {
        setPartnerVerified(true);
        setStatus("both_verified");
      } else {
        setPartnerVerified(data.partner_verified ?? false);
        setStatus("submitted");
      }
    } catch {
      setError("Something went wrong. Please try again.");
      setStatus("idle");
    }
  }

  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">Mutual Verification</h1>
          <p className="text-text-muted mb-4">
            Please log in to use the verification system.
          </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 (status === "both_verified") {
    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>
          <div className="inline-flex items-center gap-2 bg-green-500/20 text-green-400 border border-green-500/30 px-4 py-2 rounded-full text-sm font-semibold mb-4">
            <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
            </svg>
            Verified for this meeting
          </div>
          <h1 className="text-2xl font-bold mb-2">Both Verified!</h1>
          <p className="text-text-muted">
            You and your partner have both completed the verification handshake.
            Stay safe out there.
          </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">Mutual Verification</h1>
        <p className="text-text-muted">
          Verify each other before meeting. Both parties must upload a selfie matching the assigned pose.
        </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>
      )}

      {status === "submitted" && (
        <div className="bg-gold/10 border border-gold/30 rounded-lg p-4 mb-6">
          <div className="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="M5 13l4 4L19 7" />
            </svg>
            <div>
              <p className="text-gold font-semibold text-sm">Your selfie has been submitted!</p>
              <p className="text-text-muted text-sm mt-1">
                {partnerVerified
                  ? "Your partner has also verified. You're all set!"
                  : "Waiting for your partner to complete their verification..."}
              </p>
            </div>
          </div>
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Partner ID */}
        <div className="bg-surface rounded-lg p-6">
          <label className="block text-sm font-medium text-text mb-2">
            Partner&apos;s Profile ID
          </label>
          <input
            type="text"
            value={partnerIdAw}
            onChange={(e) => setPartnerIdAw(e.target.value)}
            placeholder="Enter their AdultWorld profile ID"
            required
            disabled={status === "submitted"}
            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 disabled:opacity-50"
          />
        </div>

        {/* Pose Instruction */}
        <div className="bg-surface rounded-lg p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold">Your Pose</h2>
            {status === "idle" && (
              <button
                type="button"
                onClick={refreshPose}
                className="text-gold hover:text-gold/80 text-sm font-medium transition-colors flex items-center gap-1"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                New Pose
              </button>
            )}
          </div>

          <div className="bg-gold/10 border border-gold/30 rounded-lg p-6 text-center">
            <p className="text-gold text-xl font-bold">&ldquo;{pose}&rdquo;</p>
            <p className="text-text-muted text-sm mt-2">
              Take a selfie matching this pose and upload it below
            </p>
          </div>
        </div>

        {/* Selfie Upload */}
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">Upload Selfie</h2>

          {preview ? (
            <div className="space-y-4">
              <div className="relative w-48 h-48 mx-auto rounded-lg overflow-hidden bg-surface-light">
                <img
                  src={preview}
                  alt="Selfie preview"
                  className="w-full h-full object-cover"
                />
              </div>
              {status === "idle" && (
                <div className="text-center">
                  <button
                    type="button"
                    onClick={() => {
                      setFile(null);
                      setPreview(null);
                    }}
                    className="text-red-400 hover:text-red-300 text-sm font-medium transition-colors"
                  >
                    Remove &amp; re-take
                  </button>
                </div>
              )}
            </div>
          ) : (
            <label className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-surface-light rounded-lg cursor-pointer hover:border-gold/40 transition-colors">
              <svg className="w-10 h-10 text-text-muted mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} 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={1.5} d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
              </svg>
              <span className="text-text-muted text-sm">Click to upload selfie</span>
              <input
                type="file"
                accept="image/*"
                capture="user"
                onChange={handleFileChange}
                className="hidden"
              />
            </label>
          )}
        </div>

        {/* Submit */}
        {status === "idle" && (
          <button
            type="submit"
            disabled={!file || !partnerIdAw.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"
          >
            Submit Verification
          </button>
        )}
      </form>
    </div>
  );
}
