"use client";
import React, { useState, useCallback, useEffect } from "react";
import { StepItem } from "@/components/payment/step-item";
import { usePurchaseStore } from "@/lib/purchase-store";
import { api } from "@/lib/trpc/client";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { MemberRole } from "@/server/modules/organization/types/member-role.enum";
import { OrganizationForm } from "@/components/payment/organization/organization-form";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Loader2 } from "lucide-react";

export const Step1: React.FC = () => {
    const { state, setOrganizationId } = usePurchaseStore();

    const { isLoading, data: organizations = [] } = api.organization.list.useQuery({
        role: MemberRole.OWNER
    });

    const [mode, setMode] = useState<"new" | "existing">(organizations.length > 0 ? "existing" : "new");

    const handleSetMode = useCallback(
        (mode: "new" | "existing") => {
            setMode(mode);

            if (mode === "new") {
                setOrganizationId(undefined);
            } else if (mode === "existing") {
                if (organizations.length > 0 && !state.organizationId) {
                    setOrganizationId(organizations[0].id);
                }
            }
        },
        [organizations, state.organizationId, setOrganizationId]
    );

    useEffect(() => {
        if (mode === "new" && state.organizationId) {
            setMode("existing");
        } else if (mode === "existing" && !state.organizationId && organizations.length > 0) {
            setOrganizationId(organizations[0].id);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [mode, state.organizationId]);

    if (isLoading) {
        return (
            <div className="m-4 flex items-center justify-center gap-2">
                <Loader2 className="size-8 animate-spin" /> Indlæser...
            </div>
        );
    }

    return (
        <StepItem step="1/2" title="Vælg organisation">
            <div className="mx-auto max-w-152">
                <div className="bg-client-pink p-6 md:p-[30px]">
                    <div className="flex w-full flex-col gap-4">
                        {organizations.length > 0 && (
                            <RadioGroup
                                className="flex gap-4"
                                value={mode}
                                onValueChange={(mode) => handleSetMode(mode as "new" | "existing")}
                            >
                                <div className="flex items-center space-x-2">
                                    <RadioGroupItem value="existing" id="existing" />
                                    <Label htmlFor="existing">Vælg eksisterende</Label>
                                </div>

                                <div className="flex items-center space-x-2">
                                    <RadioGroupItem value="new" id="new" />
                                    <Label htmlFor="new">Opret ny</Label>
                                </div>
                            </RadioGroup>
                        )}

                        {mode === "existing" && (
                            <Select value={state.organizationId || ""} onValueChange={setOrganizationId}>
                                <SelectTrigger className="h-11 w-full rounded-none bg-white">
                                    <SelectValue placeholder="Vælg virksomhed" />
                                </SelectTrigger>

                                <SelectContent>
                                    {organizations.map((organization) => {
                                        return (
                                            <SelectItem key={organization.id} value={organization.id}>
                                                {organization.name}
                                            </SelectItem>
                                        );
                                    })}
                                </SelectContent>
                            </Select>
                        )}

                        {mode === "new" && <OrganizationForm onSubmit={setOrganizationId} />}
                    </div>
                </div>
            </div>
        </StepItem>
    );
};
