'use client';

import React, { useState } from 'react';
import AppLayout from '@/components/AppLayout';
import { Plus, Search, Shield, ShieldCheck, Edit2, Trash2, UserX, UserCheck, Users, Key, Lock, X, Check, ChevronDown, ChevronUp } from 'lucide-react';
import Icon from '@/components/ui/AppIcon';
import { toast } from 'sonner';


interface AppUser {
  id: string;
  name: string;
  email: string;
  role: string;
  branch: string;
  lastLogin: string;
  status: 'active' | 'blocked' | 'pending';
  isSuperUser: boolean;
  permissions: string[];
}

const appUsers: AppUser[] = [
  { id: 'U001', name: 'Tiltai Cloud', email: 'tiltai@cloud.com', role: 'Super Admin', branch: 'All Branches', lastLogin: '2026-08-07 09:11', status: 'active', isSuperUser: true, permissions: ['all'] },
  { id: 'U002', name: 'Admin User', email: 'admin@cloudcorepos.co.ke', role: 'Admin', branch: 'All Branches', lastLogin: '2026-08-07 08:45', status: 'active', isSuperUser: false, permissions: ['dashboard', 'pos', 'products', 'inventory', 'reports', 'finance', 'users'] },
  { id: 'U003', name: 'Amara Mwangi', email: 'manager@cloudcorepos.co.ke', role: 'Manager', branch: 'Westlands', lastLogin: '2026-08-07 08:30', status: 'active', isSuperUser: false, permissions: ['dashboard', 'pos', 'products', 'inventory', 'reports'] },
  { id: 'U004', name: 'John Kariuki', email: 'cashier@cloudcorepos.co.ke', role: 'Cashier', branch: 'Westlands', lastLogin: '2026-08-06 17:20', status: 'active', isSuperUser: false, permissions: ['pos'] },
  { id: 'U005', name: 'Jane Waweru', email: 'jane.w@cloudcorepos.co.ke', role: 'Cashier', branch: 'CBD Branch', lastLogin: '2026-08-05 16:00', status: 'active', isSuperUser: false, permissions: ['pos'] },
  { id: 'U006', name: 'Samuel Odhiambo', email: 's.odhiambo@cloudcorepos.co.ke', role: 'Storekeeper', branch: 'Westlands', lastLogin: '2026-08-04 12:10', status: 'blocked', isSuperUser: false, permissions: ['inventory', 'products'] },
  { id: 'U007', name: 'Pending User', email: 'newuser@cloudcorepos.co.ke', role: 'Cashier', branch: 'Mombasa Road', lastLogin: 'Never', status: 'pending', isSuperUser: false, permissions: [] },
];

const ALL_PERMISSIONS = [
  { key: 'dashboard', label: 'Dashboard', desc: 'View sales overview and KPIs' },
  { key: 'pos', label: 'POS Terminal', desc: 'Process sales and payments' },
  { key: 'products', label: 'Products', desc: 'Manage product catalog' },
  { key: 'inventory', label: 'Inventory', desc: 'Stock levels and movements' },
  { key: 'customers', label: 'Customers', desc: 'Customer management' },
  { key: 'suppliers', label: 'Suppliers', desc: 'Supplier management' },
  { key: 'purchases', label: 'Purchases', desc: 'Purchase orders and GRN' },
  { key: 'sales', label: 'Sales', desc: 'Sales history and returns' },
  { key: 'reports', label: 'Reports', desc: 'Business reports and analytics' },
  { key: 'finance', label: 'Finance', desc: 'Expenses and cashbook' },
  { key: 'branches', label: 'Branches', desc: 'Branch management' },
  { key: 'users', label: 'Users & Roles', desc: 'User and permission management' },
  { key: 'settings', label: 'Settings', desc: 'System configuration' },
];

interface RoleData {
  name: string;
  color: string;
  permissions: string[];
  description: string;
}

