"use client";

import Link from "next/link";
import { Suspense, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { AppShell, ScreenHeader, useWorkspaceIdParam } from "../../components/AppShell";
import { api, ApiError, getCurrentUserId } from "../../lib/api";
import { avatarColor, initials } from "../../lib/avatar";
import { channelPath } from "../../lib/conversations";

interface ChannelRow {
  channel: { id: string | number; name: string | null; type: string };
}

interface MemberRow {
  member: { role: string };
  user: { id: string | number; name: string; email: string };
}

function HomeView() {
  const workspaceId = useWorkspaceIdParam();
  const router = useRouter();
  const [channels, setChannels] = useState<ChannelRow[]>([]);
  const [members, setMembers] = useState<MemberRow[]>([]);
  const [presence, setPresence] = useState<Record<string, { status: string }>>({});
  const [myUserId, setMyUserId] = useState<number | null>(null);
  const [channelName, setChannelName] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    getCurrentUserId().then(setMyUserId);
  }, []);

  useEffect(() => {
    if (!workspaceId) return;
    api.listChannels(workspaceId).then((res) => setChannels(res.channels as ChannelRow[])).catch(() => undefined);
    api.members(workspaceId).then((res) => setMembers(res.members as MemberRow[])).catch(() => undefined);
    api.presenceSnapshot(workspaceId).then((res) => setPresence(res.presence)).catch(() => undefined);
  }, [workspaceId]);

  async function openDm(userId: string | number) {
    if (!workspaceId || myUserId == null || String(userId) === String(myUserId)) return;
    try {
      const dm = await api.createDm(workspaceId, String(userId));
      if (dm?.id) router.push(channelPath(workspaceId, String(dm.id)));
    } catch (err) {
      setError(err instanceof ApiError ? JSON.stringify(err.body) : String(err));
    }
  }

  async function createChannel(e: React.FormEvent) {
    e.preventDefault();
    if (!workspaceId || !channelName.trim()) return;
    setBusy(true);
    setError(null);
    try {
      const created = (await api.createChannel(workspaceId, { name: channelName.trim(), type: "public" })) as {
        id: string;
      };
      setChannelName("");
      const res = await api.listChannels(workspaceId);
      setChannels(res.channels as ChannelRow[]);
      window.location.href = `/channel?workspaceId=${workspaceId}&channelId=${created.id}`;
    } catch (err) {
      setError(err instanceof ApiError ? JSON.stringify(err.body) : String(err));
    } finally {
      setBusy(false);
    }
  }

  const onlineCount = members.filter((row) => presence[String(row.user.id)]?.status === "active").length;
  const me = members.find((row) => String(row.user.id) === String(myUserId))?.user;

  return (
    <AppShell active="home" title="Home" subtitle="Your workspace at a glance">
      <ScreenHeader
        title={`Welcome${me ? `, ${me.name.split(" ")[0]}` : ""}`}
        subtitle={`${channels.length} channels · ${members.length} people · ${onlineCount} online`}
        actions={
          <div className="screen-actions">
            <Link className="screen-btn" href={`/search?workspaceId=${workspaceId}`}>Search</Link>
            <Link className="screen-btn primary" href={`/workspace?id=${workspaceId}`}>Open messages</Link>
          </div>
        }
      />

      <div className="screen-body">
        <div className="screen-grid">
          <section className="screen-card">
            <h2>Quick create</h2>
            <p>Start a public channel for your team.</p>
            <form className="form-stack" onSubmit={createChannel}>
              <input
                value={channelName}
                onChange={(e) => setChannelName(e.target.value)}
                placeholder="channel-name"
                aria-label="New channel name"
                required
              />
              <button className="screen-btn primary" type="submit" disabled={busy}>
                {busy ? "Creating…" : "Create channel"}
              </button>
            </form>
            {error && <p className="error-text">{error}</p>}
          </section>

          <section className="screen-card">
            <h2>Channels</h2>
            <p>Jump back into a conversation.</p>
            <div className="screen-list">
              {channels.slice(0, 8).map((row) => (
                <Link
                  key={row.channel.id}
                  className="screen-list-item"
                  href={`/channel?workspaceId=${workspaceId}&channelId=${row.channel.id}`}
                >
                  <span className="hash">#</span>
                  <span>{row.channel.name ?? row.channel.id}</span>
                </Link>
              ))}
              {channels.length === 0 && <div className="empty-state">No channels yet — create one above.</div>}
            </div>
          </section>

          <section className="screen-card">
            <h2>People online</h2>
            <p>Who is active in this workspace right now.</p>
            <div className="screen-list">
              {members
                .filter((row) => presence[String(row.user.id)]?.status === "active")
                .slice(0, 8)
                .map((row) => {
                  const color = avatarColor(String(row.user.id));
                  return (
                    <button
                      key={String(row.user.id)}
                      type="button"
                      className="screen-list-item"
                      onClick={() => void openDm(row.user.id)}
                    >
                      <span className="list-row-avatar" style={{ background: color.bg, color: color.fg, width: 28, height: 28, fontSize: 11 }}>
                        {initials(row.user.name)}
                      </span>
                      <span>{row.user.name}</span>
                    </button>
                  );
                })}
              {onlineCount === 0 && <div className="empty-state">Nobody else is online yet.</div>}
            </div>
          </section>

          <section className="screen-card">
            <h2>Workspace links</h2>
            <p>Admin tools and invite flows.</p>
            <div className="screen-actions" style={{ marginTop: 12 }}>
              <Link className="screen-btn" href={`/people?workspaceId=${workspaceId}&add=1`}>Add users</Link>
              <Link className="screen-btn" href={`/admin?workspaceId=${workspaceId}`}>Admin</Link>
              <Link className="screen-btn" href={`/invite?workspaceId=${workspaceId}`}>Accept invite</Link>
              <Link className="screen-btn" href={`/settings?workspaceId=${workspaceId}`}>Settings</Link>
              <Link className="screen-btn" href="/workspaces">Switch workspace</Link>
            </div>
          </section>
        </div>
      </div>
    </AppShell>
  );
}

export default function HomePage() {
  return (
    <Suspense fallback={<main className="page"><div className="empty-state">Loading home…</div></main>}>
      <HomeView />
    </Suspense>
  );
}
