"use client";

import { useState, useEffect, useRef } from "react";
import { useConfirm } from "@/components/shared/use-confirm";
import { mediaUrl } from "@/lib/media";
import ManagePageSkeleton from "@/components/shared/manage-page-skeleton";

interface Video {
  id: number;
  title: string;
  url: string;
  thumbnail_url: string | null;
  is_premium: boolean;
}

export default function ManageVideosPage() {
  const fileRef = useRef<HTMLInputElement>(null);
  const [videos, setVideos] = useState<Video[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

  useEffect(() => {
    fetch("/api/profile/videos")
      .then((r) => r.json())
      .then((data) => setVideos(data.videos || []))
      .finally(() => setLoading(false));
  }, []);

  async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    setMessage(null);
    try {
      const formData = new FormData();
      formData.append("video", file);
      const res = await fetch("/api/profile/videos", { method: "POST", body: formData });
      if (!res.ok) throw new Error("Upload failed");
      const data = await res.json();
      setVideos((prev) => [data.video, ...prev]);
      setMessage({ type: "success", text: "Video uploaded successfully." });
    } catch {
      setMessage({ type: "error", text: "Failed to upload video." });
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = "";
    }
  }

  async function handleDelete(id: number) {
    if (!(await askConfirm({ title: "Delete video", message: "Delete this video?" }))) return;
    setMessage(null);
    try {
      const res = await fetch(`/api/profile/videos?id=${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Delete failed");
      setVideos((prev) => prev.filter((v) => v.id !== id));
      setMessage({ type: "success", text: "Video deleted." });
    } catch {
      setMessage({ type: "error", text: "Failed to delete video." });
    }
  }

  if (loading) return <ManagePageSkeleton />;

  return (
    <div className="max-w-4xl mx-auto">
      {confirmDialog}
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-3xl font-bold text-text">My Videos</h1>
        <button
          onClick={() => fileRef.current?.click()}
          disabled={uploading}
          className="bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50"
        >
          {uploading ? "Uploading..." : "Upload Video"}
        </button>
        <input ref={fileRef} type="file" accept="video/*" className="hidden" onChange={handleUpload} />
      </div>

      {message && (
        <div className={`p-3 rounded-lg text-sm mb-4 ${message.type === "success" ? "bg-green-900/30 text-green-400" : "bg-red-900/30 text-red-400"}`}>
          {message.text}
        </div>
      )}

      {videos.length === 0 ? (
        <div className="bg-surface rounded-lg p-12 text-center">
          <p className="text-text-muted">No videos uploaded yet.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {videos.map((video) => (
            <div key={video.id} className="bg-surface rounded-lg overflow-hidden">
              <video src={mediaUrl(video.url)} className="w-full h-48 object-cover" />
              <div className="p-4 flex items-center justify-between">
                <div>
                  <h3 className="font-semibold text-text">{video.title}</h3>
                  <span className={`text-xs ${video.is_premium ? "text-primary" : "text-text-muted"}`}>
                    {video.is_premium ? "Premium" : "Free"}
                  </span>
                </div>
                <button
                  onClick={() => handleDelete(video.id)}
                  className="text-red-400 hover:text-red-300 text-sm"
                >
                  Delete
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
