'use client';

import { useState } from 'react';
import { Users, Plus, Search, X, Eye, Edit, Trash2, Shield, Mail, Phone, MapPin, CheckCircle, XCircle } from 'lucide-react';
import Link from 'next/link';

type UserRole = 'admin' | 'manager' | 'biker' | 'investor' | 'swapstation' | 'merchant';
type UserStatus = 'active' | 'inactive' | 'suspended';

interface User {
  id: string;
  name: string;
  email: string;
  phone: string;
  role: UserRole;
  status: UserStatus;
  avatar?: string;
  lastLogin: string;
  createdAt: string;
  linkedProfile?: {
    type: 'biker' | 'investor' | 'swapstation' | 'merchant';
    id: string;
    name: string;
  };
}

const mockUsers: User[] = [
  { id: 'USR-001', name: 'Admin User', email: 'admin@jaiben.com', phone: '+8801712345678', role: 'admin', status: 'active', lastLogin: '2024-02-16 10:30', createdAt: '2023-01-01' },
  { id: 'USR-002', name: 'Karim Manager', email: 'karim@jaiben.com', phone: '+8801812345678', role: 'manager', status: 'active', lastLogin: '2024-02-16 09:15', createdAt: '2023-06-15' },
  { id: 'USR-003', name: 'Jamal Biker', email: 'jamal@biker.com', phone: '+8801912345678', role: 'biker', status: 'active', lastLogin: '2024-02-15 18:00', createdAt: '2023-09-20', linkedProfile: { type: 'biker', id: 'BIK-001', name: 'Jamal Delivery' } },
  { id: 'USR-004', name: 'Rahim Investor', email: 'rahim@investor.com', phone: '+8801512345678', role: 'investor', status: 'active', lastLogin: '2024-02-14 12:00', createdAt: '2023-03-10', linkedProfile: { type: 'investor', id: 'INV-001', name: 'Rahim Investments' } },
  { id: 'USR-005', name: 'Swap Station Owner', email: 'swapstation@owner.com', phone: '+8801612345678', role: 'swapstation', status: 'active', lastLogin: '2024-02-15 14:30', createdAt: '2023-11-05', linkedProfile: { type: 'swapstation', id: 'SHP-001', name: 'Jaiben Swap Station' } },
  { id: 'USR-006', name: 'Merchant User', email: 'merchant@jaiben.com', phone: '+8801412345678', role: 'merchant', status: 'active', lastLogin: '2024-02-15 16:00', createdAt: '2023-08-15', linkedProfile: { type: 'merchant', id: 'MCH-001', name: 'Rahim Delivery Service' } },
];

const roleColors: Record<UserRole, string> = {
  admin: 'bg-red-100 text-red-700',
  manager: 'bg-purple-100 text-purple-700',
  biker: 'bg-blue-100 text-blue-700',
  investor: 'bg-green-100 text-green-700',
  swapstation: 'bg-amber-100 text-amber-700',
  merchant: 'bg-cyan-100 text-cyan-700'
};

const statusColors: Record<UserStatus, string> = {
  active: 'bg-green-100 text-green-700',
  inactive: 'bg-slate-100 text-slate-700',
  suspended: 'bg-red-100 text-red-700'
};

const roleLabels: Record<UserRole, string> = {
  admin: 'Admin',
  manager: 'Manager',
  biker: 'Biker',
  investor: 'Investor',
  swapstation: 'Swap Station',
  merchant: 'Merchant'
};

const statusLabels: Record<UserStatus, string> = {
  active: 'Active',
  inactive: 'Inactive',
  suspended: 'Suspended'
};

