"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Camera } from "lucide-react";

export default function AccountSettingsClient({
  name: initialName,
  email: initialEmail,
  avatarUrl: initialAvatar,
  coverUrl: initialCover,
}: {
  name: string;
  email: string;
  avatarUrl: string | null;
  coverUrl: string | null;
}) {
  const router = useRouter();
  const avatarInputRef = useRef<HTMLInputElement>(null);
  const coverInputRef = useRef<HTMLInputElement>(null);

  const [name, setName] = useState(initialName);
  const [email, setEmail] = useState(initialEmail);
  const [avatarUrl, setAvatarUrl] = useState(initialAvatar);
  const [coverUrl, setCoverUrl] = useState(initialCover);
  const [uploadingAvatar, setUploadingAvatar] = useState(false);
  const [uploadingCover, setUploadingCover] = useState(false);
  const [saving, setSaving] = useState(false);
  const [saveMsg, setSaveMsg] = useState("");

  const [prefs, setPrefs] = useState({ emailNotifyMissions: true, emailNotifyVideos: true, emailNotifyPromo: true });
  const [prefsSaving, setPrefsSaving] = useState(false);
  const [prefsSaved, setPrefsSaved] = useState(false);

  useEffect(() => {
    fetch("/api/account/email-preferences")
      .then((r) => r.json())
      .then((d) => setPrefs({ emailNotifyMissions: d.emailNotifyMissions, emailNotifyVideos: d.emailNotifyVideos, emailNotifyPromo: d.emailNotifyPromo }));
  }, []);

  async function uploadFile(file: File, setUrl: (u: string) => void, setUploading: (b: boolean) => void, field: "avatarUrl" | "coverUrl") {
    setUploading(true);
    const formData = new FormData();
    formData.append("file", file);
    const res = await fetch("/api/upload", { method: "POST", body: formData });
    const data = await res.json();
    setUploading(false);
    if (res.ok) {
      setUrl(data.url);
      await fetch("/api/account/update", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ [field]: data.url }),
      });
      router.refresh();
    } else {
      alert(data.error || "Upload failed.");
    }
  }

  async function saveProfile() {
    setSaving(true);
    setSaveMsg("");
    const res = await fetch("/api/account/update", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, newEmail: email !== initialEmail ? email : undefined }),
    });
    const data = await res.json();
    setSaving(false);
    if (!res.ok) {
      setSaveMsg(data.error);
      return;
    }
    setSaveMsg(
      data.emailChangeSent
        ? "✓ Name updated. Check your new email address for a confirmation link — your login email won't change until you click it."
        : "✓ Saved."
    );
    router.refresh();
  }

  async function savePrefs() {
    setPrefsSaving(true);
    setPrefsSaved(false);
    await fetch("/api/account/email-preferences", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(prefs),
    });
    setPrefsSaving(false);
    setPrefsSaved(true);
  }

  const inputCls = "w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600";

  return (
    <div className="space-y-6">
      {/* Cover + avatar */}
      <div className="card overflow-hidden p-0">
        <div className="relative h-32 bg-gradient-to-br from-[#3d1220] to-[#1a0d12] border-b border-[#4d1a28]">
          {coverUrl && <img src={coverUrl} className="w-full h-full object-cover" />}
          <input ref={coverInputRef} type="file" accept="image/*" className="hidden" onChange={(e) => e.target.files?.[0] && uploadFile(e.target.files[0], setCoverUrl, setUploadingCover, "coverUrl")} />
          <button
            onClick={() => coverInputRef.current?.click()}
            disabled={uploadingCover}
            className="absolute bottom-3 right-3 bg-black/60 hover:bg-black/80 text-xs px-3 py-1.5 rounded-lg flex items-center gap-1.5"
          >
            <Camera size={12} /> {uploadingCover ? "Uploading..." : "Change Cover"}
          </button>
          <div className="absolute -bottom-8 left-4 w-16 h-16 rounded-full bg-neutral-800 border-4 border-black overflow-hidden flex items-center justify-center text-xl font-bold">
            {avatarUrl ? <img src={avatarUrl} className="w-full h-full object-cover" /> : name.charAt(0).toUpperCase()}
          </div>
        </div>
        <div className="pt-10 px-4 pb-4">
          <input ref={avatarInputRef} type="file" accept="image/*" className="hidden" onChange={(e) => e.target.files?.[0] && uploadFile(e.target.files[0], setAvatarUrl, setUploadingAvatar, "avatarUrl")} />
          <button onClick={() => avatarInputRef.current?.click()} disabled={uploadingAvatar} className="btn-secondary px-3 py-1.5 text-xs">
            {uploadingAvatar ? "Uploading..." : "Change Profile Photo"}
          </button>
        </div>
      </div>

      {/* Name + email */}
      <div className="card p-6">
        <h3 className="font-bold mb-4">Profile Details</h3>
        <div className="space-y-3">
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Name</label>
            <input value={name} onChange={(e) => setName(e.target.value)} className={inputCls} />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Email</label>
            <input value={email} onChange={(e) => setEmail(e.target.value)} className={inputCls} />
            {email !== initialEmail && (
              <p className="text-xs text-amber-500 mt-1.5">
                Changing your email requires confirming the new address — you'll get a verification link there.
              </p>
            )}
          </div>
          {saveMsg && <p className={`text-sm ${saveMsg.startsWith("✓") ? "text-green-500" : "text-red-500"}`}>{saveMsg}</p>}
          <button onClick={saveProfile} disabled={saving} className="btn-primary px-5 py-2 text-sm">
            {saving ? "Saving..." : "Save Changes"}
          </button>
        </div>
      </div>

      {/* Email notification preferences */}
      <div className="card p-6">
        <h3 className="font-bold mb-1">Email Notifications</h3>
        <p className="text-xs text-neutral-500 mb-4">Choose which emails you'd like to receive.</p>
        <div className="space-y-3">
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={prefs.emailNotifyMissions} onChange={(e) => setPrefs((p) => ({ ...p, emailNotifyMissions: e.target.checked }))} />
            New missions & targets
          </label>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={prefs.emailNotifyVideos} onChange={(e) => setPrefs((p) => ({ ...p, emailNotifyVideos: e.target.checked }))} />
            New video alerts
          </label>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={prefs.emailNotifyPromo} onChange={(e) => setPrefs((p) => ({ ...p, emailNotifyPromo: e.target.checked }))} />
            Promotions & announcements
          </label>
        </div>
        <div className="flex items-center gap-3 mt-4">
          <button onClick={savePrefs} disabled={prefsSaving} className="btn-secondary px-4 py-2 text-sm">
            {prefsSaving ? "Saving..." : "Save Preferences"}
          </button>
          {prefsSaved && <span className="text-green-500 text-sm">✓ Saved</span>}
        </div>
      </div>
    </div>
  );
}
