"use client";

import { useEffect, useRef, useState } from "react";
import { Search, X, ArrowLeft, Camera, Users } from "lucide-react";
import { Avatar } from "./Avatar";
import { useEscapeKey } from "@/lib/use-escape-key";
import { fileToDataUrl } from "@/lib/image";
import { sfx } from "@/lib/sfx";
import type { User } from "@/lib/types";
import clsx from "clsx";

/** Two steps: pick members, then name and describe the group. */
export function CreateGroupModal({
  onClose,
  onCreated,
}: {
  onClose: () => void;
  onCreated: (conversationId: string) => void;
}) {
  const [step, setStep] = useState<1 | 2>(1);
  const [q, setQ] = useState("");
  const [people, setPeople] = useState<User[]>([]);
  const [picked, setPicked] = useState<User[]>([]);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [imageUrl, setImageUrl] = useState<string | undefined>();
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);

  useEscapeKey(onClose);

  useEffect(() => {
    const term = q.trim();
    const t = setTimeout(async () => {
      const url = term ? `/api/search?q=${encodeURIComponent(term)}` : "/api/users/suggested";
      const r = await fetch(url).catch(() => null);
      if (r && r.ok) {
        const d = await r.json();
        setPeople(Array.isArray(d) ? d : (d.users ?? []));
      }
    }, 220);
    return () => clearTimeout(t);
  }, [q]);

  function toggle(u: User) {
    setPicked((p) =>
      p.some((x) => x.id === u.id) ? p.filter((x) => x.id !== u.id) : [...p, u]
    );
    sfx.click();
  }

  async function create() {
    setSaving(true);
    setError(null);
    const res = await fetch("/api/messages/groups", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name,
        description,
        imageUrl,
        usernames: picked.map((p) => p.username),
      }),
    }).catch(() => null);
    setSaving(false);
    if (!res || !res.ok) {
      setError("Couldn't create the group — try again.");
      return;
    }
    const d = await res.json();
    sfx.fanfare();
    onCreated(d.id);
  }

  const available = people.filter((u) => !picked.some((p) => p.id === u.id));

  return (
    <div className="nm-back" onClick={onClose}>
      <div className="nm-card" onClick={(e) => e.stopPropagation()}>
        <div className="nm-head">
          {step === 1 ? (
            <button onClick={onClose} className="nm-x" title="Close">
              <X size={18} />
            </button>
          ) : (
            <button onClick={() => setStep(1)} className="nm-x" title="Back">
              <ArrowLeft size={18} />
            </button>
          )}
          <span className="nm-title">{step === 1 ? "Select Members" : "Group Details"}</span>
          {step === 1 ? (
            <button
              disabled={picked.length === 0}
              onClick={() => setStep(2)}
              className={clsx("nm-next", picked.length === 0 && "off")}
            >
              Next
            </button>
          ) : (
            <button
              disabled={name.trim().length < 2 || saving}
              onClick={create}
              className={clsx("nm-next", (name.trim().length < 2 || saving) && "off")}
            >
              {saving ? "Creating…" : "Create"}
            </button>
          )}
        </div>

        {step === 1 ? (
          <>
            {picked.length > 0 && (
              <div className="nm-chips">
                {picked.map((u) => (
                  <span key={u.id} className="nm-chip">
                    <Avatar user={u} size={22} effect={false} />
                    {u.name}
                    <button onClick={() => toggle(u)} title="Remove">
                      <X size={12} />
                    </button>
                  </span>
                ))}
              </div>
            )}

            <div className="nm-search">
              <Search size={16} className="text-neutral-400 shrink-0" />
              <input
                autoFocus
                value={q}
                onChange={(e) => setQ(e.target.value)}
                placeholder="Search people..."
                className="flex-1 bg-transparent outline-none text-sm min-w-0"
              />
            </div>

            <div className="nm-list">
              {available.map((u) => (
                <button key={u.id} onClick={() => toggle(u)} className="nm-row">
                  <Avatar user={u} size={44} />
                  <span className="min-w-0 text-left flex-1">
                    <span className="block text-[15px] font-bold truncate">{u.name}</span>
                    {u.bio && (
                      <span className="block text-xs text-neutral-400 truncate">{u.bio}</span>
                    )}
                  </span>
                </button>
              ))}
              {available.length === 0 && (
                <p className="text-sm text-neutral-400 text-center py-10">No one else to add.</p>
              )}
            </div>
          </>
        ) : (
          <div className="nm-details">
            <input
              ref={fileRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={async (e) => {
                const f = e.target.files?.[0];
                if (f) setImageUrl(await fileToDataUrl(f, 400));
                e.target.value = "";
              }}
            />
            <button className="nm-photo" onClick={() => fileRef.current?.click()}>
              {imageUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={imageUrl} alt="" />
              ) : (
                <Users size={30} className="text-neutral-400" />
              )}
              <span className="nm-photo-cam">
                <Camera size={13} />
              </span>
            </button>
            <p className="text-xs text-neutral-400 text-center mb-5">Tap to add photo</p>

            <label className="nm-label">Group name</label>
            <input
              value={name}
              onChange={(e) => setName(e.target.value.slice(0, 100))}
              placeholder="Group name..."
              className="nm-field"
            />
            <p className="nm-count">{name.length}/100</p>

            <label className="nm-label">Description</label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value.slice(0, 500))}
              rows={3}
              placeholder="Enter description..."
              className="nm-field resize-none"
            />
            <p className="nm-count">{description.length}/500</p>

            {error && <p className="text-xs text-red-500 mt-2">{error}</p>}
          </div>
        )}
      </div>
    </div>
  );
}
