"use client";

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

export default function ManageProfileCoverPage() {
  const fileRef = useRef<HTMLInputElement>(null);
  const [cover, setCover] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

  // D.8: hydrate the saved cover on mount. Earlier the page initialised
  // cover = null and only set it after a fresh upload, so users with a
  // saved cover always saw "No cover photo" placeholder. The cover is
  // stored as a Photo row with type='cover' (per /api/upload/cover).
  useEffect(() => {
    fetch("/api/profile/cover")
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (d?.cover) setCover(d.cover as string);
      })
      .catch(() => {});
  }, []);

  async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      // D.8: post to the actual upload endpoint. Earlier this hit
      // /api/manage/photos/cover which doesn't exist — every upload silently
      // 404'd and the catch-block alerted "Failed to upload cover photo."
      const formData = new FormData();
      formData.append("file", file);
      const res = await fetch("/api/upload/cover", { method: "POST", body: formData });
      if (!res.ok) throw new Error("Upload failed");
      const data = await res.json();
      setCover(data?.data?.cover ?? null);
    } catch {
      alert("Failed to upload cover photo.");
    } finally {
      setUploading(false);
    }
  }

  async function handleRemove() {
    if (!(await askConfirm({ title: "Remove cover", message: "Remove your cover photo?" }))) return;
    try {
      await fetch("/api/profile/cover", { method: "DELETE" });
      setCover(null);
    } catch {
      alert("Failed to remove cover photo.");
    }
  }

  return (
    <div className="max-w-2xl mx-auto">
      {confirmDialog}
      <h1 className="text-3xl font-bold text-text mb-6">Profile Cover Photo</h1>

      <div className="bg-surface rounded-lg p-6 space-y-6">
        <div className="w-full h-48 rounded-lg overflow-hidden bg-surface-light flex items-center justify-center">
          {cover ? (
            <img src={mediaUrl(cover)} alt="Cover" className="w-full h-full object-cover" />
          ) : (
            <span className="text-text-muted text-sm">No cover photo</span>
          )}
        </div>

        <div className="flex gap-3">
          <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 Cover"}
          </button>
          {cover && (
            <button
              onClick={handleRemove}
              className="bg-surface-light hover:bg-red-600 text-text-muted hover:text-white px-5 py-2.5 rounded-lg font-semibold transition-colors"
            >
              Remove
            </button>
          )}
        </div>

        <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleUpload} />
        <p className="text-text-muted text-sm">Recommended: 1200x400px, JPG or PNG, max 10MB</p>
      </div>
    </div>
  );
}
