'use client'

import { useState, useRef } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import axios from 'axios'
import { toast } from 'sonner'
import { fmtDate, fmtDateTime, cn } from '@/lib/utils'
import { Shield, Plus, Edit, Lock, Unlock, User, Building2, Check, Upload, Download } from 'lucide-react'
import { Badge, Button, Card, CardHeader, CardTitle, CardContent, Modal, Input, Select, FormGrid, PageHeader, Tabs, StatusBadge } from '@/components/ui/components'

export default function UsersPage() {
  const qc = useQueryClient()
  const fileRef = useRef<HTMLInputElement>(null)
  const [uploadingId, setUploadingId] = useState<string | null>(null)
  const [uploadTargetId, setUploadTargetId] = useState<string | null>(null)
  const [tab, setTab] = useState('users')
  const [newUserModal, setNewUserModal] = useState(false)
  const [form, setForm] = useState<{ fullName:string; email:string; phone:string; roleId:string; branchIds:string[]; password:string; employeeNumber:string }>({ fullName:'', email:'', phone:'', roleId:'', branchIds:[], password:'', employeeNumber:'' })

  const { data: usersData } = useQuery({ queryKey:['users'], queryFn: () => axios.get('/api/admin/users').then(r=>r.data.data) })
  const { data: rolesData  } = useQuery({ queryKey:['roles'],  queryFn: () => axios.get('/api/admin/users?sub=roles').then(r=>r.data.data) })
  const { data: branchesData, isLoading: branchesLoading, isError: branchesError } = useQuery({
    queryKey: ['users-branches'],
    queryFn: () => axios.get('/api/branches').then(r => r.data.data),
    staleTime: 30_000,
  })

  const branches = branchesData ?? []

  const createUser = useMutation({
    mutationFn: (payload: any) => axios.post('/api/admin/users', payload),
    onSuccess: () => { toast.success('User created'); qc.invalidateQueries({queryKey:['users']}); setNewUserModal(false) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const toggleStatus = useMutation({
    mutationFn: ({ id, status }: any) => axios.patch(`/api/admin/users/${id}`, { status }),
    onSuccess: () => { toast.success('User status updated'); qc.invalidateQueries({queryKey:['users']}) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const uploadPhoto = useMutation({
    mutationFn: async ({ id, file }: { id: string; file: File }) => {
      const fd = new FormData()
      fd.append('file', file)
      const { data } = await axios.post('/api/upload/photo', fd)
      await axios.patch(`/api/admin/users/${id}`, { profilePhotoUrl: data.data.url })
    },
    onSuccess: () => { qc.invalidateQueries({queryKey:['users']}); toast.success('Photo updated') },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Upload failed'),
  })

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    const id = uploadTargetId
    if (!file || !id) return
    setUploadTargetId(null)
    setUploadingId(id)
    uploadPhoto.mutate({ id, file }, { onSettled: () => { setUploadingId(null); if (fileRef.current) fileRef.current.value = '' } })
  }

  const users = usersData ?? []
  const roles  = rolesData ?? []

  // Role editing state
  const [editRoleModal, setEditRoleModal] = useState(false)
  const [editRoleId, setEditRoleId] = useState<string | null>(null)
  const [editRoleForm, setEditRoleForm] = useState<{ name: string; description: string; permissionIds: string[] }>({ name: '', description: '', permissionIds: [] })

  const { data: permissionsData } = useQuery({
    queryKey: ['permissions'],
    queryFn: () => axios.get('/api/admin/roles?sub=permissions').then(r => r.data.data),
    enabled: tab === 'roles',
  })

  const updateRole = useMutation({
    mutationFn: ({ id, ...payload }: any) => axios.patch(`/api/admin/roles/${id}`, payload),
    onSuccess: () => {
      toast.success('Role updated')
      qc.invalidateQueries({ queryKey: ['roles'] })
      setEditRoleModal(false)
      setEditRoleId(null)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const openRoleEditor = async (role: any) => {
    try {
      const { data } = await axios.get(`/api/admin/roles/${role.id}`)
      const d = data.data
      setEditRoleId(role.id)
      setEditRoleForm({
        name: d.name,
        description: d.description ?? '',
        permissionIds: d.permissions?.map((p: any) => p.permissionId) ?? [],
      })
      setEditRoleModal(true)
    } catch {
      toast.error('Failed to load role details')
    }
  }

  const MODULES = ['members','loans','savings','accounting','collections','payroll','reports','configuration','admin','groups','suppliers','assets']
  const ACTIONS = ['view','create','edit','delete','approve','export','import','configure']

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <PageHeader title="User Management" description={`${users.length} users`} icon={<Shield className="w-6 h-6"/>}
        actions={<Button size="sm" icon={<Plus className="w-4 h-4"/>} onClick={() => setNewUserModal(true)}>Add User</Button>}
      />

      <Tabs tabs={[{id:'users',label:'Users'},{id:'roles',label:'Roles'},{id:'permissions',label:'Permissions Matrix'}]} active={tab} onChange={setTab}/>

      {tab === 'users' && (
        <Card>
          <div className="overflow-x-auto">
            <table className="table-lms w-full">
              <thead><tr><th>User</th><th>Role</th><th>Branch</th><th>Status</th><th>Last Login</th><th>2FA</th><th>Actions</th></tr></thead>
              <tbody>
                {users.map((u: any) => (
                  <tr key={u.id}>
                    <td>
                      <div className="flex items-center gap-2.5">
                        <div className="relative shrink-0">
                          {u.profilePhotoUrl ? (
                            <img src={u.profilePhotoUrl} alt="" className="w-8 h-8 rounded-full object-cover" />
                          ) : (
                            <div className="w-8 h-8 rounded-full bg-primary/10 text-primary text-xs font-bold flex items-center justify-center">
                              {u.fullName?.split(' ').map((n: string)=>n[0]).join('').slice(0,2)}
                            </div>
                          )}
                          <button type="button" className="absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 rounded-full bg-primary text-white flex items-center justify-center"
                            title="Upload photo" disabled={uploadingId === u.id}
                            onClick={() => { setUploadTargetId(u.id); fileRef.current?.click() }}>
                            <Upload className="w-2 h-2" />
                          </button>
                        </div>
                        <div>
                          <p className="font-medium text-sm">{u.fullName}</p>
                          <p className="text-xs text-muted-foreground">{u.email}</p>
                          {u.employeeNumber && <p className="text-[10px] text-muted-foreground/70">{u.employeeNumber}</p>}
                        </div>
                      </div>
                    </td>
                    <td>
                      {u.userRoles?.map((ur: any) => (
                        <Badge key={ur.id} variant="info" className="mr-1">{ur.role?.name}</Badge>
                      ))}
                    </td>
                    <td className="text-sm text-muted-foreground">
                      {u.branchAssignments?.length
                        ? u.branchAssignments.map((ba: any) => ba.branch?.name).filter(Boolean).join(', ')
                        : u.primaryBranchName ?? '—'}
                    </td>
                    <td><Badge variant={u.status==='ACTIVE'?'success':u.status==='SUSPENDED'?'warning':'danger'}>{u.status}</Badge></td>
                    <td className="text-xs text-muted-foreground">{u.lastLoginAt ? fmtDateTime(u.lastLoginAt) : 'Never'}</td>
                    <td>{u.twoFactorEnabled ? <Badge variant="success">ON</Badge> : <Badge variant="default">OFF</Badge>}</td>
                    <td>
                      <div className="flex items-center gap-1">
                        <Button size="xs" variant="ghost" icon={<Download className="w-3.5 h-3.5"/>} title="Download ID Card"
                          onClick={() => window.open(`/api/admin/users/${u.id}/card`, '_blank')}/>
                        <Button size="xs" variant="ghost" icon={<Edit className="w-3.5 h-3.5"/>} title="Edit user (coming soon)" onClick={() => toast.info(`Edit user: ${u.fullName} — use the Status toggle for now`)}/>
                        {u.status === 'ACTIVE'
                          ? <Button size="xs" variant="ghost" icon={<Lock className="w-3.5 h-3.5"/>} onClick={() => toggleStatus.mutate({id:u.id,status:'SUSPENDED'})}/>
                          : <Button size="xs" variant="ghost" icon={<Unlock className="w-3.5 h-3.5"/>} onClick={() => toggleStatus.mutate({id:u.id,status:'ACTIVE'})}/>
                        }
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {tab === 'roles' && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {roles.map((r: any) => (
            <Card key={r.id}>
              <CardContent className="p-4">
                <div className="flex items-start justify-between mb-2">
                  <div>
                    <h3 className="font-semibold text-sm">{r.name}</h3>
                    <p className="text-xs text-muted-foreground">{r.description}</p>
                  </div>
                  {r.isSystemRole && <Badge variant="purple">System</Badge>}
                </div>
                <p className="text-xs text-muted-foreground mt-2">{r._count?.userRoles ?? 0} users · {r._count?.permissions ?? 0} permissions</p>
                <div className="flex gap-2 mt-3">
                  <Button variant="outline" size="xs" onClick={() => openRoleEditor(r)}>Edit</Button>
                  {!r.isSystemRole && (
                    <Button variant="ghost" size="xs" className="text-destructive"
                      onClick={async () => {
                        if (!confirm(`Delete role "${r.name}"?`)) return
                        try { await axios.delete(`/api/admin/roles/${r.id}`); toast.success('Role deleted'); qc.invalidateQueries({queryKey:['roles']}) }
                        catch (e: any) { toast.error(e.response?.data?.error ?? 'Failed') }
                      }}>Delete</Button>
                  )}
                </div>
              </CardContent>
            </Card>
          ))}
          <Card className="border-dashed">
            <CardContent className="p-4 flex items-center justify-center h-full min-h-[120px]">
              <Button variant="ghost" icon={<Plus className="w-4 h-4"/>} onClick={() => toast.info("Role management coming soon — contact system administrator")}>Create New Role</Button>
            </CardContent>
          </Card>
        </div>
      )}

      {tab === 'permissions' && (
        <Card>
          <CardContent className="p-0 overflow-x-auto">
            <table className="w-full text-xs border-collapse">
              <thead>
                <tr>
                  <th className="border p-2 bg-muted text-left sticky left-0 bg-card z-10 min-w-[140px]">Module / Action</th>
                  {ACTIONS.map(a => <th key={a} className="border p-2 bg-muted capitalize whitespace-nowrap">{a}</th>)}
                </tr>
              </thead>
              <tbody>
                {MODULES.map(mod => (
                  <tr key={mod}>
                    <td className="border p-2 font-medium capitalize sticky left-0 bg-card">{mod}</td>
                    {ACTIONS.map(act => (
                      <td key={act} className="border p-1.5 text-center">
                        <div className="flex items-center justify-center">
                          <div className="w-4 h-4 rounded bg-green-100 text-green-700 flex items-center justify-center text-xs">✓</div>
                        </div>
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </CardContent>
        </Card>
      )}

      {/* Hidden file input for photo upload */}
      <input ref={fileRef} type="file" accept="image/jpeg,image/png" className="hidden"
        onChange={handleFileSelect}
      />

      {/* Edit role modal */}
      <Modal open={editRoleModal} onClose={() => { setEditRoleModal(false); setEditRoleId(null) }} title={editRoleForm.name ? `Edit Role: ${editRoleForm.name}` : 'Edit Role'}
        footer={<><Button variant="outline" size="sm" onClick={() => { setEditRoleModal(false); setEditRoleId(null) }}>Cancel</Button><Button size="sm" loading={updateRole.isPending} onClick={() => updateRole.mutate({ id: editRoleId, name: editRoleForm.name, description: editRoleForm.description || null, permissionIds: editRoleForm.permissionIds })}>Save</Button></>}
      >
        <div className="space-y-4 max-h-[70vh] overflow-y-auto">
          <FormGrid>
            <Input label="Role Name" required value={editRoleForm.name} onChange={e => setEditRoleForm(f => ({ ...f, name: e.target.value }))} />
            <Input label="Description" value={editRoleForm.description} onChange={e => setEditRoleForm(f => ({ ...f, description: e.target.value }))} />
          </FormGrid>
          <div>
            <label className="block text-sm font-medium mb-2">Permissions</label>
            {permissionsData && Object.entries(permissionsData).map(([module, perms]: [string, any]) => (
              <div key={module} className="mb-3">
                <p className="text-xs font-semibold uppercase text-muted-foreground mb-1.5">{module}</p>
                <div className="flex flex-wrap gap-1.5">
                  {perms.map((p: any) => {
                    const checked = editRoleForm.permissionIds.includes(p.id)
                    return (
                      <label key={p.id}
                        className={`px-2 py-1 rounded text-xs border cursor-pointer transition-colors ${checked ? 'bg-primary/10 border-primary text-primary' : 'hover:bg-accent border-border'}`}>
                        <input type="checkbox" className="hidden" checked={checked}
                          onChange={() => setEditRoleForm(f => ({
                            ...f,
                            permissionIds: checked ? f.permissionIds.filter(id => id !== p.id) : [...f.permissionIds, p.id],
                          }))}
                        />
                        {p.displayName ?? p.action}
                      </label>
                    )
                  })}
                </div>
              </div>
            ))}
            {!permissionsData && <p className="text-sm text-muted-foreground">Loading permissions...</p>}
          </div>
        </div>
      </Modal>

      {/* New user modal */}
      <Modal open={newUserModal} onClose={() => setNewUserModal(false)} title="Create New User"
        footer={<><Button variant="outline" size="sm" onClick={() => setNewUserModal(false)}>Cancel</Button><Button size="sm" loading={createUser.isPending} onClick={() => createUser.mutate(form)}>Create User</Button></>}
      >
        <div className="space-y-4">
          <FormGrid>
            <Input label="Full Name" required value={form.fullName} onChange={e => setForm(f=>({...f,fullName:e.target.value}))} placeholder="Jane Wanjiku Mwangi"/>
            <Input label="Email Address" required type="email" value={form.email} onChange={e => setForm(f=>({...f,email:e.target.value}))} placeholder="jane@finserve.co.ke"/>
          </FormGrid>
          <FormGrid>
            <Input label="Phone Number" value={form.phone} onChange={e => setForm(f=>({...f,phone:e.target.value}))} placeholder="0712345678"/>
            <Input label="Employee Number" value={form.employeeNumber} onChange={e => setForm(f=>({...f,employeeNumber:e.target.value}))} placeholder="EMP-0001" hint="Leave blank to auto-generate"/>
          </FormGrid>
          <Select label="Role" required value={form.roleId} onChange={e => setForm(f=>({...f,roleId:e.target.value}))}
            placeholder="Select role..."
            options={roles.map((r: any) => ({ value: r.id, label: r.name }))}
          />
          <div>
            <label className="block text-sm font-medium mb-2">Branch Assignments</label>
            {branchesLoading ? (
              <p className="text-sm text-muted-foreground">Loading branches...</p>
            ) : branchesError ? (
              <p className="text-sm text-destructive">Failed to load branches. Check permissions.</p>
            ) : branches.length === 0 ? (
              <p className="text-sm text-muted-foreground">No branches available. Create one in Configuration first.</p>
            ) : (
              <div className="grid grid-cols-2 gap-2">
                {branches.map((b: any) => {
                  const selected = form.branchIds.includes(b.id)
                  return (
                    <label key={b.id} className={`flex items-center gap-2 p-2 border rounded-md cursor-pointer text-sm transition-colors ${selected ? 'border-primary bg-primary/5' : 'hover:bg-accent'}`}>
                      <input type="checkbox" checked={selected} onChange={() => {
                        setForm(f => ({
                          ...f,
                          branchIds: selected ? f.branchIds.filter(id => id !== b.id) : [...f.branchIds, b.id],
                        }))
                      }} className="rounded" />
                      <Building2 className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
                      <span>{b.name}</span>
                    </label>
                  )
                })}
              </div>
            )}
          </div>
          <Input label="Temporary Password" required type="password" value={form.password} onChange={e => setForm(f=>({...f,password:e.target.value}))} placeholder="Min 8 chars" hint="User will be asked to change on first login"/>
        </div>
      </Modal>
    </div>
  )
}
