import {useCallback, useEffect, useState} from 'react';
import {useNavigate} from 'react-router-dom';
import {useMutation, useQuery} from '@tanstack/react-query';
import {workspaceCreate, workspaceList} from '@/client';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import {Button} from '@/components/ui/button';
import {toast} from 'sonner';
import {InitLayout} from '@/components/init-layout';
import {CheckCircle2, XCircle, Loader2} from 'lucide-react';

export function InitWorkspace() {
    const navigate = useNavigate();
    const [slug, setSlug] = useState('');
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');

    const [slugAvailable, setSlugAvailable] = useState<boolean | null>(null);
    const [slugMessage, setSlugMessage] = useState('');
    const [checkingSlug, setCheckingSlug] = useState(false);

    const baseUrl = typeof window !== 'undefined' ? `${window.location.hostname}/w` : 'localhost/w';

    // Fetch existing workspaces to check slug/name against
    const {data: workspacesData} = useQuery({
        queryKey: ['workspaceListForInit'],
        queryFn: async () => {
            const resp = await workspaceList();
            return resp.data?.data ?? null;
        },
    });

    const checkSlugAvailability = useCallback(
        (value: string) => {
            if (!value.trim()) {
                setSlugAvailable(null);
                setSlugMessage('');
                return;
            }
            if (!/^[a-z0-9-_]+$/.test(value)) {
                setSlugAvailable(false);
                setSlugMessage('Only letters, numbers, hyphens and underscores allowed');
                return;
            }
            setCheckingSlug(true);
            const exists =
                workspacesData?.workspaces?.some(
                    (ws) => ws.slug.toLowerCase() === value.toLowerCase(),
                ) ?? false;
            setCheckingSlug(false);
            setSlugAvailable(!exists);
            setSlugMessage(exists ? 'This slug is already taken' : 'Slug is available');
        },
        [workspacesData],
    );

    // Debounce slug check
    useEffect(() => {
        const timer = setTimeout(() => {
            checkSlugAvailability(slug);
        }, 400);
        return () => clearTimeout(timer);
    }, [slug, checkSlugAvailability]);

    const createMutation = useMutation({
        mutationFn: async () => {
            const resp = await workspaceCreate({
                body: {
                    slug,
                    name,
                    description: description || undefined,
                },
            });
            return resp.data?.data;
        },
        onSuccess: (data) => {
            toast.success('Workspace created!');
            if (data?.slug) {
                navigate(`/w/${data.slug}`);
            }
        },
        onError: (err: unknown) => {
            const axiosErr = err as {response?: {data?: {message?: string}}; message?: string};
            toast.error(
                axiosErr.response?.data?.message ||
                    axiosErr.message ||
                    'Failed to create workspace',
            );
        },
    });

    const canSubmit =
        !createMutation.isPending &&
        !!slug.trim() &&
        !!name.trim() &&
        slugAvailable === true;

    const handleNameChange = (value: string) => {
        setName(value);
        if (!slug) {
            const slugified = value
                .toLowerCase()
                .replace(/[^a-z0-9-_]/g, '')
                .slice(0, 50);
            setSlug(slugified);
        }
    };

    return (
        <InitLayout>
            <div className="w-full max-w-md space-y-6">
                <div className="text-center">
                    <h1 className="text-2xl font-bold">Create a Workspace</h1>
                    <p className="text-muted-foreground text-sm mt-1">
                        Workspaces organize your projects and team members.
                    </p>
                </div>

                <div className="space-y-4">
                    {/* Workspace Name */}
                    <div className="space-y-2">
                        <Label htmlFor="name">Workspace Name</Label>
                        <Input
                            id="name"
                            placeholder="My Company"
                            value={name}
                            onChange={(e) => handleNameChange(e.target.value)}
                            maxLength={100}
                        />
                    </div>

                    {/* URL Slug */}
                    <div className="space-y-2">
                        <Label htmlFor="slug">URL Slug</Label>
                        <div className="relative">
                            <div className="flex items-center rounded-md border bg-background px-3 h-10">
                                <span className="text-muted-foreground text-sm shrink-0">{baseUrl}/</span>
                                <input
                                    id="slug"
                                    className="flex-1 bg-transparent outline-none text-sm"
                                    placeholder="my-workspace"
                                    value={slug}
                                    onChange={(e) =>
                                        setSlug(
                                            e.target.value
                                                .toLowerCase()
                                                .replace(/[^a-z0-9-_]/g, ''),
                                        )
                                    }
                                />
                                <div className="ml-2 shrink-0">
                                    {checkingSlug && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
                                    {!checkingSlug && slugAvailable === true && (
                                        <CheckCircle2 className="h-4 w-4 text-green-500" />
                                    )}
                                    {!checkingSlug && slugAvailable === false && (
                                        <XCircle className="h-4 w-4 text-destructive" />
                                    )}
                                </div>
                            </div>
                        </div>
                        {slugMessage && (
                            <p
                                className={`text-xs ${
                                    slugAvailable ? 'text-green-600 dark:text-green-400' : 'text-destructive'
                                }`}
                            >
                                {slugMessage}
                            </p>
                        )}
                    </div>

                    {/* Description */}
                    <div className="space-y-2">
                        <Label htmlFor="description">Description (optional)</Label>
                        <textarea
                            id="description"
                            className="flex min-h-20 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                            placeholder="Describe this workspace..."
                            value={description}
                            onChange={(e) => setDescription(e.target.value)}
                        />
                    </div>

                    {/* Submit */}
                    <div className="flex gap-3">
                        <Button
                            variant="outline"
                            className="flex-1"
                            onClick={() => navigate(-1)}
                        >
                            Cancel
                        </Button>
                        <Button
                            className="flex-1"
                            onClick={() => createMutation.mutate()}
                            disabled={!canSubmit}
                        >
                            {createMutation.isPending ? 'Creating...' : 'Create Workspace'}
                        </Button>
                    </div>
                </div>
            </div>
        </InitLayout>
    );
}
