import { Crown, Mail, MoreHorizontal, Shield, User, UserPlus } from 'lucide-react';
import { useParams } from 'react-router-dom';

import { useWorkspaceMembers } from '@/hooks/workspace/useWorkspaceMembers';
import { cn, timeAgo } from '@/lib/utils';

// ---------------------------------------------------------------------------
// WorkspaceMembersPage
// ---------------------------------------------------------------------------

export function WorkspaceMembersPage() {
  const { workspaceName } = useParams<{ workspaceName: string }>();
  const { data: members, isLoading, error } = useWorkspaceMembers(workspaceName ?? null);

  const list = members ?? [];
  const activeMembers = list.filter((m) => m.status === 'Active');
  const pendingMembers = list.filter((m) => m.status !== 'Active');

  return (
    <div className="px-6 pt-8 pb-16">
      {/* Header */}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-foreground">Members</h1>
          <p className="mt-1 text-[13px] text-muted-foreground">
            Manage who has access to this workspace.
          </p>
        </div>
        <button
          type="button"
          className="inline-flex items-center gap-2 rounded-md bg-primary px-3 py-[6px] text-[13px] font-medium text-primary-foreground transition-colors hover:bg-primary/85"
        >
          <UserPlus className="size-3.5" />
          Invite member
        </button>
      </div>

      {/* Loading */}
      {isLoading && (
        <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
          <span className="inline-block size-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
          Loading members…
        </div>
      )}

      {/* Error */}
      {error && (
        <div className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-[14px] text-destructive">
          Failed to load members.
        </div>
      )}

      {/* Active members */}
      {!isLoading && !error && (
        <>
          <div className="mb-4">
            <h2 className="text-[13px] font-semibold text-foreground">
              Active members
              <span className="ml-2 font-normal text-muted-foreground">
                ({activeMembers.length})
              </span>
            </h2>
          </div>

          {activeMembers.length === 0 ? (
            <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-16 text-center">
              <User className="size-8 text-muted-foreground/40" />
              <p className="mt-3 text-[14px] text-muted-foreground">No active members.</p>
            </div>
          ) : (
            <div className="space-y-1.5">
              {activeMembers.map((m) => (
                <div
                  key={m.id}
                  className="flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 transition-colors hover:border-primary/30"
                >
                  <div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-muted">
                    <User className="size-4 text-muted-foreground" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-[14px] font-medium text-foreground">{m.user_id}</p>
                    <p className="mt-0.5 text-[12px] text-muted-foreground">
                      Joined {m.joined_at ? timeAgo(m.joined_at) : 'Unknown'}
                    </p>
                  </div>
                  <RoleBadge role={m.role} />
                  <button
                    type="button"
                    className="flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
                  >
                    <MoreHorizontal className="size-4" />
                  </button>
                </div>
              ))}
            </div>
          )}

          {/* Pending members */}
          {pendingMembers.length > 0 && (
            <div className="mt-8">
              <h2 className="mb-3 text-[13px] font-semibold text-foreground">
                Pending
                <span className="ml-2 font-normal text-muted-foreground">
                  ({pendingMembers.length})
                </span>
              </h2>
              <div className="space-y-1.5">
                {pendingMembers.map((m) => (
                  <div
                    key={m.id}
                    className="flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 opacity-70"
                  >
                    <div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-muted">
                      <Mail className="size-4 text-muted-foreground" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-[14px] font-medium text-foreground">
                        {m.user_id}
                      </p>
                      <p className="mt-0.5 text-[12px] text-muted-foreground">
                        Invited {timeAgo(m.created_at)}
                      </p>
                    </div>
                    <span className="shrink-0 rounded-full bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-600">
                      Pending
                    </span>
                    <RoleBadge role={m.role} />
                  </div>
                ))}
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// RoleBadge
// ---------------------------------------------------------------------------

function RoleBadge({ role }: { role: string }) {
  return (
    <span
      className={cn(
        'shrink-0 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium',
        role === 'Owner'
          ? 'bg-amber-500/10 text-amber-600'
          : role === 'Admin'
            ? 'bg-primary/10 text-primary'
            : role === 'Maintainer'
              ? 'bg-blue-500/10 text-blue-600'
              : 'bg-muted text-muted-foreground',
      )}
    >
      {role === 'Owner' && <Crown className="size-2.5" />}
      {role === 'Admin' && <Shield className="size-2.5" />}
      {role}
    </span>
  );
}

// ---------------------------------------------------------------------------
// timeAgo
// ---------------------------------------------------------------------------
