import {useState} from 'react';
import {useNavigate} from 'react-router-dom';
import {useMutation} from '@tanstack/react-query';
import {workspaceUpdate, workspaceDelete} from '@/client';
import {useWorkspace} from '@/contexts';
import {Avatar, AvatarFallback, AvatarImage} from '@/components/ui/avatar';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import {toast} from 'sonner';

export function WorkspaceSettings() {
    const {currentWorkspace, refetch} = useWorkspace();
    const navigate = useNavigate();

    const [name, setName] = useState(currentWorkspace?.name ?? '');
    const [description, setDescription] = useState(currentWorkspace?.description ?? '');
    const [avatarUrl, setAvatarUrl] = useState(currentWorkspace?.avatar_url ?? '');
    const [billingEmail, setBillingEmail] = useState(currentWorkspace?.billing_email ?? '');

    const updateMutation = useMutation({
        mutationFn: async () => {
            await workspaceUpdate({
                path: {slug: currentWorkspace!.slug},
                body: {
                    name: name || undefined,
                    description: description || undefined,
                    avatar_url: avatarUrl || undefined,
                    billing_email: billingEmail || undefined,
                },
            });
        },
        onSuccess: () => {
            toast.success('Workspace updated');
            refetch();
        },
        onError: (err: Error) => {
            toast.error(err.message || 'Failed to update workspace');
        },
    });

    const deleteMutation = useMutation({
        mutationFn: async () => {
            if (!confirm('Are you sure you want to delete this workspace? This action cannot be undone.')) {
                throw new Error('cancelled');
            }
            await workspaceDelete({path: {slug: currentWorkspace!.slug}});
        },
        onSuccess: () => {
            toast.success('Workspace deleted');
            navigate('/');
        },
        onError: (err: Error) => {
            if (err.message !== 'cancelled') {
                toast.error(err.message || 'Failed to delete workspace');
            }
        },
    });

    if (!currentWorkspace) return null;

    const isOwner = currentWorkspace.my_role?.toLowerCase() === 'owner';

    return (
        <div className="flex-1 p-6 max-w-2xl space-y-8">
            <h1 className="text-xl font-semibold">Workspace Settings</h1>

            {/* Basic Info */}
            <section className="space-y-4">
                <h2 className="text-sm font-semibold border-b pb-2">General</h2>

                {/* Workspace Avatar & Slug */}
                <div className="flex items-center gap-4">
                    <Avatar className="h-16 w-16 rounded-xl">
                        <AvatarImage src={currentWorkspace.avatar_url ?? ''}/>
                        <AvatarFallback className="rounded-xl bg-zinc-100 dark:bg-zinc-800 text-xl font-bold">
                            {currentWorkspace.name.charAt(0).toUpperCase()}
                        </AvatarFallback>
                    </Avatar>
                    <div className="flex-1">
                        <p className="font-semibold text-lg">{currentWorkspace.name}</p>
                        <p className="text-sm text-muted-foreground">
                            <span className="font-mono text-xs">w/{currentWorkspace.slug}</span>
                        </p>
                    </div>
                </div>

                {/* Avatar URL */}
                <div className="space-y-2">
                    <Label htmlFor="avatar_url">Avatar URL</Label>
                    <Input
                        id="avatar_url"
                        value={avatarUrl}
                        onChange={(e) => setAvatarUrl(e.target.value)}
                        placeholder="https://example.com/avatar.png"
                    />
                    <p className="text-xs text-muted-foreground">
                        Enter a URL to an image for the workspace avatar.
                    </p>
                </div>

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

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

                {/* Billing Email */}
                <div className="space-y-2">
                    <Label htmlFor="billing_email">Billing Email</Label>
                    <Input
                        id="billing_email"
                        type="email"
                        value={billingEmail}
                        onChange={(e) => setBillingEmail(e.target.value)}
                        placeholder="billing@example.com"
                    />
                    <p className="text-xs text-muted-foreground">
                        Invoices will be sent to this email.
                    </p>
                </div>

                <Button
                    onClick={() => updateMutation.mutate()}
                    disabled={updateMutation.isPending || (!name && !description && !avatarUrl && !billingEmail)}
                >
                    {updateMutation.isPending ? 'Saving...' : 'Save Changes'}
                </Button>
            </section>

            {/* Plan Info */}
            <section className="space-y-4">
                <h2 className="text-sm font-semibold border-b pb-2">Plan</h2>
                <div className="flex items-center justify-between rounded-lg border p-4">
                    <div>
                        <p className="font-medium">Current Plan</p>
                        <p className="text-sm text-muted-foreground capitalize">{currentWorkspace.plan}</p>
                    </div>
                    <Button variant="outline" size="sm" onClick={() => navigate(`/w/${currentWorkspace.slug}/billing`)}>
                        Manage Billing
                    </Button>
                </div>
            </section>

            {/* Danger Zone */}
            {isOwner && (
                <section className="space-y-4">
                    <h2 className="text-sm font-semibold border-b pb-2 text-destructive">Danger Zone</h2>
                    <div className="rounded-lg border border-destructive/30 p-4 space-y-3">
                        <div>
                            <p className="font-medium text-sm">Delete Workspace</p>
                            <p className="text-xs text-muted-foreground">
                                Permanently delete this workspace and all its data. This action cannot be undone.
                            </p>
                        </div>
                        <Button
                            variant="destructive"
                            size="sm"
                            onClick={() => deleteMutation.mutate()}
                            disabled={deleteMutation.isPending}
                        >
                            {deleteMutation.isPending ? 'Deleting...' : 'Delete Workspace'}
                        </Button>
                    </div>
                </section>
            )}
        </div>
    );
}
