'use client';

import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { FiPlus, FiEdit2, FiTrash2, FiLock, FiUserX } from 'react-icons/fi';
import AdminTable from '@/components/admin/AdminTable';
import AdminModal from '@/components/admin/AdminModal';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import Badge from '@/components/ui/Badge';
import Dropdown from '@/components/ui/Dropdown';
import { getRoleLabel, getStatusLabel, formatDateShort } from '@/lib/utils';
import toast from 'react-hot-toast';
import type { TableColumn, User } from '@/types';

const mockUsers: (User & Record<string, unknown>)[] = [
  { id: '1', username: 'carlos.mendoza', email: 'carlos@email.com', role: 'admin', status: 'active', createdAt: '2023-01-15T00:00:00Z', lastLogin: '2024-03-20T10:30:00Z', maxDevices: 5, connectedDevices: 2 },
  { id: '2', username: 'ana.torres', email: 'ana@email.com', role: 'user', status: 'active', createdAt: '2023-03-20T00:00:00Z', lastLogin: '2024-03-19T15:00:00Z', maxDevices: 3, connectedDevices: 1 },
  { id: '3', username: 'miguel.reyes', email: 'miguel@email.com', role: 'user', status: 'active', createdAt: '2023-06-10T00:00:00Z', lastLogin: '2024-03-18T09:00:00Z', maxDevices: 3, connectedDevices: 3 },
  { id: '4', username: 'sofia.vega', email: 'sofia@email.com', role: 'moderator', status: 'active', createdAt: '2023-08-05T00:00:00Z', lastLogin: '2024-03-20T08:00:00Z', maxDevices: 3, connectedDevices: 1 },
  { id: '5', username: 'diego.luna', email: 'diego@email.com', role: 'user', status: 'suspended', createdAt: '2023-09-12T00:00:00Z', lastLogin: '2024-02-28T14:00:00Z', maxDevices: 3, connectedDevices: 0 },
  { id: '6', username: 'laura.sanchez', email: 'laura@email.com', role: 'user', status: 'active', createdAt: '2023-11-01T00:00:00Z', lastLogin: '2024-03-17T20:00:00Z', maxDevices: 3, connectedDevices: 2 },
  { id: '7', username: 'pedro.infante', email: 'pedro@email.com', role: 'user', status: 'expired', createdAt: '2023-04-15T00:00:00Z', expiresAt: '2024-01-15T00:00:00Z', lastLogin: '2024-01-10T12:00:00Z', maxDevices: 3, connectedDevices: 0 },
  { id: '8', username: 'carmen.lopez', email: 'carmen@email.com', role: 'user', status: 'active', createdAt: '2024-01-20T00:00:00Z', lastLogin: '2024-03-20T07:30:00Z', maxDevices: 3, connectedDevices: 1 },
  { id: '9', username: 'roberto.garcia', email: 'roberto@email.com', role: 'user', status: 'active', createdAt: '2024-02-10T00:00:00Z', lastLogin: '2024-03-19T22:00:00Z', maxDevices: 3, connectedDevices: 2 },
  { id: '10', username: 'isabella.martinez', email: 'isabella@email.com', role: 'user', status: 'active', createdAt: '2024-03-01T00:00:00Z', lastLogin: '2024-03-20T11:00:00Z', maxDevices: 3, connectedDevices: 1 },
];