const initialRoles: RoleData[] = [
  { name: 'Super Admin', color: 'badge-danger', permissions: ALL_PERMISSIONS.map((p) => p.key), description: 'Full system access, user management, all branches' },
  { name: 'Admin', color: 'badge-warning', permissions: ['dashboard', 'pos', 'products', 'inventory', 'customers', 'suppliers', 'purchases', 'sales', 'reports', 'finance', 'branches'], description: 'All modules except user deletion, all branches' },
  { name: 'Manager', color: 'badge-info', permissions: ['dashboard', 'pos', 'products', 'inventory', 'customers', 'sales', 'reports'], description: 'Dashboard, POS, Products, Inventory, Reports — assigned branch' },
  { name: 'Cashier', color: 'badge-success', permissions: ['pos'], description: 'POS Terminal only — assigned branch' },
  { name: 'Storekeeper', color: 'badge-neutral', permissions: ['products', 'inventory'], description: 'Products and Inventory — assigned branch' },
];

const statusConfig = {
  active: { label: 'Active', className: 'badge-success', icon: UserCheck },
  blocked: { label: 'Blocked', className: 'badge-danger', icon: UserX },
  pending: { label: 'Pending', className: 'badge-warning', icon: Shield },
};

interface EditPermissionsModalProps {
  role: RoleData;
  onSave: (updatedPermissions: string[]) => void;
  onClose: () => void;
}

function EditPermissionsModal({ role, onSave, onClose }: EditPermissionsModalProps) {
  const [selected, setSelected] = useState<string[]>(role.permissions);

  const toggle = (key: string) => {
    setSelected((prev) =>
      prev.includes(key) ? prev.filter((p) => p !== key) : [...prev, key]
    );
  };

  const selectAll = () => setSelected(ALL_PERMISSIONS.map((p) => p.key));
  const clearAll = () => setSelected([]);

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-card rounded-xl shadow-xl w-full max-w-lg p-6 fade-in flex flex-col max-h-[90vh]">
        <div className="flex items-center justify-between mb-4 flex-shrink-0">
          <div>
            <h2 className="text-base font-700 text-foreground">Edit Permissions</h2>
            <p className="text-xs text-muted-foreground mt-0.5">Role: <span className="font-600 text-foreground">{role.name}</span></p>
          </div>
          <button onClick={onClose} className="p-1.5 rounded hover:bg-muted text-muted-foreground"><X size={16} /></button>
        </div>

        <div className="flex gap-2 mb-4 flex-shrink-0">
          <button onClick={selectAll} className="px-3 h-7 text-xs font-600 rounded border border-border text-muted-foreground hover:bg-muted transition-colors">Select All</button>
          <button onClick={clearAll} className="px-3 h-7 text-xs font-600 rounded border border-border text-muted-foreground hover:bg-muted transition-colors">Clear All</button>
          <span className="ml-auto text-xs text-muted-foreground self-center">{selected.length} / {ALL_PERMISSIONS.length} selected</span>
        </div>

        <div className="flex-1 overflow-y-auto scrollbar-thin space-y-1 mb-4">
          {ALL_PERMISSIONS.map((perm) => {
            const isChecked = selected.includes(perm.key);
            return (
              <label
                key={perm.key}
                className={`flex items-center gap-3 px-3 py-2.5 rounded-lg cursor-pointer transition-colors ${isChecked ? 'bg-primary/5 border border-primary/20' : 'border border-transparent hover:bg-muted'}`}
              >
                <div className={`w-5 h-5 rounded flex items-center justify-center flex-shrink-0 border-2 transition-all ${isChecked ? 'bg-primary border-primary' : 'border-border bg-background'}`}>
                  {isChecked && <Check size={12} className="text-white" />}
                </div>
                <input type="checkbox" className="sr-only" checked={isChecked} onChange={() => toggle(perm.key)} />
                <div className="flex-1 min-w-0">
                  <p className={`text-sm font-600 ${isChecked ? 'text-primary' : 'text-foreground'}`}>{perm.label}</p>
                  <p className="text-xs text-muted-foreground">{perm.desc}</p>
                </div>
              </label>
            );
          })}
        </div>

        <div className="flex gap-3 flex-shrink-0 border-t border-border pt-4">
          <button onClick={onClose} className="flex-1 h-9 rounded-md border border-border text-sm text-muted-foreground hover:bg-muted transition-colors">Cancel</button>
          <button
            onClick={() => { onSave(selected); toast.success(`Permissions updated for ${role.name}`); onClose(); }}
            className="flex-1 h-9 rounded-md btn-primary text-sm font-600 text-white"
          >
            Save Permissions
          </button>
        </div>
      </div>
    </div>
  );
}

