"use client";

import { useState, useEffect } from "react";
import ManagePageSkeleton from "@/components/shared/manage-page-skeleton";

type VerificationStatus = "none" | "pending" | "verified" | "rejected";

export default function VerificationPage() {
  const [status, setStatus] = useState<VerificationStatus>("none");
  const [uploading, setUploading] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/upload/verification")
      .then(async (r) => {
        if (!r.ok) {
          throw new Error(`Failed to load verification status (HTTP ${r.status})`);
        }
        return r.json();
      })
      .then((data) => {
        if (data.status) setStatus(data.status);
      })
      .catch((e) => setLoadError(e instanceof Error ? e.message : "Failed to load"))
      .finally(() => setLoading(false));
  }, []);

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

  async function handleUpload() {
    if (!file) return;
    setUploading(true);
    try {
      const formData = new FormData();
      formData.append("file", file);

      const res = await fetch("/api/upload/verification", {
        method: "POST",
        body: formData,
      });
      if (res.ok) {
        setStatus("pending");
        setFile(null);
        setPreview(null);
      } else {
        const data = await res.json().catch(() => ({}));
        alert(data.error || "Upload failed. Please try again.");
      }
    } catch {
      alert("Upload failed. Please try again.");
    } finally {
      setUploading(false);
    }
  }

  if (loading) {
    return <ManagePageSkeleton />;
  }

  if (loadError) {
    return (
      <div className="max-w-2xl mx-auto p-8">
        <div className="bg-red-500/10 border border-red-500/40 text-red-300 rounded-lg p-4 text-sm">
          {loadError}. Please refresh, or contact support if the issue persists.
        </div>
      </div>
    );
  }

  const today = new Date().toLocaleDateString(undefined, {
    day: "numeric",
    month: "long",
    year: "numeric",
  });

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <h1 className="text-3xl font-bold text-text">Photo Verification</h1>
      <p className="text-text-muted">
        Verify your identity to earn a verified badge on your profile. Verified profiles rank higher and receive more views.
      </p>

      {/* Status Display */}
      {status === "pending" && (
        <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-xl p-5 flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-yellow-500/20 flex items-center justify-center shrink-0">
            <svg className="w-5 h-5 text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <div>
            <p className="text-yellow-400 font-semibold text-sm">Verification Pending</p>
            <p className="text-text-muted text-xs mt-0.5">Your selfie is being reviewed. This usually takes 24-48 hours.</p>
          </div>
        </div>
      )}

      {status === "verified" && (
        <div className="bg-green-500/10 border border-green-500/30 rounded-xl p-5 flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-green-500/20 flex items-center justify-center shrink-0">
            <svg className="w-5 h-5 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <div>
            <p className="text-green-400 font-semibold text-sm">Verified</p>
            <p className="text-text-muted text-xs mt-0.5">Your identity has been verified. Your profile now shows a verified badge.</p>
          </div>
        </div>
      )}

      {status === "rejected" && (
        <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-5 flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center shrink-0">
            <svg className="w-5 h-5 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </div>
          <div>
            <p className="text-red-400 font-semibold text-sm">Rejected</p>
            <p className="text-text-muted text-xs mt-0.5">Your verification was rejected. Please try again with a clearer photo following the instructions below.</p>
          </div>
        </div>
      )}

      {/* Instructions */}
      {(status === "none" || status === "rejected") && (
        <>
          <div className="bg-surface rounded-xl border border-white/5 p-6">
            <h2 className="text-lg font-semibold text-white mb-4">Instructions</h2>
            <div className="space-y-3">
              <div className="flex items-start gap-3">
                <span className="w-6 h-6 rounded-full bg-gold/20 text-gold text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">1</span>
                <p className="text-text-muted text-sm">
                  Take a piece of paper and write <span className="text-white font-semibold">&quot;AdultWorld&quot;</span> and today&apos;s date: <span className="text-white font-semibold">{today}</span>
                </p>
              </div>
              <div className="flex items-start gap-3">
                <span className="w-6 h-6 rounded-full bg-gold/20 text-gold text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">2</span>
                <p className="text-text-muted text-sm">Hold the paper next to your face and take a clear selfie.</p>
              </div>
              <div className="flex items-start gap-3">
                <span className="w-6 h-6 rounded-full bg-gold/20 text-gold text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">3</span>
                <p className="text-text-muted text-sm">Make sure the text on the paper is readable and your face is clearly visible.</p>
              </div>
              <div className="flex items-start gap-3">
                <span className="w-6 h-6 rounded-full bg-gold/20 text-gold text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">4</span>
                <p className="text-text-muted text-sm">Upload the photo below. Our team will review it within 24-48 hours.</p>
              </div>
            </div>
          </div>

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

            {preview ? (
              <div className="mb-4">
                <img
                  src={preview}
                  alt="Preview"
                  className="max-h-64 rounded-lg mx-auto"
                />
              </div>
            ) : (
              <label className="block border-2 border-dashed border-surface-light rounded-xl p-8 text-center cursor-pointer hover:border-gold/50 transition-colors mb-4">
                <svg className="w-12 h-12 text-text-muted mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                </svg>
                <p className="text-text-muted text-sm">Click to upload your verification selfie</p>
                <p className="text-text-muted text-xs mt-1">JPG, PNG up to 10MB</p>
                <input
                  type="file"
                  accept="image/jpeg,image/png,image/webp"
                  onChange={handleFileChange}
                  className="hidden"
                />
              </label>
            )}

            {file && (
              <div className="flex gap-3">
                <button
                  onClick={handleUpload}
                  disabled={uploading}
                  className="flex-1 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"
                >
                  {uploading ? "Uploading..." : "Submit for Verification"}
                </button>
                <button
                  onClick={() => { setFile(null); setPreview(null); }}
                  className="px-4 py-2.5 border border-white/20 text-text-muted hover:text-white rounded-lg transition-colors text-sm"
                >
                  Cancel
                </button>
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}