const columns: TableColumn<User & Record<string, unknown>>[] = [
  { key: 'username', label: 'Usuario', sortable: true },
  { key: 'email', label: 'Email', sortable: true },
  {
    key: 'role', label: 'Rol', sortable: true,
    render: (item) => (
      <Badge variant={item.role === 'admin' ? 'accent' : item.role === 'moderator' ? 'warning' : 'neutral'} size="sm">
        {getRoleLabel(item.role)}
      </Badge>
    ),
  },
  {
    key: 'status', label: 'Estado', sortable: true,
    render: (item) => (
      <Badge variant={item.status === 'active' ? 'success' : item.status === 'suspended' ? 'warning' : 'danger'} size="sm">
        {getStatusLabel(item.status)}
      </Badge>
    ),
  },
  {
    key: 'connectedDevices', label: 'Dispositivos',
    render: (item) => <span className="text-white/50">{item.connectedDevices}/{item.maxDevices}</span>,
  },
  {
    key: 'createdAt', label: 'Creado', sortable: true,
    render: (item) => <span className="text-white/50 text-xs">{formatDateShort(item.createdAt)}</span>,
  },
];

export default function AdminUsersPage() {
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newUser, setNewUser] = useState({ username: '', email: '', password: '', role: 'user', maxDevices: '3' });

  const handleCreate = () => {
    toast.success('Usuario creado correctamente');
    setShowCreateModal(false);
    setNewUser({ username: '', email: '', password: '', role: 'user', maxDevices: '3' });
  };

  return (
    <div className="space-y-6">
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="flex items-center justify-between flex-wrap gap-4"
      >
        <div>
          <h1 className="text-2xl md:text-3xl font-bold text-white">👥 Usuarios</h1>
          <p className="text-white/40 text-sm mt-1">{mockUsers.length} usuarios registrados</p>
        </div>
        <Button
          variant="primary"
          icon={<FiPlus size={18} />}
          onClick={() => setShowCreateModal(true)}
        >
          Crear Usuario
        </Button>
      </motion.div>

      <AdminTable
        columns={columns}
        data={mockUsers}
        keyField="id"
        searchPlaceholder="Buscar usuario..."
        actions={(item) => (
          <>
            <button onClick={() => toast.success('Editando ' + item.username)} className="p-2 rounded-lg text-white/40 hover:text-accent hover:bg-accent/10 transition-all" title="Editar">
              <FiEdit2 size={15} />
            </button>
            <button onClick={() => toast.success('Contraseña reseteada')} className="p-2 rounded-lg text-white/40 hover:text-yellow-400 hover:bg-yellow-400/10 transition-all" title="Resetear contraseña">
              <FiLock size={15} />
            </button>
            <button onClick={() => toast.success('Usuario suspendido')} className="p-2 rounded-lg text-white/40 hover:text-orange-400 hover:bg-orange-400/10 transition-all" title="Suspender">
              <FiUserX size={15} />
            </button>
            <button onClick={() => toast.error('Usuario eliminado')} className="p-2 rounded-lg text-white/40 hover:text-red-400 hover:bg-red-400/10 transition-all" title="Eliminar">
              <FiTrash2 size={15} />
            </button>
          </>
        )}
      />

      {/* Create user modal */}
      <AdminModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onSubmit={handleCreate}
        title="Crear Nuevo Usuario"
        submitLabel="Crear Usuario"
      >
        <div className="space-y-4">
          <Input label="Nombre de usuario" placeholder="nombre.usuario" value={newUser.username} onChange={(e) => setNewUser({ ...newUser, username: e.target.value })} />
          <Input label="Correo electrónico" type="email" placeholder="email@ejemplo.com" value={newUser.email} onChange={(e) => setNewUser({ ...newUser, email: e.target.value })} />
          <Input label="Contraseña" type="password" placeholder="••••••••" value={newUser.password} onChange={(e) => setNewUser({ ...newUser, password: e.target.value })} />
          <Dropdown label="Rol" options={[{ value: 'user', label: 'Usuario' }, { value: 'moderator', label: 'Moderador' }, { value: 'admin', label: 'Administrador' }]} value={newUser.role} onChange={(v) => setNewUser({ ...newUser, role: v })} />
          <Input label="Máx. dispositivos" type="number" value={newUser.maxDevices} onChange={(e) => setNewUser({ ...newUser, maxDevices: e.target.value })} />
        </div>
      </AdminModal>
    </div>
  );
}
