import { createSignal, For, Show } from "solid-js";

import { useApp } from "~/lib/app-context";
import { colorOptions, getColorStyle } from "~/lib/utils";

export default function SettingsRoute() {
  const app = useApp();
  const workspaceSlug = () => app.primaryWorkspace()?.slug ?? "personal";
  const currentMemberRole = () =>
    app.state.members.find(member => member.workspaceSlug === workspaceSlug() && member.email === app.state.session?.email)?.role ??
    app.primaryWorkspace()?.role ??
    "member";
  const canManageMembers = () => currentMemberRole() === "owner" || currentMemberRole() === "admin";
  const [inviteEmail, setInviteEmail] = createSignal("");
  const [labelName, setLabelName] = createSignal("");
  const [labelColor, setLabelColor] = createSignal("rose");
  const [memberNotice, setMemberNotice] = createSignal<string>("");
  const [inviteNotice, setInviteNotice] = createSignal<string>("");

  const createInvite = async () => {
    if (!inviteEmail().trim()) return;
    const saved = await app.createInvite(workspaceSlug(), inviteEmail(), "member");
    if (!saved) {
      setInviteNotice("Invite could not be created. Check connection and permissions.");
      return;
    }
    setInviteNotice("");
    setInviteEmail("");
  };

  const updateMemberRole = async (memberId: string, role: "owner" | "admin" | "member") => {
    const updated = await app.updateMember(memberId, { role });
    setMemberNotice(updated ? "" : "Member role update failed. Confirm owner/admin access.");
  };

  const toggleMemberStatus = async (memberId: string, nextStatus: "active" | "removed") => {
    const updated = await app.updateMember(memberId, { status: nextStatus });
    setMemberNotice(updated ? "" : "Member status update failed. At least one active owner is required.");
  };

  const revokeInvite = async (inviteId: string) => {
    const ok = await app.revokeInvite(inviteId);
    setInviteNotice(ok ? "" : "Invite revoke failed. It may already be accepted or permissions are missing.");
  };

  const addLabel = () => {
    if (!labelName().trim()) return;
    app.addLabel(workspaceSlug(), labelName(), labelColor());
    setLabelName("");
  };

  return (
    <div class="mx-auto max-w-2xl space-y-6">
      {/* Page header */}
      <div>
        <h1 class="text-xl font-semibold">Settings</h1>
        <p class="mt-1 text-sm text-[var(--text-muted)]">Manage workspace preferences</p>
      </div>

      {/* Theme */}
      <div class="rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <div class="border-b border-[var(--border)] px-4 py-3">
          <h2 class="text-sm font-medium">Theme</h2>
        </div>
        <div class="p-4">
          <div class="flex gap-2">
            <For each={["light", "dark"] as const}>
              {mode => (
                <button
                  class="rounded-md px-4 py-2 text-sm font-medium transition-colors"
                  classList={{
                    "bg-[var(--accent-subtle)] text-[var(--accent)]": app.state.theme === mode,
                    "bg-[var(--bg-subtle)] text-[var(--text-muted)] hover:text-[var(--text)]": app.state.theme !== mode
                  }}
                  onClick={() => app.setTheme(mode)}
                >
                  {mode}
                </button>
              )}
            </For>
          </div>
        </div>
      </div>

      {/* Labels */}
      <div class="rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <div class="border-b border-[var(--border)] px-4 py-3">
          <h2 class="text-sm font-medium">Labels</h2>
        </div>
        <div class="p-4">
          <div class="mb-4 flex gap-2">
            <input
              class="input-base flex-1"
              placeholder="New label"
              value={labelName()}
              onInput={event => setLabelName(event.currentTarget.value)}
              onKeyDown={event => event.key === "Enter" && addLabel()}
            />
            <select
              class="input-base w-28"
              value={labelColor()}
              onInput={event => setLabelColor(event.currentTarget.value)}
            >
              <For each={colorOptions}>{option => <option value={option}>{option}</option>}</For>
            </select>
            <button class="button-primary px-4 py-2 text-sm" onClick={addLabel}>
              Add
            </button>
          </div>
          <div class="flex flex-wrap gap-2">
            <For each={app.state.labels.filter(label => label.workspaceSlug === workspaceSlug())}>
              {label => (
                <span
                  class="rounded px-2 py-1 text-xs font-medium"
                  style={{ background: getColorStyle(label.color).bg, color: getColorStyle(label.color).text }}
                >
                  {label.name}
                </span>
              )}
            </For>
            <Show when={app.state.labels.filter(label => label.workspaceSlug === workspaceSlug()).length === 0}>
              <span class="text-xs text-[var(--text-muted)]">No labels yet</span>
            </Show>
          </div>
        </div>
      </div>

      {/* Members */}
      <div class="rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <div class="border-b border-[var(--border)] px-4 py-3">
          <h2 class="text-sm font-medium">Members</h2>
        </div>
        <Show when={memberNotice()}>
          <div class="border-b border-[var(--border)] bg-[var(--warning-subtle)] px-4 py-2 text-xs text-[var(--warning)]">
            {memberNotice()}
          </div>
        </Show>
        <div class="divide-y divide-[var(--border)]">
          <For each={app.state.members.filter(member => member.workspaceSlug === workspaceSlug())}>
            {member => (
              <div class="flex items-center justify-between px-4 py-3">
                <div>
                  <p class="text-sm font-medium">{member.name}</p>
                  <p class="text-xs text-[var(--text-muted)]">{member.email}</p>
                </div>
                <div class="flex items-center gap-2">
                  <Show
                    when={canManageMembers()}
                    fallback={
                      <span class="text-xs text-[var(--text-muted)]">
                        {member.role} · {member.status}
                      </span>
                    }
                  >
                    <select
                      class="input-base h-7 w-24 text-xs"
                      value={member.role}
                      onInput={event => void updateMemberRole(member.id, event.currentTarget.value as "owner" | "admin" | "member")}
                      disabled={member.status !== "active"}
                    >
                      <option value="owner">owner</option>
                      <option value="admin">admin</option>
                      <option value="member">member</option>
                    </select>
                    <button
                      class="button-secondary h-7 px-2 text-xs"
                      disabled={member.email === app.state.session?.email}
                      onClick={() => void toggleMemberStatus(member.id, member.status === "active" ? "removed" : "active")}
                    >
                      {member.status === "active" ? "Remove" : "Restore"}
                    </button>
                  </Show>
                </div>
              </div>
            )}
          </For>
        </div>
      </div>

      {/* Invites */}
      <div class="rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <div class="border-b border-[var(--border)] px-4 py-3">
          <h2 class="text-sm font-medium">Invites</h2>
        </div>
        <div class="border-b border-[var(--border)] p-4">
          <div class="flex gap-2">
            <input
              class="input-base flex-1"
              placeholder="teammate@company.com"
              value={inviteEmail()}
              onInput={event => setInviteEmail(event.currentTarget.value)}
              onKeyDown={event => event.key === "Enter" && void createInvite()}
            />
            <button
              class="button-primary px-4 py-2 text-sm"
              onClick={() => void createInvite()}
              disabled={!canManageMembers()}
            >
              Invite
            </button>
          </div>
          <Show when={inviteNotice()}>
            <p class="mt-2 text-xs text-[var(--warning)]">{inviteNotice()}</p>
          </Show>
        </div>
        <div class="divide-y divide-[var(--border)]">
          <For each={app.state.invites.filter(invite => invite.workspaceSlug === workspaceSlug())}>
            {invite => (
              <div class="flex items-center justify-between px-4 py-3">
                <div>
                  <p class="text-sm font-medium">{invite.email}</p>
                  <p class="text-xs text-[var(--text-muted)]">{invite.role} · {invite.status}</p>
                </div>
                <Show when={canManageMembers() && invite.status === "pending"}>
                  <button
                    class="button-secondary h-7 px-2 text-xs"
                    onClick={() => void revokeInvite(invite.id)}
                  >
                    Revoke
                  </button>
                </Show>
              </div>
            )}
          </For>
          <Show when={app.state.invites.filter(invite => invite.workspaceSlug === workspaceSlug()).length === 0}>
            <div class="px-4 py-3 text-center text-xs text-[var(--text-muted)]">
              No pending invites
            </div>
          </Show>
        </div>
      </div>

      {/* Offline queue */}
      <div class="rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <div class="border-b border-[var(--border)] px-4 py-3">
          <h2 class="text-sm font-medium">Offline Queue</h2>
        </div>
        <div class="divide-y divide-[var(--border)]">
          <For each={app.state.offlineQueue}>
            {item => (
              <div class="flex items-center justify-between px-4 py-3">
                <p class="text-sm font-medium">{item.description}</p>
                <span class="text-xs text-[var(--text-muted)]">{item.status}</span>
              </div>
            )}
          </For>
          <Show when={app.state.offlineQueue.length === 0}>
            <div class="px-4 py-3 text-center text-xs text-[var(--text-muted)]">
              Everything is in sync
            </div>
          </Show>
        </div>
      </div>
    </div>
  );
}
