<script lang="ts">
    import { getContext } from "svelte";
    import { goto } from "$app/navigation";
    import { Modal, Logo, Badge } from "$lib/components/ui";
    import { createOrganization, generateSlug } from "$lib/api/organizations";
    import { toasts } from "$lib/stores/toast.svelte";
    import type { SupabaseClient } from "@supabase/supabase-js";
    import type { Database } from "$lib/supabase/types";

    interface OrgWithRole {
        id: string;
        name: string;
        slug: string;
        avatar_url?: string | null;
        role: string;
    }

    interface PendingInvite {
        id: string;
        role: string;
        token: string;
        createdAt: string;
        org: { id: string; name: string; slug: string };
    }

    interface Props {
        data: {
            organizations: OrgWithRole[];
            pendingInvites: PendingInvite[];
            user: any;
        };
    }

    let { data }: Props = $props();

    const supabase = getContext<SupabaseClient<Database>>("supabase");

    // svelte-ignore state_referenced_locally
    let organizations = $state(data.organizations);
    $effect(() => {
        organizations = data.organizations;
    });
    // svelte-ignore state_referenced_locally
    let pendingInvites = $state<PendingInvite[]>(data.pendingInvites);
    $effect(() => {
        pendingInvites = data.pendingInvites;
    });
    let showCreateModal = $state(false);
    let newOrgName = $state("");
    let creating = $state(false);

    let acceptingInviteId = $state<string | null>(null);

    async function acceptInvite(invite: PendingInvite) {
        if (!data.user) return;
        acceptingInviteId = invite.id;

        try {
            const res = await fetch("/api/accept-invite", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    inviteId: invite.id,
                    orgId: invite.org.id,
                    role: invite.role,
                }),
            });

            const result = await res.json();

            if (!res.ok) {
                toasts.error(result.error || "Failed to join organization.");
                acceptingInviteId = null;
                return;
            }

            // Remove from pending list and add to orgs
            pendingInvites = pendingInvites.filter((i) => i.id !== invite.id);
            if (!result.already_member) {
                organizations = [
                    ...organizations,
                    {
                        id: invite.org.id,
                        name: invite.org.name,
                        slug: invite.org.slug,
                        role: invite.role,
                    },
                ];
            }

            toasts.success(`Joined ${invite.org.name}!`);
            acceptingInviteId = null;
        } catch (e) {
            toasts.error("Something went wrong. Please try again.");
            acceptingInviteId = null;
        }
    }

    async function handleCreateOrg() {
        if (!newOrgName.trim() || creating) return;

        creating = true;
        try {
            const slug = generateSlug(newOrgName);

            const newOrg = await createOrganization(supabase, newOrgName, slug);
            organizations = [...organizations, { ...newOrg, role: "owner" }];

            showCreateModal = false;
            newOrgName = "";
        } catch (error) {
            toasts.error(
                "Failed to create organization. The name may already be taken.",
            );
        } finally {
            creating = false;
        }
    }
</script>

<svelte:head>
    <title>Organizations | root</title>
</svelte:head>

