'use client';

import { useState, useEffect, useCallback } from 'react';
import { type ColumnDef } from '@tanstack/react-table';
import { Pencil, Trash2, Plus, ShieldCheck, ShieldOff } 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 { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { apiFetch } from '@/lib/api/client';
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;
}

export function UserList() {
  const [users, setUsers] = useState<UserRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [formOpen, setFormOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<UserRow | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      const res = await apiFetch<{ data: UserRow[] }>('/api/v1/admin/users');
      setUsers(res.data);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void fetchUsers();
  }, [fetchUsers]);

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

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

  async function handleRemoveUser(userId: string) {
    setDeletingId(userId);
    try {
      await apiFetch(`/api/v1/admin/users/${userId}`, { method: 'DELETE' });
      await fetchUsers();
    } finally {
      setDeletingId(null);
    }
  }

  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">{row.original.role.name}</Badge>,
    },
    {
      accessorKey: 'isActive',
      header: 'Status',
      cell: ({ row }) =>
        row.original.isActive ? (
          <Badge variant="default" className="bg-green-600">
            <ShieldCheck className="mr-1 h-3 w-3" />
            Active
          </Badge>
        ) : (
          <Badge variant="destructive">
            <ShieldOff className="mr-1 h-3 w-3" />
            Disabled
          </Badge>
        ),
    },
    {
      accessorKey: 'lastLoginAt',
      header: 'Last Login',
      cell: ({ row }) =>
        row.original.lastLoginAt
          ? new Date(row.original.lastLoginAt).toLocaleDateString()
          : 'Never',
    },
    {
      id: 'actions',
      header: '',
      cell: ({ row }) => (
        <div className="flex items-center justify-end gap-1">
          <Button variant="ghost" size="sm" onClick={() => handleEditUser(row.original)}>
            <Pencil className="h-4 w-4" />
            <span className="sr-only">Edit</span>
          </Button>
          <ConfirmationDialog
            trigger={
              <Button variant="ghost" size="sm" className="text-destructive hover:text-destructive">
                <Trash2 className="h-4 w-4" />
                <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}
          />
        </div>
      ),
      enableSorting: false,
      size: 80,
    },
  ];

  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" />
            New User
          </Button>
        }
      />

      <DataTable
        columns={columns}
        data={users}
        isLoading={loading}
        getRowId={(row) => row.userId}
        cardRender={(row) => (
          <UserCard
            user={row.original}
            onEdit={handleEditUser}
            onRemove={handleRemoveUser}
            isRemoving={deletingId === 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>
  );
}
