<script lang="ts">
    import { getContext } from "svelte";
    import { Button, Card, Modal, Input } 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;
        role: string;
    }

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

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

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

    let organizations = $state(data.organizations);
    $effect(() => {
        organizations = data.organizations;
    });
    let showCreateModal = $state(false);
    let newOrgName = $state("");
    let creating = $state(false);

    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-dark">
    <header class="border-b border-light/10 bg-surface">
        <div
            class="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between"
        >
            <h1 class="text-xl font-bold text-light">Root Org</h1>
            <div class="flex items-center gap-4">
                <a href="/style" class="text-sm text-light/60 hover:text-light"
                    >Style Guide</a
                >
                <form method="POST" action="/auth/logout">
                    <Button variant="tertiary" size="sm" type="submit"
                        >Sign Out</Button
                    >
                </form>
            </div>
        </div>
    </header>

    <main class="max-w-6xl mx-auto px-6 py-8">
        <div class="flex items-center justify-between mb-8">
            <div>
                <h2 class="text-2xl font-bold text-light">
                    Your Organizations
                </h2>
                <p class="text-light/50 mt-1">
                    Select an organization to get started
                </p>
            </div>
            <Button onclick={() => (showCreateModal = true)}>
                <svg
                    class="w-4 h-4 mr-2"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                >
                    <line x1="12" y1="5" x2="12" y2="19" />
                    <line x1="5" y1="12" x2="19" y2="12" />
                </svg>
                New Organization
            </Button>
        </div>

        {#if organizations.length === 0}
            <Card>
                <div class="p-12 text-center">
                    <svg
                        class="w-16 h-16 mx-auto mb-4 text-light/30"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="1.5"
                    >
                        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
                        <circle cx="9" cy="7" r="4" />
                        <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
                        <path d="M16 3.13a4 4 0 0 1 0 7.75" />
                    </svg>
                    <h3 class="text-lg font-medium text-light mb-2">
                        No organizations yet
                    </h3>
                    <p class="text-light/50 mb-6">
                        Create your first organization to start collaborating
                    </p>
                    <Button onclick={() => (showCreateModal = true)}
                        >Create Organization</Button
                    >
                </div>
            </Card>
        {:else}
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {#each organizations as org}
                    <a href="/{org.slug}" class="block group">
                        <Card
                            class="h-full hover:ring-1 hover:ring-primary/50 transition-all"
                        >
                            <div class="p-6">
                                <div
                                    class="flex items-start justify-between mb-4"
                                >
                                    <div
                                        class="w-12 h-12 bg-primary/20 rounded-xl flex items-center justify-center text-primary font-bold text-lg"
                                    >
                                        {org.name.charAt(0).toUpperCase()}
                                    </div>
                                    <span
                                        class="text-xs px-2 py-1 bg-light/10 rounded text-light/60 capitalize"
                                    >
                                        {org.role}
                                    </span>
                                </div>
                                <h3
                                    class="text-lg font-semibold text-light group-hover:text-primary transition-colors"
                                >
                                    {org.name}
                                </h3>
                                <p class="text-sm text-light/40 mt-1">
                                    /{org.slug}
                                </p>
                            </div>
                        </Card>
                    </a>
                {/each}
            </div>
        {/if}
    </main>
</div>

<Modal
    isOpen={showCreateModal}
    onClose={() => (showCreateModal = false)}
    title="Create Organization"
>
    <div class="space-y-4">
        <Input
            label="Organization Name"
            bind:value={newOrgName}
            placeholder="e.g. Acme Inc"
        />
        {#if newOrgName}
            <p class="text-sm text-light/50">
                URL: <span class="text-light/70"
                    >/{generateSlug(newOrgName)}</span
                >
            </p>
        {/if}
        <div class="flex justify-end gap-2 pt-2">
            <Button variant="tertiary" onclick={() => (showCreateModal = false)}
                >Cancel</Button
            >
            <Button
                onclick={handleCreateOrg}
                disabled={!newOrgName.trim() || creating}
            >
                {creating ? "Creating..." : "Create"}
            </Button>
        </div>
    </div>
</Modal>