<div class="min-h-screen bg-background">
    <!-- Header -->
    <header class="border-b border-light/5">
        <div
            class="max-w-5xl mx-auto px-6 py-4 flex items-center justify-between"
        >
            <div class="flex items-center gap-2.5">
                <Logo size="sm" />
            </div>
            <div class="flex items-center gap-2">
                {#if pendingInvites.length > 0}
                    <a
                        href="#invites"
                        class="relative p-2 text-light/40 hover:text-white hover:bg-dark/50 rounded-xl transition-colors"
                        title="{pendingInvites.length} pending invite{pendingInvites.length >
                        1
                            ? 's'
                            : ''}"
                    >
                        <span
                            class="material-symbols-rounded"
                            style="font-size: 22px; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 22;"
                            >notifications</span
                        >
                        <span
                            class="absolute -top-0.5 -right-0.5 w-5 h-5 bg-primary text-background text-[10px] font-bold rounded-full flex items-center justify-center"
                        >
                            {pendingInvites.length}
                        </span>
                    </a>
                {/if}
                <form method="POST" action="/auth/logout">
                    <button
                        type="submit"
                        class="px-3 py-1.5 text-body-sm text-light/40 hover:text-white hover:bg-dark/50 rounded-xl transition-colors"
                        >Sign Out</button
                    >
                </form>
            </div>
        </div>
    </header>

    <main class="max-w-5xl mx-auto px-6 py-8">
        <!-- Pending Invites -->
        {#if pendingInvites.length > 0}
            <section id="invites" class="mb-8">
                <div class="flex items-center gap-2 mb-4">
                    <span
                        class="material-symbols-rounded text-primary"
                        style="font-size: 22px; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 22;"
                        >mail</span
                    >
                    <h2 class="font-heading text-body text-white">
                        Pending Invitations
                    </h2>
                    <span
                        class="text-[11px] px-2 py-0.5 bg-primary/10 text-primary rounded-lg font-body"
                    >
                        {pendingInvites.length}
                    </span>
                </div>
                <div
                    class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3"
                >
                    {#each pendingInvites as invite}
                        <div
                            class="bg-primary/5 border border-primary/20 rounded-2xl p-5 transition-all"
                        >
                            <div class="flex items-start justify-between mb-3">
                                <div
                                    class="w-10 h-10 bg-primary/10 rounded-xl flex items-center justify-center text-primary font-heading text-body"
                                >
                                    {invite.org.name.charAt(0).toUpperCase()}
                                </div>
                                <span
                                    class="text-[10px] px-2 py-0.5 bg-primary/10 rounded-lg text-primary capitalize font-body"
                                    >{invite.role}</span
                                >
                            </div>
                            <h3
                                class="font-heading text-body-sm text-white mb-1"
                            >
                                {invite.org.name}
                            </h3>
                            <p class="text-[11px] text-light/30 mb-4 font-body">
                                You've been invited to join this organization
                            </p>
                            <div class="flex items-center gap-2">
                                <button
                                    type="button"
                                    disabled={acceptingInviteId === invite.id}
                                    class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-primary text-background rounded-xl text-body-sm font-body hover:bg-primary-hover transition-colors disabled:opacity-50"
                                    onclick={() => acceptInvite(invite)}
                                >
                                    <span
                                        class="material-symbols-rounded"
                                        style="font-size: 16px; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 16;"
                                        >{acceptingInviteId === invite.id
                                            ? "hourglass_empty"
                                            : "check"}</span
                                    >
                                    {acceptingInviteId === invite.id
                                        ? "Joining..."
                                        : "Accept"}
                                </button>
                            </div>
                        </div>
                    {/each}
                </div>
            </section>
        {/if}

        <div class="flex items-center justify-between mb-6">
            <div>
                <h2 class="font-heading text-h3 text-white">
                    Your Organizations
                </h2>
                <p class="text-body-sm text-light/40 mt-1">
                    Select an organization to get started
                </p>
            </div>
            <button
                class="flex items-center gap-1.5 px-3 py-2 bg-primary text-background rounded-xl text-body-sm font-body hover:bg-primary-hover transition-colors"
                onclick={() => (showCreateModal = true)}
            >
                <span
                    class="material-symbols-rounded"
                    style="font-size: 18px; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 18;"
                    >add</span
                >
                New Organization
            </button>
        </div>

        {#if organizations.length === 0}
            <div
                class="bg-dark/30 border border-light/5 rounded-2xl p-12 text-center"
            >
                <div
                    class="w-14 h-14 mx-auto mb-4 rounded-2xl bg-light/5 flex items-center justify-center"
                >
                    <span
                        class="material-symbols-rounded text-light/20"
                        style="font-size: 28px; font-variation-settings: 'FILL' 0, 'wght' 300, 'GRAD' 0, 'opsz' 28;"
                        >groups</span
                    >
                </div>
                <h3 class="font-heading text-body text-white mb-1">
                    No organizations yet
                </h3>
                <p class="text-body-sm text-light/40 mb-6">
                    Create your first organization to start collaborating
                </p>
                <button
                    class="px-4 py-2 bg-primary text-background rounded-xl text-body-sm font-body hover:bg-primary-hover transition-colors"
                    onclick={() => (showCreateModal = true)}
                    >Create Organization</button
                >
            </div>
        {:else}
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                {#each organizations as org}
                    <a href="/{org.slug}" class="block group">
                        <div
                            class="bg-dark/30 border border-light/5 hover:border-primary/30 rounded-2xl p-5 transition-all h-full"
                        >
                            <div class="flex items-start justify-between mb-3">
                                {#if org.avatar_url}
                                    <img
                                        src={org.avatar_url}
                                        alt={org.name}
                                        class="w-10 h-10 rounded-xl object-cover"
                                    />
                                {:else}
                                    <div
                                        class="w-10 h-10 bg-primary/10 rounded-xl flex items-center justify-center text-primary font-heading text-body"
                                    >
                                        {org.name.charAt(0).toUpperCase()}
                                    </div>
                                {/if}
                                <span
                                    class="text-[10px] px-2 py-0.5 bg-light/5 rounded-lg text-light/40 capitalize font-body"
                                    >{org.role}</span
                                >
                            </div>
                            <h3
                                class="font-heading text-body-sm text-white group-hover:text-primary transition-colors"
                            >
                                {org.name}
                            </h3>
                            <p
                                class="text-[11px] text-light/30 mt-0.5 font-body"
                            >
                                /{org.slug}
                            </p>
                        </div>
                    </a>
                {/each}
            </div>
        {/if}
    </main>
</div>

<Modal
    isOpen={showCreateModal}
    onClose={() => (showCreateModal = false)}
    title="Create Organization"
>
    <div class="flex flex-col gap-4">
        <div class="flex flex-col gap-1.5">
            <label for="org-name" class="text-body-sm text-light/60 font-body"
                >Organization Name</label
            >
            <input
                id="org-name"
                type="text"
                bind:value={newOrgName}
                placeholder="e.g. Acme Inc"
                class="bg-dark border border-light/10 rounded-xl px-3 py-2 text-body-sm text-white placeholder:text-light/30 focus:outline-none focus:border-primary"
            />
        </div>
        {#if newOrgName}
            <p class="text-body-sm text-light/40">
                URL: <span class="text-white font-body"
                    >/{generateSlug(newOrgName)}</span
                >
            </p>
        {/if}
        <div
            class="flex items-center justify-end gap-3 pt-2 border-t border-light/5"
        >
            <button
                type="button"
                class="px-4 py-2 text-body-sm text-light/60 hover:text-white transition-colors"
                onclick={() => (showCreateModal = false)}>Cancel</button
            >
            <button
                type="button"
                disabled={!newOrgName.trim() || creating}
                class="px-4 py-2 bg-primary text-background rounded-xl font-body text-body-sm hover:bg-primary-hover transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                onclick={handleCreateOrg}
            >
                {creating ? "Creating..." : "Create"}
            </button>
        </div>
    </div>
</Modal>
