import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Plus,
  MoreVertical,
  Eye,
  Edit,
  Trash2,
  UserCheck,
  UserX,
  Mail,
} from 'lucide-react';
import { Button } from '@components/atoms/Button';
import { Avatar } from '@components/atoms/Avatar';
import { Card, CardHeader, CardTitle, CardContent } from '@components/molecules/Card';
import { DataTable, type Column } from '@components/organisms/DataTable';
import { Dropdown, type DropdownItem } from '@components/organisms/Dropdown';
import { ConfirmModal } from '@components/organisms/Modal';
import { Breadcrumbs } from '@components/organisms/Breadcrumbs';
import { NoDataEmptyState, ErrorEmptyState } from '@components/templates/EmptyState';
import { useUsers } from '@features/users/hooks';
import { UserStatusBadge } from '@features/users/components/UserStatusBadge';
import { UserFiltersPanel } from '@features/users/components/UserFiltersPanel';
import type { User } from '@features/users/types';
import { formatDate } from '@utils/formatters';

export function UsersListPage() {
  const navigate = useNavigate();
  const [userToDelete, setUserToDelete] = useState<User | null>(null);
  const [userToToggle, setUserToToggle] = useState<{ user: User; action: 'activate' | 'deactivate' } | null>(null);

  const {
    users,
    total,
    page,
    totalPages,
    isLoading,
    error,
    filters,
    setFilters,
    deleteUser,
    activateUser,
    deactivateUser,
    refresh,
  } = useUsers({ page: 1, limit: 10 });

  const getActionsMenu = (user: User): DropdownItem[] => {
    const items: DropdownItem[] = [
      {
        key: 'view',
        label: 'Ver detalle',
        icon: <Eye className="h-4 w-4" />,
        onClick: () => navigate(`/users/${user.id}`),
      },
      {
        key: 'edit',
        label: 'Editar',
        icon: <Edit className="h-4 w-4" />,
        onClick: () => navigate(`/users/${user.id}/edit`),
      },
      {
        key: 'email',
        label: 'Enviar email',
        icon: <Mail className="h-4 w-4" />,
        onClick: () => window.location.href = `mailto:${user.email}`,
      },
    ];

    if (user.status === 'active') {
      items.push({
        key: 'deactivate',
        label: 'Desactivar',
        icon: <UserX className="h-4 w-4" />,
        onClick: () => setUserToToggle({ user, action: 'deactivate' }),
      });
    } else {
      items.push({
        key: 'activate',
        label: 'Activar',
        icon: <UserCheck className="h-4 w-4" />,
        onClick: () => setUserToToggle({ user, action: 'activate' }),
      });
    }

    items.push({
      key: 'delete',
      label: 'Eliminar',
      icon: <Trash2 className="h-4 w-4" />,
      danger: true,
      onClick: () => setUserToDelete(user),
    });

    return items;
  };

  const columns: Column<User>[] = [
    {
      key: 'user',
      header: 'Usuario',
      render: (user) => (
        <div className="flex items-center gap-3">
          <Avatar
            src={user.avatar}
            fallback={`${user.firstName} ${user.lastName}`}
            size="sm"
            status={user.status === 'active' ? 'online' : 'offline'}
          />
          <div>
            <div className="font-medium text-gray-900">
              {user.firstName} {user.lastName}
            </div>
            <div className="text-sm text-gray-500">{user.email}</div>
          </div>
        </div>
      ),
    },
    {
      key: 'role',
      header: 'Rol',
      render: (user) => (
        <span className="text-sm text-gray-600">{user.role?.name || '-'}</span>
      ),
    },
    {
      key: 'status',
      header: 'Estado',
      render: (user) => <UserStatusBadge status={user.status} />,
    },
    {
      key: 'lastLoginAt',
      header: 'Último acceso',
      render: (user) => (
        <span className="text-sm text-gray-500">
          {user.lastLoginAt ? formatDate(user.lastLoginAt, 'relative') : 'Nunca'}
        </span>
      ),
    },
    {
      key: 'createdAt',
      header: 'Creado',
      sortable: true,
      render: (user) => (
        <span className="text-sm text-gray-500">
          {formatDate(user.createdAt, 'short')}
        </span>
      ),
    },
    {
      key: 'actions',
      header: '',
      render: (user) => (
        <Dropdown
          trigger={
            <button className="rounded p-1 hover:bg-gray-100">
              <MoreVertical className="h-4 w-4 text-gray-500" />
            </button>
          }
          items={getActionsMenu(user)}
          align="right"
        />
      ),
    },
  ];

  const handlePageChange = (newPage: number) => {
    setFilters({ ...filters, page: newPage });
  };

  const handleSort = (key: string) => {
    const newOrder = filters.sortBy === key && filters.sortOrder === 'asc' ? 'desc' : 'asc';
    setFilters({ ...filters, sortBy: key, sortOrder: newOrder });
  };

  const handleDeleteConfirm = async () => {
    if (userToDelete) {
      await deleteUser(userToDelete.id);
      setUserToDelete(null);
    }
  };

  const handleToggleConfirm = async () => {
    if (userToToggle) {
      if (userToToggle.action === 'activate') {
        await activateUser(userToToggle.user.id);
      } else {
        await deactivateUser(userToToggle.user.id);
      }
      setUserToToggle(null);
    }
  };

  if (error) {
    return (
      <div className="p-6">
        <ErrorEmptyState onRetry={refresh} />
      </div>
    );
  }

  return (
    <div className="space-y-6 p-6">
      <Breadcrumbs
        items={[{ label: 'Usuarios' }]}
      />

      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Usuarios</h1>
          <p className="text-sm text-gray-500">
            Gestiona los usuarios del sistema
          </p>
        </div>
        <Button onClick={() => navigate('/users/new')}>
          <Plus className="mr-2 h-4 w-4" />
          Nuevo usuario
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Lista de usuarios</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <UserFiltersPanel
              filters={filters}
              onFiltersChange={setFilters}
            />

            {users.length === 0 && !isLoading ? (
              <NoDataEmptyState
                entityName="usuarios"
                onCreateNew={() => navigate('/users/new')}
              />
            ) : (
              <DataTable
                data={users}
                columns={columns}
                isLoading={isLoading}
                pagination={{
                  page,
                  totalPages,
                  total,
                  limit: filters.limit || 10,
                  onPageChange: handlePageChange,
                }}
                sorting={{
                  sortBy: filters.sortBy || null,
                  sortOrder: (filters.sortOrder as 'asc' | 'desc') || 'asc',
                  onSort: handleSort,
                }}
              />
            )}
          </div>
        </CardContent>
      </Card>

      {/* Delete confirmation modal */}
      <ConfirmModal
        isOpen={!!userToDelete}
        onClose={() => setUserToDelete(null)}
        onConfirm={handleDeleteConfirm}
        title="Eliminar usuario"
        message={`¿Estás seguro de que deseas eliminar a ${userToDelete?.firstName} ${userToDelete?.lastName}? Esta acción no se puede deshacer.`}
        variant="danger"
        confirmText="Eliminar"
      />

      {/* Activate/Deactivate confirmation modal */}
      <ConfirmModal
        isOpen={!!userToToggle}
        onClose={() => setUserToToggle(null)}
        onConfirm={handleToggleConfirm}
        title={userToToggle?.action === 'activate' ? 'Activar usuario' : 'Desactivar usuario'}
        message={
          userToToggle?.action === 'activate'
            ? `¿Deseas activar a ${userToToggle?.user.firstName} ${userToToggle?.user.lastName}?`
            : `¿Deseas desactivar a ${userToToggle?.user.firstName} ${userToToggle?.user.lastName}? El usuario no podrá acceder al sistema.`
        }
        variant={userToToggle?.action === 'activate' ? 'success' : 'warning'}
        confirmText={userToToggle?.action === 'activate' ? 'Activar' : 'Desactivar'}
      />
    </div>
  );
}

export default UsersListPage;
