import {useNavigate} from 'react-router-dom';
import {useQuery} from '@tanstack/react-query';
import {workspaceStats, type WorkspaceStatsResponse} from '@/client';
import {useWorkspace} from '@/contexts';
import {Badge} from '@/components/ui/badge';
import {Card, CardContent, CardHeader, CardTitle} from '@/components/ui/card';
import {Spinner} from '@/components/ui/spinner';
import {Activity, FolderOpen, Users} from 'lucide-react';

export function WorkspaceOverview() {
    const {currentWorkspace, isLoading} = useWorkspace();
    const navigate = useNavigate();

    const {data: stats, isLoading: statsLoading} = useQuery({
        queryKey: ['workspaceStats', currentWorkspace?.slug],
        queryFn: async (): Promise<WorkspaceStatsResponse | null> => {
            if (!currentWorkspace?.slug) return null;
            const resp = await workspaceStats({path: {slug: currentWorkspace.slug}});
            return resp.data?.data ?? null;
        },
        enabled: !!currentWorkspace?.slug,
    });

    if (isLoading || statsLoading) {
        return (
            <div className="flex items-center justify-center h-64">
                <Spinner/>
            </div>
        );
    }

    if (!currentWorkspace) return null;

    const isAdmin = currentWorkspace.my_role?.toLowerCase() === 'owner' || currentWorkspace.my_role?.toLowerCase() === 'admin';

    return (
        <div className="flex-1 p-6 space-y-6">
            {/* Header */}
            <div className="flex items-start justify-between gap-4">
                <div className="flex items-center gap-3">
                    <div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
                        <span className="text-xl font-bold text-primary">
                            {currentWorkspace.name.charAt(0).toUpperCase()}
                        </span>
                    </div>
                    <div>
                        <h1 className="text-2xl font-bold">{currentWorkspace.name}</h1>
                        <p className="text-sm text-muted-foreground">
                            {currentWorkspace.description || 'No description'}
                        </p>
                    </div>
                </div>
                {isAdmin && (
                    <button
                        className="px-4 py-2 text-sm border rounded-md hover:bg-muted transition-colors"
                        onClick={() => navigate(`/w/${currentWorkspace.slug}/settings`)}
                    >
                        Settings
                    </button>
                )}
            </div>

            {/* Stats cards */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1.5">
                            <FolderOpen className="h-3.5 w-3.5"/> Projects
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <span className="text-2xl font-bold">{stats?.project_count ?? 0}</span>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1.5">
                            <Users className="h-3.5 w-3.5"/> Members
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <span className="text-2xl font-bold">{stats?.member_count ?? 0}</span>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Plan</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <Badge variant="outline">{currentWorkspace.plan}</Badge>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Your Role</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <Badge variant="secondary">{currentWorkspace.my_role || 'Guest'}</Badge>
                    </CardContent>
                </Card>
            </div>

            {/* Recent Activity */}
            <div>
                <div className="flex items-center justify-between mb-3">
                    <h2 className="text-sm font-semibold flex items-center gap-1.5">
                        <Activity className="h-4 w-4"/> Recent Activity
                    </h2>
                </div>
                {stats?.recent_activities && stats.recent_activities.length > 0 ? (
                    <div className="border rounded-lg divide-y">
                        {stats.recent_activities.map((activity) => (
                            <div key={activity.id} className="px-4 py-3 flex items-start gap-3">
                                <div className="flex-1 min-w-0">
                                    <p className="text-sm truncate">{activity.title}</p>
                                    <p className="text-xs text-muted-foreground">
                                        {activity.actor_name} · {activity.project_name} · {formatRelativeTime(activity.created_at)}
                                    </p>
                                </div>
                            </div>
                        ))}
                    </div>
                ) : (
                    <div className="border border-dashed rounded-lg py-8 text-center text-sm text-muted-foreground">
                        No recent activity in this workspace.
                    </div>
                )}
            </div>

            {/* Quick actions */}
            <div className="flex gap-3">
                <button
                    className="px-4 py-2 text-sm border rounded-md hover:bg-muted transition-colors"
                    onClick={() => navigate(`/w/${currentWorkspace.slug}/projects`)}
                >
                    View Projects
                </button>
                <button
                    className="px-4 py-2 text-sm border rounded-md hover:bg-muted transition-colors"
                    onClick={() => navigate(`/w/${currentWorkspace.slug}/members`)}
                >
                    Manage Members
                </button>
            </div>
        </div>
    );
}

function formatRelativeTime(date: Date | string): string {
    const now = new Date();
    const diff = now.getTime() - new Date(date).getTime();
    const seconds = Math.floor(diff / 1000);
    if (seconds < 60) return 'just now';
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    if (days < 7) return `${days}d ago`;
    return new Date(date).toLocaleDateString();
}
