import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { Plus, Trash2, User } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import { useAddRepoMember } from '@/hooks/repo/useAddRepoMember';
import { useRemoveRepoMember } from '@/hooks/repo/useRemoveRepoMember';
import { useRepoMembers } from '@/hooks/repo/useRepoMembers';
import { useUpdateRepoMemberRole } from '@/hooks/repo/useUpdateRepoMemberRole';
import { cn, timeAgo } from '@/lib/utils';
import type { Role } from '@/client/models/Role';

const ROLES: Role[] = ['Owner', 'Admin', 'Maintainer', 'Member', 'Viewer'];

export function RepoMembersPage() {
  const { workspaceName = '', repoName = '' } = useParams();
  const [showAdd, setShowAdd] = useState(false);
  const [newUserId, setNewUserId] = useState('');
  const [newRole, setNewRole] = useState<Role>('Member');

  const { data: members, isLoading } = useRepoMembers(workspaceName, repoName, 100);
  const addMember = useAddRepoMember();
  const removeMember = useRemoveRepoMember();
  const updateRole = useUpdateRepoMemberRole();

  const handleAdd = () => {
    if (!newUserId.trim()) return;
    addMember.mutate(
      { userId: newUserId.trim(), role: newRole },
      {
        onSuccess: () => {
          setNewUserId('');
          setNewRole('Member');
          setShowAdd(false);
        },
      },
    );
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-[12px] text-muted-foreground">
          {(members ?? []).length} member{(members ?? []).length !== 1 ? 's' : ''}
        </p>
        <Button size="sm" onClick={() => setShowAdd(!showAdd)}>
          <Plus className="size-3.5" />
          Add member
        </Button>
      </div>

      {showAdd && (
        <div className="flex items-center gap-2 rounded-lg border border-border p-3">
          <Input
            className="h-8 flex-1 text-[13px]"
            placeholder="User ID"
            value={newUserId}
            onChange={(e) => setNewUserId(e.target.value)}
          />
          <select
            className="h-8 rounded-lg border border-border bg-transparent px-2 text-[13px] text-foreground"
            value={newRole}
            onChange={(e) => setNewRole(e.target.value as Role)}
          >
            {ROLES.map((r) => (
              <option key={r} value={r}>
                {r}
              </option>
            ))}
          </select>
          <Button size="sm" disabled={!newUserId.trim() || addMember.isPending} onClick={handleAdd}>
            Add
          </Button>
          <Button size="sm" variant="outline" onClick={() => setShowAdd(false)}>
            Cancel
          </Button>
        </div>
      )}

      <div className="overflow-hidden rounded-lg border border-border">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Spinner />
          </div>
        ) : (members ?? []).length > 0 ? (
          <div className="divide-y divide-border">
            {(members ?? []).map((member) => (
              <div
                key={member.id}
                className="flex items-center gap-3 px-4 py-2.5 transition-colors hover:bg-muted/40"
              >
                <div className="flex size-8 items-center justify-center rounded-full bg-muted text-[11px] font-semibold text-muted-foreground">
                  <User className="size-4" />
                </div>
                <div className="min-w-0 flex-1">
                  <span className="text-[13px] font-medium text-foreground">
                    {member.user_id}
                  </span>
                  <div className="text-[11px] text-muted-foreground">
                    Joined {timeAgo(member.created_at)}
                    {member.last_active_at && ` · Active ${timeAgo(member.last_active_at)}`}
                  </div>
                </div>
                <select
                  className="h-7 rounded border border-border bg-transparent px-2 text-[12px] text-foreground"
                  value={member.role}
                  onChange={(e) =>
                    updateRole.mutate({
                      memberId: member.id,
                      role: e.target.value as Role,
                    })
                  }
                >
                  {ROLES.map((r) => (
                    <option key={r} value={r}>
                      {r}
                    </option>
                  ))}
                </select>
                <RoleBadge role={member.role} />
                {member.role !== 'Owner' && (
                  <Button
                    size="icon-sm"
                    variant="ghost"
                    className="text-muted-foreground hover:text-destructive"
                    onClick={() => {
                      if (confirm(`Remove member?`)) removeMember.mutate(member.id);
                    }}
                  >
                    <Trash2 className="size-3.5" />
                  </Button>
                )}
              </div>
            ))}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center py-16 text-center">
            <User className="size-6 text-muted-foreground/30" />
            <p className="mt-3 text-[13px] text-muted-foreground">No members</p>
          </div>
        )}
      </div>
    </div>
  );
}

function RoleBadge({ role }: { role: string }) {
  const colors: Record<string, string> = {
    Owner: 'text-purple-600 bg-purple-500/10',
    Admin: 'text-red-600 bg-red-500/10',
    Maintainer: 'text-blue-600 bg-blue-500/10',
    Member: 'text-muted-foreground bg-muted',
    Viewer: 'text-muted-foreground/70 bg-muted/50',
  };
  return (
    <span
      className={cn(
        'rounded px-1.5 py-0.5 text-[10px] font-medium',
        colors[role] || colors.Member,
      )}
    >
      {role}
    </span>
  );
}
