import { useState } from "react";
import { useParams, Link } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { getBand } from "../api/bands";
import { api } from "../api/client";

interface SongSummary {
  id: string;
  title: string;
  status: string;
  version_count: number;
}

interface BandMember {
  id: string;
  display_name: string;
  email: string;
  role: string;
  joined_at: string;
}

interface BandInvite {
  id: string;
  token: string;
  role: string;
  expires_at: string;
}

export function BandPage() {
  const { bandId } = useParams<{ bandId: string }>();
  const qc = useQueryClient();
  const [showCreate, setShowCreate] = useState(false);
  const [title, setTitle] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [scanMsg, setScanMsg] = useState<string | null>(null);
  const [inviteLink, setInviteLink] = useState<string | null>(null);
  const [editingFolder, setEditingFolder] = useState(false);
  const [folderInput, setFolderInput] = useState("");

  const { data: band, isLoading } = useQuery({
    queryKey: ["band", bandId],
    queryFn: () => getBand(bandId!),
    enabled: !!bandId,
  });

  const { data: songs } = useQuery({
    queryKey: ["songs", bandId],
    queryFn: () => api.get<SongSummary[]>(`/bands/${bandId}/songs`),
    enabled: !!bandId,
  });

  const { data: members } = useQuery({
    queryKey: ["members", bandId],
    queryFn: () => api.get<BandMember[]>(`/bands/${bandId}/members`),
    enabled: !!bandId,
  });

  const createMutation = useMutation({
    mutationFn: () => api.post(`/bands/${bandId}/songs`, { title }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["songs", bandId] });
      setShowCreate(false);
      setTitle("");
      setError(null);
    },
    onError: (err) => setError(err instanceof Error ? err.message : "Failed to create song"),
  });

  const scanMutation = useMutation({
    mutationFn: () => api.post<SongSummary[]>(`/bands/${bandId}/nc-scan`, {}),
    onSuccess: (imported) => {
      qc.invalidateQueries({ queryKey: ["songs", bandId] });
      setScanMsg(
        imported.length > 0
          ? `Imported ${imported.length} new song${imported.length !== 1 ? "s" : ""} from Nextcloud.`
          : "No new audio files found in Nextcloud."
      );
      setTimeout(() => setScanMsg(null), 4000);
    },
    onError: (err) => setScanMsg(err instanceof Error ? err.message : "Scan failed"),
  });

  const inviteMutation = useMutation({
    mutationFn: () => api.post<BandInvite>(`/bands/${bandId}/invites`, {}),
    onSuccess: (invite) => {
      const url = `${window.location.origin}/invite/${invite.token}`;
      setInviteLink(url);
      navigator.clipboard.writeText(url).catch(() => {});
    },
  });

  const removeMemberMutation = useMutation({
    mutationFn: (memberId: string) => api.delete(`/bands/${bandId}/members/${memberId}`),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["members", bandId] }),
  });

  const updateFolderMutation = useMutation({
    mutationFn: (nc_folder_path: string) =>
      api.patch(`/bands/${bandId}`, { nc_folder_path }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["band", bandId] });
      setEditingFolder(false);
    },
  });

  const amAdmin = members?.some((m) => m.role === "admin") ?? false;

  if (isLoading) return <div style={{ color: "var(--text-muted)", padding: 32 }}>Loading...</div>;
  if (!band) return <div style={{ color: "var(--danger)", padding: 32 }}>Band not found</div>;

  return (
    <div style={{ background: "var(--bg)", minHeight: "100vh", color: "var(--text)", padding: 32 }}>
      <div style={{ maxWidth: 720, margin: "0 auto" }}>
        <Link to="/" style={{ color: "var(--text-muted)", fontSize: 12, textDecoration: "none", display: "inline-block", marginBottom: 20 }}>
          ← All Bands
        </Link>

        {/* ── Band header ── */}
        <div style={{ marginBottom: 24 }}>
          <h1 style={{ color: "var(--accent)", fontFamily: "monospace", margin: "0 0 4px" }}>{band.name}</h1>
          {band.genre_tags.length > 0 && (
            <div style={{ display: "flex", gap: 4, marginTop: 8 }}>
              {band.genre_tags.map((t: string) => (
                <span key={t} style={{ background: "var(--teal-bg)", color: "var(--teal)", fontSize: 10, padding: "2px 6px", borderRadius: 3, fontFamily: "monospace" }}>{t}</span>
              ))}
            </div>
          )}
        </div>

        {/* ── Nextcloud folder ── */}
        <div style={{ marginBottom: 24, background: "var(--bg-subtle)", border: "1px solid var(--border)", borderRadius: 8, padding: "12px 16px" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
            <div>
              <span style={{ color: "var(--text-muted)", fontSize: 11 }}>NEXTCLOUD SCAN FOLDER</span>
              <div style={{ fontFamily: "monospace", color: "var(--teal)", fontSize: 13, marginTop: 4 }}>
                {band.nc_folder_path ?? `bands/${band.slug}/`}
              </div>
            </div>
            {amAdmin && !editingFolder && (
              <button
                onClick={() => { setFolderInput(band.nc_folder_path ?? ""); setEditingFolder(true); }}
                style={{ background: "none", border: "1px solid var(--border)", borderRadius: 6, color: "var(--text-muted)", cursor: "pointer", padding: "4px 10px", fontSize: 11 }}
              >
                Edit
              </button>
            )}
          </div>
          {editingFolder && (
            <div style={{ marginTop: 10 }}>
              <input
                value={folderInput}
                onChange={(e) => setFolderInput(e.target.value)}
                placeholder={`bands/${band.slug}/`}
                style={{ width: "100%", padding: "7px 10px", background: "var(--bg-inset)", border: "1px solid var(--border)", borderRadius: 6, color: "var(--text)", fontSize: 13, fontFamily: "monospace", boxSizing: "border-box" }}
              />
              <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
                <button
                  onClick={() => updateFolderMutation.mutate(folderInput)}
                  disabled={updateFolderMutation.isPending}
                  style={{ background: "var(--teal)", border: "none", borderRadius: 6, color: "var(--bg)", cursor: "pointer", padding: "6px 14px", fontSize: 12, fontWeight: 600 }}
                >
                  Save
                </button>
                <button
                  onClick={() => setEditingFolder(false)}
                  style={{ background: "none", border: "1px solid var(--border)", borderRadius: 6, color: "var(--text-muted)", cursor: "pointer", padding: "6px 14px", fontSize: 12 }}
                >
                  Cancel
                </button>
              </div>
            </div>
          )}
        </div>

        {/* ── Members ── */}
        <div style={{ marginBottom: 32 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
            <h2 style={{ color: "var(--text)", margin: 0, fontSize: 16 }}>Members</h2>
            <button
              onClick={() => inviteMutation.mutate()}
              disabled={inviteMutation.isPending}
              style={{ background: "none", border: "1px solid var(--border)", borderRadius: 6, color: "var(--accent)", cursor: "pointer", padding: "6px 14px", fontSize: 12 }}
            >
              + Invite
            </button>
          </div>

          {inviteLink && (
            <div style={{ background: "var(--accent-bg)", border: "1px solid var(--accent)", borderRadius: 6, padding: "10px 14px", marginBottom: 12 }}>
              <p style={{ color: "var(--text-muted)", fontSize: 11, margin: "0 0 6px" }}>Invite link (copied to clipboard, valid 72h):</p>
              <code style={{ color: "var(--accent)", fontSize: 12, wordBreak: "break-all" }}>{inviteLink}</code>
              <button
                onClick={() => setInviteLink(null)}
                style={{ display: "block", marginTop: 8, background: "none", border: "none", color: "var(--text-muted)", cursor: "pointer", fontSize: 11, padding: 0 }}
              >
                Dismiss
              </button>
            </div>
          )}

          <div style={{ display: "grid", gap: 6 }}>
            {members?.map((m) => (
              <div
                key={m.id}
                style={{ background: "var(--bg-subtle)", border: "1px solid var(--border)", borderRadius: 6, padding: "10px 14px", display: "flex", justifyContent: "space-between", alignItems: "center" }}
              >
                <div>
                  <span style={{ fontWeight: 500 }}>{m.display_name}</span>
                  <span style={{ color: "var(--text-muted)", fontSize: 11, marginLeft: 10 }}>{m.email}</span>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <span style={{
                    fontSize: 10, fontFamily: "monospace", padding: "2px 6px", borderRadius: 3,
                    background: m.role === "admin" ? "var(--accent-bg)" : "var(--bg-inset)",
                    color: m.role === "admin" ? "var(--accent)" : "var(--text-muted)",
                    border: `1px solid ${m.role === "admin" ? "var(--accent)" : "var(--border)"}`,
                  }}>
                    {m.role}
                  </span>
                  {amAdmin && m.role !== "admin" && (
                    <button
                      onClick={() => removeMemberMutation.mutate(m.id)}
                      style={{ background: "none", border: "none", color: "var(--danger)", cursor: "pointer", fontSize: 11, padding: 0 }}
                    >
                      Remove
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* ── Songs ── */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
          <h2 style={{ color: "var(--text)", margin: 0, fontSize: 16 }}>Songs</h2>
          <div style={{ display: "flex", gap: 8 }}>
            <button
              onClick={() => scanMutation.mutate()}
              disabled={scanMutation.isPending}
              style={{ background: "none", border: "1px solid var(--border)", borderRadius: 6, color: "var(--teal)", cursor: "pointer", padding: "6px 14px", fontSize: 12 }}
            >
              {scanMutation.isPending ? "Scanning…" : "⟳ Scan Nextcloud"}
            </button>
            <button
              onClick={() => { setShowCreate(!showCreate); setError(null); }}
              style={{ background: "var(--accent)", border: "none", borderRadius: 6, color: "var(--accent-fg)", cursor: "pointer", padding: "6px 14px", fontSize: 12, fontWeight: 600 }}
            >
              + New Song
            </button>
          </div>
        </div>

        {scanMsg && (
          <div style={{ background: "var(--teal-bg)", border: "1px solid var(--teal)", borderRadius: 6, color: "var(--teal)", fontSize: 12, padding: "8px 14px", marginBottom: 12 }}>
            {scanMsg}
          </div>
        )}

        {showCreate && (
          <div style={{ background: "var(--bg-subtle)", border: "1px solid var(--border)", borderRadius: 8, padding: 20, marginBottom: 16 }}>
            {error && <p style={{ color: "var(--danger)", fontSize: 13, marginBottom: 12 }}>{error}</p>}
            <label style={{ display: "block", color: "var(--text-muted)", fontSize: 11, marginBottom: 6 }}>SONG TITLE</label>
            <input
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && title && createMutation.mutate()}
              style={{ width: "100%", padding: "8px 12px", background: "var(--bg-inset)", border: "1px solid var(--border)", borderRadius: 6, color: "var(--text)", marginBottom: 12, fontSize: 14, boxSizing: "border-box" }}
              autoFocus
            />
            <p style={{ color: "var(--text-muted)", fontSize: 11, margin: "0 0 12px" }}>
              A folder <code style={{ color: "var(--teal)" }}>bands/{band.slug}/songs/{title.toLowerCase().replace(/\s+/g, "-") || "…"}/</code> will be created in Nextcloud.
            </p>
            <div style={{ display: "flex", gap: 8 }}>
              <button
                onClick={() => createMutation.mutate()}
                disabled={!title}
                style={{ background: "var(--accent)", border: "none", borderRadius: 6, color: "var(--accent-fg)", cursor: "pointer", padding: "8px 18px", fontWeight: 600, fontSize: 13 }}
              >
                Create
              </button>
              <button
                onClick={() => { setShowCreate(false); setError(null); }}
                style={{ background: "none", border: "1px solid var(--border)", borderRadius: 6, color: "var(--text-muted)", cursor: "pointer", padding: "8px 18px", fontSize: 13 }}
              >
                Cancel
              </button>
            </div>
          </div>
        )}

        <div style={{ display: "grid", gap: 8 }}>
          {songs?.map((song) => (
            <Link
              key={song.id}
              to={`/bands/${bandId}/songs/${song.id}`}
              style={{ background: "var(--bg-inset)", border: "1px solid var(--border)", borderRadius: 8, padding: "14px 18px", textDecoration: "none", color: "var(--text)", display: "flex", justifyContent: "space-between", alignItems: "center" }}
            >
              <span>{song.title}</span>
              <span style={{ color: "var(--text-muted)", fontSize: 12 }}>
                <span style={{ background: "var(--bg-subtle)", borderRadius: 4, padding: "2px 6px", marginRight: 8, fontFamily: "monospace", fontSize: 10 }}>{song.status}</span>
                {song.version_count} version{song.version_count !== 1 ? "s" : ""}
              </span>
            </Link>
          ))}
          {songs?.length === 0 && (
            <p style={{ color: "var(--text-muted)", fontSize: 13 }}>
              No songs yet. Create one or scan Nextcloud to import from <code style={{ color: "var(--teal)" }}>{band.nc_folder_path ?? `bands/${band.slug}/`}</code>.
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
