"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";

/** Some Android cameras return file.type = "" — detect from extension as fallback. */
function resolveContentType(file: File): string {
  if (file.type && file.type !== "application/octet-stream") return file.type;
  const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
  const map: Record<string, string> = {
    jpg: "image/jpeg", jpeg: "image/jpeg",
    png: "image/png", webp: "image/webp",
    heic: "image/heic", heif: "image/heic",
  };
  return map[ext] || "image/jpeg";
}

export default function ProfilePage() {
  const router  = useRouter();
  const fileRef = useRef<HTMLInputElement>(null);

  const [name, setName]           = useState("");
  const [email, setEmail]         = useState("");
  const [phone, setPhone]         = useState("");
  const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
  const [loading, setLoading]     = useState(true);
  const [saving, setSaving]       = useState(false);
  const [saveMsg, setSaveMsg]     = useState("");
  const [avatarError, setAvatarError] = useState(false);
  const [uploading, setUploading]     = useState(false);

  useEffect(() => {
    fetch("/api/auth/profile")
      .then(r => r.json())
      .then(data => {
        if (data.user) {
          setName(data.user.name || "");
          setEmail(data.user.email || "");
          setPhone(data.user.phone || "");
          setAvatarUrl(data.user.avatarUrl || null);
        }
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  const handlePhotoChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const contentType = resolveContentType(file);
    setUploading(true);
    setSaveMsg("");

    try {
      // Step 1: reserve upload slot
      const initRes = await fetch("/api/auth/avatar", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ contentType, filename: file.name }),
      });
      const initData = await initRes.json();
      if (!initRes.ok) throw new Error(initData.error || `Upload failed (${initRes.status})`);
      const { key, publicUrl: r2Url } = initData;

      // Step 2: upload binary via proxy
      const putRes = await fetch(`/api/upload?${new URLSearchParams({ key, contentType })}`, {
        method: "PUT",
        body: file,
        headers: { "Content-Type": contentType },
      });
      if (!putRes.ok) throw new Error(`Upload failed (${putRes.status})`);

      // Step 3: save R2 URL to DB
      const patchRes = await fetch("/api/auth/avatar", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ avatarUrl: r2Url }),
      });
      if (!patchRes.ok) throw new Error("Failed to save photo");

      setAvatarError(false);
      setAvatarUrl(`/api/img?key=${encodeURIComponent(key)}`);
    } catch (err) {
      setSaveMsg(err instanceof Error ? err.message : "Upload failed");
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = "";
    }
  };

  const handleRemovePhoto = async () => {
    setSaveMsg("");
    try {
      const res = await fetch("/api/auth/avatar", { method: "DELETE" });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to remove photo");
      setAvatarUrl(null);
      setAvatarError(false);
    } catch (err) {
      setSaveMsg(err instanceof Error ? err.message : "Failed to remove photo");
    }
  };

  const saveProfile = async () => {
    if (!name.trim()) { setSaveMsg("Please enter your name"); return; }
    setSaving(true);
    setSaveMsg("");
    try {
      const res  = await fetch("/api/auth/profile", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, phone }),
      });
      const data = await res.json();
      setSaveMsg(data.success ? "Saved!" : data.error || "Save failed");
    } catch {
      setSaveMsg("Failed to save");
    }
    setSaving(false);
  };

  const initials = name.split(" ").map(w => w[0]).join("").toUpperCase().slice(0, 2);

  return (
    <div className="min-h-screen bg-gradient-to-br from-rose-50 to-amber-50 dark:from-gray-900 dark:to-gray-800">
      {/* Header */}
      <div className="sticky top-0 z-10 bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm border-b border-gray-100 dark:border-gray-800 px-4 py-3 flex items-center gap-3">
        <button onClick={() => router.back()} className="text-gray-500 dark:text-gray-400 p-1">←</button>
        <h1 className="text-sm font-semibold dark:text-white">My Profile</h1>
      </div>

      <div className="px-4 pb-24 space-y-4">
        {/* Avatar */}
        <div className="flex flex-col items-center pt-8 pb-2">
          <div className="relative mb-3">
            {avatarUrl && !avatarError ? (
              <img
                src={avatarUrl}
                alt={name}
                className="w-24 h-24 rounded-full object-cover ring-4 ring-white dark:ring-gray-800 shadow-md"
                onError={() => setAvatarError(true)}
              />
            ) : (
              <div className="w-24 h-24 rounded-full bg-gradient-to-br from-rose-300 to-amber-300 flex items-center justify-center text-white text-2xl font-bold shadow-md ring-4 ring-white dark:ring-gray-800">
                {initials || "👤"}
              </div>
            )}
            {uploading && (
              <div className="absolute inset-0 rounded-full bg-black/40 flex items-center justify-center">
                <div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin" />
              </div>
            )}
          </div>

          <button
            onClick={() => fileRef.current?.click()}
            disabled={uploading}
            className="text-sm font-medium text-rose-500 dark:text-rose-400 disabled:opacity-50"
          >
            {uploading ? "Uploading…" : "Change Photo"}
          </button>
          {avatarUrl && !uploading && (
            <button onClick={handleRemovePhoto} className="text-xs text-gray-400 mt-0.5 hover:text-red-400 transition-colors">
              Remove photo
            </button>
          )}
          {!avatarUrl && !uploading && (
            <p className="text-xs text-gray-400 mt-0.5">JPEG, PNG, WebP or HEIC</p>
          )}

          <input
            ref={fileRef}
            type="file"
            accept="image/jpeg,image/jpg,image/png,image/webp,image/heic"
            onChange={handlePhotoChange}
            className="hidden"
          />
        </div>

        {/* Form */}
        {loading ? (
          <div className="text-center py-8 text-gray-400 text-sm">Loading…</div>
        ) : (
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-4 space-y-4">
            <div>
              <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Name</label>
              <input
                type="text"
                value={name}
                onChange={e => setName(e.target.value)}
                className="w-full px-3 py-2.5 bg-gray-50 dark:bg-gray-700 rounded-xl border border-gray-200 dark:border-gray-600 text-sm dark:text-white focus:outline-none focus:ring-2 focus:ring-rose-300"
                placeholder="Your name"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Phone Number</label>
              <input
                type="tel"
                value={phone}
                onChange={e => setPhone(e.target.value)}
                className="w-full px-3 py-2.5 bg-gray-50 dark:bg-gray-700 rounded-xl border border-gray-200 dark:border-gray-600 text-sm dark:text-white focus:outline-none focus:ring-2 focus:ring-rose-300"
                placeholder="+91 98765 43210"
              />
              <p className="text-xs text-gray-400 mt-1">For important reminders &amp; updates (optional)</p>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Email</label>
              <input
                type="email"
                value={email}
                disabled
                className="w-full px-3 py-2.5 bg-gray-100 dark:bg-gray-700/50 rounded-xl border border-gray-200 dark:border-gray-600 text-sm text-gray-400 dark:text-gray-500 cursor-not-allowed"
              />
              <p className="text-xs text-gray-400 mt-1">Email cannot be changed</p>
            </div>

            {saveMsg && (
              <p className={`text-xs text-center font-medium ${saveMsg === "Saved!" ? "text-green-600 dark:text-green-400" : "text-red-500"}`}>
                {saveMsg}
              </p>
            )}

            <button
              onClick={saveProfile}
              disabled={saving || !name.trim()}
              className="w-full py-3 bg-rose-400 text-white rounded-xl font-medium text-sm disabled:opacity-50 active:scale-95 transition-transform"
            >
              {saving ? "Saving…" : "Save Changes"}
            </button>
          </div>
        )}

        {/* Account info */}
        <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-4">
          <p className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Account</p>
          <p className="text-sm text-gray-700 dark:text-gray-300">{email}</p>
        </div>
      </div>
    </div>
  );
}
