"use client";

import { useState, useRef } from "react";
import clsx from "clsx";
import { DECORATION_LIST } from "./AvatarDecoration";
import { Camera, Loader2, ChevronLeft, ChevronRight } from "lucide-react";
import { Avatar } from "./Avatar";
import { fileToDataUrl } from "@/lib/image";
import { useEscapeKey } from "@/lib/use-escape-key";
import type { PublicProfile } from "@/lib/types";

export function EditProfileModal({
  profile,
  onClose,
  onSaved,
}: {
  profile: PublicProfile;
  onClose: () => void;
  onSaved: (p: PublicProfile) => void;
}) {
  const [avatarUrl, setAvatarUrl] = useState(profile.avatarUrl);
  const [decoration, setDecoration] = useState<string>(profile.decoration || "");
  const frameRail = useRef<HTMLDivElement>(null);

  /** Nudge the frame rail one screen at a time. */
  function scrollFrames(dir: 1 | -1) {
    frameRail.current?.scrollBy({ left: dir * 240, behavior: "smooth" });
  }
  const [avatarLoading, setAvatarLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEscapeKey(onClose);

  async function handleAvatarPick(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    e.target.value = "";
    if (!file) return;
    setAvatarLoading(true);
    setError(null);
    try {
      const dataUrl = await fileToDataUrl(file, 400, 0.85);
      setAvatarUrl(dataUrl);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Couldn't load that image");
    }
    setAvatarLoading(false);
  }

  async function save() {
    setError(null);
    setSaving(true);
    const res = await fetch("/api/me", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ avatarUrl, decoration }),
    });
    setSaving(false);
    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      setError(data.error || "Something went wrong");
      return;
    }
    const updated = await res.json();
    onSaved({ ...profile, ...updated });
  }

  return (
    <div
      className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-start md:items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-white dark:bg-neutral-950 rounded-2xl w-full max-w-md shadow-2xl mt-10 md:mt-0"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-5 py-4 border-b border-neutral-100 dark:border-neutral-800">
          <button onClick={onClose} className="text-neutral-500 text-sm font-medium">
            Cancel
          </button>
          <span className="font-semibold">Profile effect</span>
          <button
            onClick={save}
            disabled={saving}
            className="text-sm font-semibold text-black dark:text-white disabled:text-neutral-300"
          >
            {saving ? "Saving…" : "Save"}
          </button>
        </div>

        <div className="px-5 py-4 flex flex-col gap-4">
          {error && (
            <p className="text-sm text-red-500 bg-red-50 dark:bg-red-950/40 rounded-lg px-3 py-2">
              {error}
            </p>
          )}

          <div className="flex justify-center">
            <button
              onClick={() => fileInputRef.current?.click()}
              className="relative"
              title="Change photo"
            >
              <Avatar user={{ ...profile, avatarUrl, decoration: decoration || undefined }} size={80} />
              <span
                className={`absolute inset-0 rounded-full bg-black/40 flex items-center justify-center transition-opacity ${avatarLoading ? "opacity-100" : "opacity-0 hover:opacity-100"}`}
              >
                {avatarLoading ? (
                  <Loader2 size={20} className="text-white animate-spin" />
                ) : (
                  <Camera size={20} className="text-white" />
                )}
              </span>
            </button>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleAvatarPick}
            />
          </div>

          

          

          {/* Effect picker — previews render on the person's own avatar */}
          <div>
            <label className="text-sm font-medium text-neutral-500">Effect</label>
            <div className="deco-carousel mt-2">
              <button
                type="button"
                onClick={() => scrollFrames(-1)}
                className="deco-arrow"
                title="Previous"
              >
                <ChevronLeft size={16} />
              </button>

              <div className="deco-rail" ref={frameRail}>
                <button
                  type="button"
                  onClick={() => setDecoration("")}
                  className={clsx("deco-cell", decoration === "" && "sel")}
                >
                  <span className="deco-thumb">
                    <Avatar
                      user={{ ...profile, avatarUrl, decoration: undefined }}
                      size={54}
                      effect={false}
                    />
                  </span>
                  <span className="deco-label">None</span>
                </button>

                {DECORATION_LIST.map((d) => (
                  <button
                    key={d.id}
                    type="button"
                    onClick={() => setDecoration(d.id)}
                    className={clsx("deco-cell", decoration === d.id && "sel")}
                  >
                    <span className="deco-thumb">
                      <Avatar
                        user={{ ...profile, avatarUrl, decoration: d.id }}
                        size={54}
                      />
                    </span>
                    <span className="deco-label">{d.label}</span>
                  </button>
                ))}
              </div>

              <button
                type="button"
                onClick={() => scrollFrames(1)}
                className="deco-arrow"
                title="Next"
              >
                <ChevronRight size={16} />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
