"use client";

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

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

  useEffect(() => {
    fetch("/api/profile")
      .then((r) => r.json())
      .then((data) => {
        setAvatar(data.profile_photo || null);
      })
      .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("avatar", file);
      const res = await fetch("/api/profile/avatar", { method: "POST", body: formData });
      if (!res.ok) throw new Error("Upload failed");
      const data = await res.json();
      setAvatar(data.url);
      setMessage({ type: "success", text: "Avatar uploaded successfully." });
    } catch {
      setMessage({ type: "error", text: "Failed to upload avatar." });
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = "";
    }
  }

  async function handleRemove() {
    if (!(await askConfirm({ title: "Remove avatar", message: "Remove your avatar? This cannot be undone." }))) return;
    setMessage(null);
    try {
      const res = await fetch("/api/profile", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ profile_photo: null }),
      });
      if (!res.ok) throw new Error("Failed");
      setAvatar(null);
      setMessage({ type: "success", text: "Avatar removed." });
    } catch {
      setMessage({ type: "error", text: "Failed to remove avatar." });
    }
  }

  if (loading) return <ManagePageSkeleton />;

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

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

        <div className="w-40 h-40 rounded-full mx-auto overflow-hidden bg-surface-light flex items-center justify-center">
          {avatar ? (
            <img src={avatarUrl(avatar)} alt="Avatar" className="w-full h-full object-cover" />
          ) : (
            <span className="text-text-muted text-sm">No avatar</span>
          )}
        </div>

        <div className="flex gap-3 justify-center">
          <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 Avatar"}
          </button>
          {avatar && (
            <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: 400x400px, JPG or PNG, max 5MB</p>
      </div>
    </div>
  );
}