export default function UsersPage() {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState<'users' | 'roles'>('users');
  const [showModal, setShowModal] = useState(false);
  const [selectedUser, setSelectedUser] = useState<AppUser | null>(null);
  const [roles, setRoles] = useState<RoleData[]>(initialRoles);
  const [editingRole, setEditingRole] = useState<RoleData | null>(null);
  const [expandedRole, setExpandedRole] = useState<string | null>(null);

  const filtered = appUsers.filter((u) =>
    u.name.toLowerCase().includes(search.toLowerCase()) ||
    u.email.toLowerCase().includes(search.toLowerCase()) ||
    u.role.toLowerCase().includes(search.toLowerCase())
  );

  const handleBlock = (user: AppUser) => {
    setSelectedUser(user);
  };

  const handleSavePermissions = (roleName: string, updatedPermissions: string[]) => {
    setRoles((prev) =>
      prev.map((r) => r.name === roleName ? { ...r, permissions: updatedPermissions } : r)
    );
  };

  return (
    <AppLayout>
      <div className="p-6 xl:p-8 max-w-screen-2xl mx-auto space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-xl font-700 text-foreground">Users & Roles</h1>
            <p className="text-sm text-muted-foreground mt-0.5">Manage system users, roles and access permissions</p>
          </div>
          <button onClick={() => setShowModal(true)} className="btn-primary flex items-center gap-2 px-4 py-2 rounded-md text-sm font-600 text-white">
            <Plus size={16} />
            Add User
          </button>
        </div>

        {/* Super User Banner */}
        <div className="bg-primary/5 border border-primary/20 rounded-xl p-4 flex items-start gap-3">
          <div className="w-9 h-9 rounded-full bg-primary flex items-center justify-center flex-shrink-0">
            <ShieldCheck size={18} className="text-white" />
          </div>
          <div>
            <p className="text-sm font-700 text-primary">Super User Account Active</p>
            <p className="text-xs text-muted-foreground mt-0.5">
              <span className="font-600 text-foreground">tiltai@cloud.com</span> has full system access including user creation, deletion, and blocking. This account cannot be deleted or blocked.
            </p>
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            { label: 'Total Users', value: appUsers.length, icon: Users, color: 'text-primary', bg: 'bg-primary/10' },
            { label: 'Active Users', value: appUsers.filter((u) => u.status === 'active').length, icon: UserCheck, color: 'text-success', bg: 'bg-success-bg' },
            { label: 'Blocked Users', value: appUsers.filter((u) => u.status === 'blocked').length, icon: UserX, color: 'text-danger', bg: 'bg-danger-bg' },
            { label: 'Roles Defined', value: roles.length, icon: Key, color: 'text-info', bg: 'bg-info-bg' },
          ].map((stat) => {
            const Icon = stat.icon;
            return (
              <div key={stat.label} className="card-elevated rounded-xl p-4 flex items-center gap-3">
                <div className={`w-10 h-10 rounded-lg ${stat.bg} flex items-center justify-center flex-shrink-0`}>
                  <Icon size={18} className={stat.color} />
                </div>
                <div>
                  <p className="text-2xl font-700 text-foreground">{stat.value}</p>
                  <p className="text-xs text-muted-foreground">{stat.label}</p>
                </div>
              </div>
            );
          })}
        </div>

        {/* Tabs */}
        <div className="flex gap-1 bg-muted rounded-lg p-1 w-fit">
          {(['users', 'roles'] as const).map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`px-4 py-1.5 rounded-md text-sm font-600 transition-all ${activeTab === tab ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}
            >
              {tab === 'users' ? 'System Users' : 'Roles & Permissions'}
            </button>
          ))}
        </div>

        {activeTab === 'users' && (
          <>
            {/* Search */}
            <div className="card-elevated rounded-xl p-4">
              <div className="flex items-center gap-2 bg-muted border border-border rounded-md px-3 h-9 max-w-sm">
                <Search size={14} className="text-muted-foreground" />
                <input
                  type="text"
                  placeholder="Search users…"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none w-full"
                />
              </div>
            </div>

            {/* Users Table */}
            <div className="card-elevated rounded-xl overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="bg-muted/50 border-b border-border">
                      <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">User</th>
                      <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Role</th>
                      <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Branch</th>
                      <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Last Login</th>
                      <th className="text-center px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Status</th>
                      <th className="text-center px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {filtered.map((user) => {
                      const sc = statusConfig[user.status];
                      const StatusIcon = sc.icon;
                      return (
                        <tr key={user.id} className="hover:bg-muted/30 transition-colors">
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-2.5">
                              <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${user.isSuperUser ? 'bg-primary' : 'bg-primary/10'}`}>
                                {user.isSuperUser ? <ShieldCheck size={14} className="text-white" /> : <span className="text-xs font-700 text-primary">{user.name.split(' ').map((n) => n[0]).join('')}</span>}
                              </div>
                              <div>
                                <div className="flex items-center gap-1.5">
                                  <p className="font-600 text-foreground">{user.name}</p>
                                  {user.isSuperUser && <span className="text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary font-600">Super</span>}
                                </div>
                                <p className="text-xs text-muted-foreground">{user.email}</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-4 py-3 text-sm text-foreground">{user.role}</td>
                          <td className="px-4 py-3 text-sm text-muted-foreground">{user.branch}</td>
                          <td className="px-4 py-3 text-xs font-mono text-muted-foreground">{user.lastLogin}</td>
                          <td className="px-4 py-3 text-center">
                            <span className={`text-xs px-2 py-0.5 rounded-full font-600 ${sc.className}`}>{sc.label}</span>
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center justify-center gap-1">
                              <button className="p-1.5 rounded hover:bg-warning-bg text-muted-foreground hover:text-warning transition-colors" title="Edit"><Edit2 size={14} /></button>
                              {!user.isSuperUser && (
                                <>
                                  <button
                                    onClick={() => handleBlock(user)}
                                    className={`p-1.5 rounded transition-colors ${user.status === 'blocked' ? 'hover:bg-success-bg text-muted-foreground hover:text-success' : 'hover:bg-warning-bg text-muted-foreground hover:text-warning'}`}
                                    title={user.status === 'blocked' ? 'Unblock' : 'Block'}
                                  >
                                    {user.status === 'blocked' ? <UserCheck size={14} /> : <UserX size={14} />}
                                  </button>
                                  <button className="p-1.5 rounded hover:bg-danger-bg text-muted-foreground hover:text-danger transition-colors" title="Delete"><Trash2 size={14} /></button>
                                </>
                              )}
                              {user.isSuperUser && (
                                <span className="text-xs text-muted-foreground px-2">Protected</span>
                              )}
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          </>
        )}

        {activeTab === 'roles' && (
          <div className="space-y-4">
            {roles.map((role) => {
              const isExpanded = expandedRole === role.name;
              return (
                <div key={role.name} className="card-elevated rounded-xl overflow-hidden">
                  <div className="flex items-center justify-between p-5">
                    <div className="flex items-center gap-3">
                      <Lock size={16} className="text-primary" />
                      <div>
                        <div className="flex items-center gap-2">
                          <h3 className="font-700 text-foreground">{role.name}</h3>
                          <span className={`text-xs px-2 py-0.5 rounded-full font-600 ${role.color}`}>{role.name}</span>
                        </div>
                        <p className="text-xs text-muted-foreground mt-0.5">{role.description}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-xs text-muted-foreground">{role.permissions.length} permissions</span>
                      <button
                        onClick={() => setEditingRole(role)}
                        className="flex items-center gap-1.5 h-7 px-3 text-xs font-600 rounded border border-primary/30 bg-primary/5 text-primary hover:bg-primary/10 transition-colors"
                      >
                        <Edit2 size={12} />
                        Edit Permissions
                      </button>
                      <button
                        onClick={() => setExpandedRole(isExpanded ? null : role.name)}
                        className="p-1.5 rounded hover:bg-muted text-muted-foreground transition-colors"
                      >
                        {isExpanded ? <ChevronUp size={15} /> : <ChevronDown size={15} />}
                      </button>
                    </div>
                  </div>

                  {isExpanded && (
                    <div className="border-t border-border px-5 py-4">
                      <p className="text-xs font-600 text-muted-foreground uppercase tracking-wide mb-3">Assigned Permissions</p>
                      <div className="flex flex-wrap gap-2">
                        {ALL_PERMISSIONS.map((perm) => {
                          const hasPermission = role.permissions.includes(perm.key);
                          return (
                            <span
                              key={perm.key}
                              className={`text-xs px-2.5 py-1 rounded-full font-600 ${hasPermission ? 'bg-primary/10 text-primary border border-primary/20' : 'bg-muted text-muted-foreground border border-border line-through opacity-50'}`}
                            >
                              {perm.label}
                            </span>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}

        {/* Add User Modal */}
        {showModal && (
          <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
            <div className="bg-card rounded-xl shadow-xl w-full max-w-lg p-6 fade-in">
              <div className="flex items-center justify-between mb-5">
                <h2 className="text-base font-700 text-foreground">Add New User</h2>
                <button onClick={() => setShowModal(false)} className="p-1.5 rounded hover:bg-muted text-muted-foreground">✕</button>
              </div>
              <div className="grid grid-cols-2 gap-4">
                {[
                  { label: 'Full Name', placeholder: 'John Doe', span: 2 },
                  { label: 'Email Address', placeholder: 'john@cloudcorepos.co.ke', span: 2 },
                  { label: 'Password', placeholder: 'Min. 8 characters' },
                  { label: 'Confirm Password', placeholder: 'Repeat password' },
                  { label: 'Role', placeholder: 'Select role…' },
                  { label: 'Branch', placeholder: 'Select branch…' },
                  { label: 'Phone Number', placeholder: '+254 7XX XXX XXX' },
                ].map((f) => (
                  <div key={f.label} className={f.span === 2 ? 'col-span-2' : ''}>
                    <label className="block text-xs font-600 text-foreground mb-1">{f.label}</label>
                    <input
                      type={f.label.toLowerCase().includes('password') ? 'password' : 'text'}
                      placeholder={f.placeholder}
                      className="w-full h-9 px-3 text-sm bg-background border border-border rounded-md outline-none focus:border-primary text-foreground placeholder:text-muted-foreground"
                    />
                  </div>
                ))}
              </div>
              <div className="flex gap-3 mt-6">
                <button onClick={() => setShowModal(false)} className="flex-1 h-9 rounded-md border border-border text-sm text-muted-foreground hover:bg-muted transition-colors">Cancel</button>
                <button onClick={() => setShowModal(false)} className="flex-1 h-9 rounded-md btn-primary text-sm font-600 text-white">Create User</button>
              </div>
            </div>
          </div>
        )}

        {/* Edit Permissions Modal */}
        {editingRole && (
          <EditPermissionsModal
            role={editingRole}
            onSave={(perms) => handleSavePermissions(editingRole.name, perms)}
            onClose={() => setEditingRole(null)}
          />
        )}
      </div>
    </AppLayout>
  );
}
