'use client';

import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { type ColumnDef } from '@tanstack/react-table';
import { Pencil, Trash2, Plus, ShieldCheck, ShieldOff, Power, PowerOff } from 'lucide-react';

import { DataTable } from '@/components/shared/data-table';
import { PageHeader } from '@/components/shared/page-header';
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
import { PermissionGate } from '@/components/shared/permission-gate';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { StatusPill } from '@/components/ui/status-pill';
import { apiFetch } from '@/lib/api/client';
import { formatRole } from '@/lib/constants';
import { formatDate } from '@/lib/utils/format-date';
import { UserCard } from './user-card';
import { UserForm } from './user-form';

interface UserRow {
  userId: string;
  displayName: string;
  email: string;
  phone: string | null;
  isActive: boolean;
  isSuperAdmin: boolean;
  lastLoginAt: string | null;
  role: { id: string; name: string };
  assignedAt: string;
}

const USERS_QUERY_KEY = ['admin', 'users'] as const;

export function UserList() {
  const queryClient = useQueryClient();
  const [formOpen, setFormOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<UserRow | null>(null);

  const { data: users = [], isLoading: loading } = useQuery<UserRow[]>({
    queryKey: USERS_QUERY_KEY,
    queryFn: () => apiFetch<{ data: UserRow[] }>('/api/v1/admin/users').then((r) => r.data),
  });

  const fetchUsers = () => queryClient.invalidateQueries({ queryKey: USERS_QUERY_KEY });

  const removeMutation = useMutation({
    mutationFn: (userId: string) => apiFetch(`/api/v1/admin/users/${userId}`, { method: 'DELETE' }),
    onSuccess: () => fetchUsers(),
  });

  const toggleMutation = useMutation({
    mutationFn: (user: UserRow) =>
      apiFetch(`/api/v1/admin/users/${user.userId}`, {
        method: 'PATCH',
        body: { isActive: !user.isActive },
      }),
    onSuccess: () => fetchUsers(),
  });

  const deletingId = removeMutation.isPending ? removeMutation.variables : null;
  const togglingId = toggleMutation.isPending ? (toggleMutation.variables?.userId ?? null) : null;

  function handleNewUser() {
    setEditingUser(null);
    setFormOpen(true);
  }

  function handleEditUser(user: UserRow) {
    setEditingUser(user);
    setFormOpen(true);
  }

  function handleRemoveUser(userId: string) {
    removeMutation.mutate(userId);
  }

  function handleToggleActive(user: UserRow) {
    toggleMutation.mutate(user);
  }

  const columns: ColumnDef<UserRow, unknown>[] = [
    {
      accessorKey: 'displayName',
      header: 'Name',
      cell: ({ row }) => (
        <div className="flex flex-col">
          <span className="font-medium">{row.original.displayName}</span>
          <span className="text-xs text-muted-foreground">{row.original.email}</span>
        </div>
      ),
    },
    {
      accessorKey: 'role',
      header: 'Role',
      cell: ({ row }) => <Badge variant="secondary">{formatRole(row.original.role.name)}</Badge>,
    },
    {
      accessorKey: 'isActive',
      header: 'Status',
      cell: ({ row }) =>
        row.original.isActive ? (
          <StatusPill status="enabled">
            <ShieldCheck className="h-3 w-3" aria-hidden />
            Active
          </StatusPill>
        ) : (
          <StatusPill status="disabled">
            <ShieldOff className="h-3 w-3" aria-hidden />
            Disabled
          </StatusPill>
        ),
    },
    {
      accessorKey: 'lastLoginAt',
      header: 'Last Login',
      cell: ({ row }) =>
        row.original.lastLoginAt ? formatDate(row.original.lastLoginAt, 'date.medium') : 'Never',
    },
    {
      id: 'actions',
      header: '',
      cell: ({ row }) => (
        <div className="flex items-center justify-end gap-1">
          <PermissionGate resource="admin" action="manage_users">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleEditUser(row.original)}
              title="Edit user"
            >
              <Pencil className="h-4 w-4" aria-hidden />
              <span className="sr-only">Edit</span>
            </Button>
          </PermissionGate>
          <PermissionGate resource="admin" action="manage_users">
            <ConfirmationDialog
              trigger={
                <Button
                  variant="ghost"
                  size="sm"
                  title={row.original.isActive ? 'Disable sign-in' : 'Enable sign-in'}
                  disabled={togglingId === row.original.userId}
                  className={
                    row.original.isActive
                      ? 'text-muted-foreground hover:text-foreground'
                      : 'text-emerald-600 hover:text-emerald-700'
                  }
                >
                  {row.original.isActive ? (
                    <PowerOff className="h-4 w-4" aria-hidden />
                  ) : (
                    <Power className="h-4 w-4" aria-hidden />
                  )}
                  <span className="sr-only">{row.original.isActive ? 'Disable' : 'Enable'}</span>
                </Button>
              }
              title={row.original.isActive ? 'Disable user' : 'Enable user'}
              description={
                row.original.isActive
                  ? `Disable sign-in for "${row.original.displayName}"? Their account stays intact; they just can't log in until you re-enable.`
                  : `Re-enable sign-in for "${row.original.displayName}"?`
              }
              confirmLabel={row.original.isActive ? 'Disable' : 'Enable'}
              onConfirm={() => handleToggleActive(row.original)}
              loading={togglingId === row.original.userId}
            />
          </PermissionGate>
          <PermissionGate resource="admin" action="manage_users">
            <ConfirmationDialog
              trigger={
                <Button
                  variant="ghost"
                  size="sm"
                  title="Remove from port"
                  className="text-destructive hover:text-destructive"
                >
                  <Trash2 className="h-4 w-4" aria-hidden />
                  <span className="sr-only">Remove</span>
                </Button>
              }
              title="Remove User"
              description={`Remove "${row.original.displayName}" from this port? They will lose access but their account remains.`}
              confirmLabel="Remove"
              onConfirm={() => handleRemoveUser(row.original.userId)}
              loading={deletingId === row.original.userId}
            />
          </PermissionGate>
        </div>
      ),
      enableSorting: false,
      size: 120,
    },
  ];

  return (
    <div>
      <PageHeader
        title="User Management"
        description="Manage users and their roles for this port"
        actions={
          <Button onClick={handleNewUser}>
            <Plus className="mr-1.5 h-4 w-4" aria-hidden />
            New User
          </Button>
        }
      />

      <DataTable
        columns={columns}
        data={users}
        isLoading={loading}
        getRowId={(row) => row.userId}
        cardRender={(row) => (
          <UserCard
            user={row.original}
            onEdit={handleEditUser}
            onRemove={handleRemoveUser}
            onToggleActive={handleToggleActive}
            isRemoving={deletingId === row.original.userId}
            isToggling={togglingId === row.original.userId}
          />
        )}
        emptyState={
          <div className="text-center py-8">
            <p className="text-muted-foreground">No users assigned to this port.</p>
            <Button variant="link" onClick={handleNewUser} className="mt-2">
              Add the first user
            </Button>
          </div>
        }
      />

      <UserForm
        open={formOpen}
        onOpenChange={setFormOpen}
        user={editingUser}
        onSuccess={fetchUsers}
      />
    </div>
  );
}