export default function UsersPage() {
  const [users, setUsers] = useState<User[]>(mockUsers);
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    role: 'biker' as UserRole,
    status: 'active' as UserStatus
  });

  const filteredUsers = users.filter(u => {
    const matchesSearch = u.name.toLowerCase().includes(search.toLowerCase()) ||
      u.email.toLowerCase().includes(search.toLowerCase()) ||
      u.phone.includes(search) ||
      u.id.toLowerCase().includes(search.toLowerCase());
    const matchesRole = roleFilter === 'all' || u.role === roleFilter;
    const matchesStatus = statusFilter === 'all' || u.status === statusFilter;
    return matchesSearch && matchesRole && matchesStatus;
  });

  const stats = {
    total: users.length,
    active: users.filter(u => u.status === 'active').length,
    admins: users.filter(u => u.role === 'admin').length,
    managers: users.filter(u => u.role === 'manager').length,
  };

  const handleSave = () => {
    if (!formData.name || !formData.email || !formData.phone) return;
    
    if (editingUser) {
      setUsers(users.map(u => u.id === editingUser.id ? { ...u, ...formData } : u));
    } else {
      const newUser: User = {
        id: `USR-${String(users.length + 1).padStart(3, '0')}`,
        ...formData,
        lastLogin: '-',
        createdAt: new Date().toISOString().split('T')[0]
      };
      setUsers([...users, newUser]);
    }
    
    setShowCreateModal(false);
    setEditingUser(null);
    setFormData({ name: '', email: '', phone: '', role: 'biker', status: 'active' });
  };

  const handleDelete = (id: string) => {
    if (confirm('Are you sure you want to delete this user?')) {
      setUsers(users.filter(u => u.id !== id));
    }
  };

  const openEdit = (user: User) => {
    setEditingUser(user);
    setFormData({
      name: user.name,
      email: user.email,
      phone: user.phone,
      role: user.role,
      status: user.status
    });
    setShowCreateModal(true);
  };

  return (
    <div className="p-4 lg:p-6">
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl lg:text-3xl font-extrabold text-slate-800">Users</h1>
          <p className="text-sm text-slate-500 mt-1">Manage system users and permissions</p>
        </div>
        <button 
          onClick={() => {
            setEditingUser(null);
            setFormData({ name: '', email: '', phone: '', role: 'biker', status: 'active' });
            setShowCreateModal(true);
          }}
          className="py-2.5 px-4 bg-accent text-white rounded-lg font-semibold text-sm hover:bg-accent-dark transition-colors flex items-center gap-2"
        >
          <Plus className="w-4 h-4" /> Add User
        </button>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-slate-800">{stats.total}</p>
          <p className="text-sm text-slate-500">Total Users</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-green-600">{stats.active}</p>
          <p className="text-sm text-slate-500">Active</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-red-600">{stats.admins}</p>
          <p className="text-sm text-slate-500">Admins</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-purple-600">{stats.managers}</p>
          <p className="text-sm text-slate-500">Managers</p>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-slate-100">
        <div className="p-4 border-b border-slate-100">
          <div className="flex flex-col lg:flex-row gap-4">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <input 
                type="text" 
                placeholder="Search users..." 
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
              />
            </div>
            <select
              value={roleFilter}
              onChange={(e) => setRoleFilter(e.target.value)}
              className="py-2 px-4 border border-slate-200 rounded-lg text-sm"
            >
              <option value="all">All Roles</option>
              <option value="admin">Admin</option>
              <option value="manager">Manager</option>
              <option value="biker">Biker</option>
              <option value="investor">Investor</option>
              <option value="swapstation">Swap Station</option>
              <option value="merchant">Merchant</option>
            </select>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="py-2 px-4 border border-slate-200 rounded-lg text-sm"
            >
              <option value="all">All Status</option>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
              <option value="suspended">Suspended</option>
            </select>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">User</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Contact</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Role</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Linked</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Status</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Last Login</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {filteredUsers.map(user => (
                <tr key={user.id} className="hover:bg-slate-50 transition-colors">
                  <td className="px-4 py-3">
                    <Link href={`/admin/users/${user.id.toLowerCase()}`} className="flex items-center gap-3 hover:text-accent">
                      <div className="w-10 h-10 rounded-full bg-accent-light flex items-center justify-center">
                        <span className="text-sm font-bold text-accent">{user.name.charAt(0).toUpperCase()}</span>
                      </div>
                      <div>
                        <p className="text-sm font-medium text-slate-700">{user.name}</p>
                        <p className="text-xs text-slate-400">{user.id}</p>
                      </div>
                    </Link>
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-sm text-slate-600">{user.email}</p>
                    <p className="text-xs text-slate-400">{user.phone}</p>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs px-2 py-1 rounded-full ${roleColors[user.role]}`}>
                      {roleLabels[user.role]}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    {user.linkedProfile ? (
                      <span className="text-xs px-2 py-1 rounded-full bg-accent-light text-accent">
                        {user.linkedProfile.type}
                      </span>
                    ) : (
                      <span className="text-xs text-slate-400">-</span>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs px-2 py-1 rounded-full ${statusColors[user.status]}`}>
                      {statusLabels[user.status]}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-sm text-slate-500">{user.lastLogin}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1">
                      <button onClick={() => openEdit(user)} className="p-2 hover:bg-slate-100 rounded-lg">
                        <Edit className="w-4 h-4 text-slate-400" />
                      </button>
                      <button onClick={() => handleDelete(user.id)} className="p-2 hover:bg-red-50 rounded-lg">
                        <Trash2 className="w-4 h-4 text-red-400" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {showCreateModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b border-slate-100 flex justify-between items-center sticky top-0 bg-white">
              <h3 className="font-semibold text-slate-800">{editingUser ? 'Edit User' : 'Add New User'}</h3>
              <button onClick={() => setShowCreateModal(false)} className="text-slate-400 hover:text-slate-600">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="text-sm text-slate-600">Full Name *</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  placeholder="Enter full name"
                />
              </div>
              <div>
                <label className="text-sm text-slate-600">Email *</label>
                <input
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  placeholder="email@example.com"
                />
              </div>
              <div>
                <label className="text-sm text-slate-600">Phone *</label>
                <input
                  type="text"
                  value={formData.phone}
                  onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  placeholder="+8801xxxxxxxxx"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-slate-600">Role</label>
                  <select
                    value={formData.role}
                    onChange={(e) => setFormData({ ...formData, role: e.target.value as UserRole })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  >
                    <option value="admin">Admin</option>
                    <option value="manager">Manager</option>
                    <option value="biker">Biker</option>
                    <option value="investor">Investor</option>
                    <option value="swapstation">Swap Station</option>
                    <option value="merchant">Merchant</option>
                  </select>
                </div>
                <div>
                  <label className="text-sm text-slate-600">Status</label>
                  <select
                    value={formData.status}
                    onChange={(e) => setFormData({ ...formData, status: e.target.value as UserStatus })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  >
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                    <option value="suspended">Suspended</option>
                  </select>
                </div>
              </div>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end gap-2 sticky bottom-0 bg-white">
              <button 
                onClick={() => setShowCreateModal(false)} 
                className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm"
              >
                Cancel
              </button>
              <button 
                onClick={handleSave}
                disabled={!formData.name || !formData.email || !formData.phone}
                className="px-4 py-2 bg-accent text-white rounded-lg text-sm disabled:opacity-50"
              >
                {editingUser ? 'Update' : 'Create'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}