import { BookOpen, FolderGit2, Globe, LogIn, Plus, Sparkles, UserPlus, Users } from 'lucide-react';
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';

import { CreateWorkspaceModal } from '@/components/CreateWorkspaceModal';
import { useUserContext } from '@/contexts/UserContext';
import { useAllWorkspaceStats } from '@/hooks/workspace/useAllWorkspaceStats';
import { useWorkspaceList } from '@/hooks/workspace/useWorkspaceList';

// ---------------------------------------------------------------------------
// Loading
// ---------------------------------------------------------------------------

function Spinner() {
  return (
    <div className="flex items-center justify-center py-20">
      <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
    </div>
  );
}

// ---------------------------------------------------------------------------
// Unauthenticated landing
// ---------------------------------------------------------------------------

function WelcomeHero() {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center">
      <div className="flex size-16 items-center justify-center rounded-full bg-muted">
        <Sparkles className="size-8 text-muted-foreground/60" />
      </div>
      <h1 className="mt-5 text-2xl font-semibold tracking-tight text-foreground">
        Welcome to GitDataAi
      </h1>
      <p className="mt-3 max-w-md text-[14px] text-muted-foreground">
        Sign in to manage your repositories, issues, and pull requests across all your workspaces.
      </p>
      <div className="mt-6 flex gap-3">
        <Link
          to="/auth/login"
          className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/85"
        >
          <LogIn className="size-4" />
          Sign in
        </Link>
        <Link
          to="/auth/register"
          className="inline-flex items-center gap-2 rounded-lg border border-border px-4 py-2 text-sm font-medium text-foreground transition-colors hover:bg-muted"
        >
          <UserPlus className="size-4" />
          Create account
        </Link>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// HomePage — user personal page
// ---------------------------------------------------------------------------

export function HomePage() {
  const { user, isLoading: userLoading, isAuthenticated } = useUserContext();
  const { data: workspaces, isLoading: wsLoading } = useWorkspaceList();
  const [createWsOpen, setCreateWsOpen] = useState(false);
  const navigate = useNavigate();

  const workspaceList = workspaces ?? [];
  const statsResults = useAllWorkspaceStats(workspaceList);

  // Loading
  if (userLoading || wsLoading) {
    return (
      <ContentCard>
        <Spinner />
      </ContentCard>
    );
  }

  // Unauthenticated
  if (!isAuthenticated) {
    return (
      <ContentCard>
        <WelcomeHero />
      </ContentCard>
    );
  }

  const totalRepos = statsResults.reduce((s, r) => s + (r.data?.repos_count ?? 0), 0);
  const totalMembers = statsResults.reduce((s, r) => s + (r.data?.members_count ?? 0), 0);

  return (
    <ContentCard>
      <div className="px-6 pt-10 pb-16">
        {/* User profile header */}
        <div className="mb-10 flex items-center gap-5">
          {user?.avatar_url ? (
            <img
              src={user.avatar_url}
              alt={user.username ?? ''}
              className="size-20 rounded-full border-2 border-border object-cover"
            />
          ) : (
            <div className="flex size-20 items-center justify-center rounded-full bg-primary text-2xl font-bold text-primary-foreground">
              {(user?.username ?? 'U').slice(0, 2).toUpperCase()}
            </div>
          )}
          <div>
            <h1 className="text-2xl font-semibold text-foreground">
              {user?.display_name ?? user?.username ?? '—'}
            </h1>
            <p className="mt-1 text-[14px] text-muted-foreground">@{user?.username ?? '—'}</p>
            <div className="mt-2 flex gap-4 text-[13px] text-muted-foreground">
              <span className="flex items-center gap-1">
                <FolderGit2 className="size-3.5" />
                {totalRepos} repos
              </span>
              <span className="flex items-center gap-1">
                <Users className="size-3.5" />
                {totalMembers} members
              </span>
              <span className="flex items-center gap-1">
                <Globe className="size-3.5" />
                {workspaceList.length} {workspaceList.length === 1 ? 'workspace' : 'workspaces'}
              </span>
            </div>
          </div>
        </div>

        {/* Workspace list */}
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Globe className="size-4 text-muted-foreground" />
            <h2 className="text-[15px] font-semibold text-foreground">Your workspaces</h2>
          </div>
          <button
            type="button"
            onClick={() => setCreateWsOpen(true)}
            className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-[5px] text-[13px] font-medium text-primary-foreground transition-colors hover:bg-primary/85"
          >
            <Plus className="size-3.5" />
            New workspace
          </button>
        </div>

        {workspaceList.length === 0 ? (
          <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-16 text-center">
            <FolderGit2 className="size-8 text-muted-foreground/40" />
            <p className="mt-3 text-[14px] text-muted-foreground">
              No workspaces yet. Create your first one.
            </p>
          </div>
        ) : (
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {workspaceList.map((ws, i) => {
              const stats = statsResults[i]?.data;
              return (
                <button
                  key={ws.id}
                  type="button"
                  onClick={() => navigate(`/${ws.name}`)}
                  className="flex items-center gap-3 rounded-xl border border-border bg-card p-4 text-left transition-colors hover:border-primary/30 hover:shadow-sm"
                >
                  {ws.avatar_url ? (
                    <img
                      src={ws.avatar_url}
                      alt={ws.name}
                      className="size-10 rounded-lg object-cover"
                    />
                  ) : (
                    <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-sm font-semibold text-muted-foreground">
                      {ws.name.slice(0, 2).toUpperCase()}
                    </div>
                  )}
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-[14px] font-semibold text-foreground">{ws.name}</p>
                    <p className="mt-0.5 text-[12px] text-muted-foreground capitalize">
                      {ws.visibility}
                      {ws.is_personal ? ' · Personal' : ''}
                    </p>
                  </div>
                  {stats && (
                    <div className="shrink-0 text-right text-[11px] text-muted-foreground">
                      <p className="flex items-center gap-1">
                        <BookOpen className="size-3" />
                        {stats.repos_count}
                      </p>
                      <p className="mt-0.5 flex items-center gap-1">
                        <Users className="size-3" />
                        {stats.members_count}
                      </p>
                    </div>
                  )}
                </button>
              );
            })}
          </div>
        )}
      </div>
      <CreateWorkspaceModal open={createWsOpen} onClose={() => setCreateWsOpen(false)} />
    </ContentCard>
  );
}

// ---------------------------------------------------------------------------
// ContentCard
// ---------------------------------------------------------------------------

function ContentCard({ children }: { children: React.ReactNode }) {
  return (
    <div className="flex flex-1 flex-col pr-4 pb-2 pl-4 gap-1">
      <div className="h-12 shrink-0 rounded-xl bg-background shadow-sm" />
      <div className="flex flex-1 flex-col min-h-0 rounded-2xl bg-background shadow-[0_2px_16px_rgba(0,0,0,0.06),0_0_0_1px_rgba(0,0,0,0.03)] overflow-hidden">
        <main className="flex-1 overflow-y-auto">{children}</main>
      </div>
    </div>
  );
}
