import { useState, useEffect, useCallback } from 'react'
import { Plus, Pencil, UserX, Shield, User as UserIcon } from 'lucide-react'
import { admin, type AdminUser } from '../../services/api'

export function UserManagement() {
  const [users, setUsers] = useState<AdminUser[]>([])
  const [loading, setLoading] = useState(true)
  const [showCreate, setShowCreate] = useState(false)
  const [editingUser, setEditingUser] = useState<AdminUser | null>(null)
  const [error, setError] = useState<string | null>(null)

  const fetchUsers = useCallback(async () => {
    try {
      const data = await admin.listUsers()
      setUsers(data.users)
    } catch {
      setError('Failed to load users.')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchUsers()
  }, [fetchUsers])

  if (loading) {
    return <div className="p-4 text-sm text-text-muted">Loading users&hellip;</div>
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-text">Users</h3>
        <button
          onClick={() => setShowCreate(true)}
          className="flex items-center gap-1 rounded bg-accent px-2 py-1 text-xs text-white hover:bg-accent/80"
        >
          <Plus className="h-3 w-3" />
          Add User
        </button>
      </div>

      {error && (
        <div className="rounded bg-red-900/30 px-3 py-2 text-xs text-red-300">
          {error}
        </div>
      )}

      <table className="w-full text-xs">
        <thead>
          <tr className="border-b border-border text-left text-text-muted">
            <th className="pb-1 pr-4">Username</th>
            <th className="pb-1 pr-4">Role</th>
            <th className="pb-1 pr-4">Photos</th>
            <th className="pb-1 pr-4">Status</th>
            <th className="pb-1">Actions</th>
          </tr>
        </thead>
        <tbody>
          {users.map((u) => (
            <tr key={u.id} className="border-b border-border/50">
              <td className="py-1.5 pr-4">
                <div className="flex items-center gap-1.5">
                  {u.role === 'admin' ? (
                    <Shield className="h-3 w-3 text-accent" />
                  ) : (
                    <UserIcon className="h-3 w-3 text-text-muted" />
                  )}
                  <span className="text-text">{u.username}</span>
                </div>
              </td>
              <td className="py-1.5 pr-4 text-text-muted">{u.role}</td>
              <td className="py-1.5 pr-4 text-text-muted">
                {u.photo_count.toLocaleString()}
              </td>
              <td className="py-1.5 pr-4">
                <span
                  className={
                    u.is_active
                      ? 'text-green-400'
                      : 'text-red-400'
                  }
                >
                  {u.is_active ? 'Active' : 'Inactive'}
                </span>
              </td>
              <td className="py-1.5">
                <div className="flex gap-1">
                  <button
                    onClick={() => setEditingUser(u)}
                    className="rounded p-1 text-text-muted hover:bg-bg hover:text-text"
                    title="Edit user"
                  >
                    <Pencil className="h-3 w-3" />
                  </button>
                  {u.is_active && (
                    <button
                      onClick={async () => {
                        if (!confirm(`Deactivate user "${u.username}"? Their photos will be preserved.`)) return
                        try {
                          await admin.deleteUser(u.id)
                          fetchUsers()
                        } catch (err: any) {
                          setError(err.response?.data?.detail ?? 'Failed to deactivate user.')
                        }
                      }}
                      className="rounded p-1 text-text-muted hover:bg-bg hover:text-red-400"
                      title="Deactivate user"
                    >
                      <UserX className="h-3 w-3" />
                    </button>
                  )}
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      {showCreate && (
        <CreateUserModal
          onClose={() => setShowCreate(false)}
          onCreated={() => {
            setShowCreate(false)
            fetchUsers()
          }}
        />
      )}

      {editingUser && (
        <EditUserModal
          user={editingUser}
          onClose={() => setEditingUser(null)}
          onSaved={() => {
            setEditingUser(null)
            fetchUsers()
          }}
        />
      )}
    </div>
  )
}

// ── Create User Modal ──────────────────────────────────────────────────

function CreateUserModal({
  onClose,
  onCreated,
}: {
  onClose: () => void
  onCreated: () => void
}) {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [role, setRole] = useState<'user' | 'admin'>('user')
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  const handleSubmit = async () => {
    setError(null)
    setLoading(true)
    try {
      await admin.createUser({ username: username.trim(), password, role })
      onCreated()
    } catch (err: any) {
      setError(err.response?.data?.detail ?? 'Failed to create user.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <ModalOverlay onClose={onClose} title="Add User">
      {error && (
        <div className="rounded bg-red-900/30 px-3 py-2 text-xs text-red-300">
          {error}
        </div>
      )}
      <div className="space-y-3">
        <Field label="Username">
          <input
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            className="w-full rounded border border-border bg-bg px-2 py-1 text-xs text-text outline-none focus:border-accent"
            autoFocus
          />
        </Field>
        <Field label="Password">
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full rounded border border-border bg-bg px-2 py-1 text-xs text-text outline-none focus:border-accent"
          />
        </Field>
        <Field label="Role">
          <select
            value={role}
            onChange={(e) => setRole(e.target.value as 'user' | 'admin')}
            className="rounded border border-border bg-bg px-2 py-1 text-xs text-text outline-none focus:border-accent"
          >
            <option value="user">User</option>
            <option value="admin">Admin</option>
          </select>
        </Field>
      </div>
      <div className="mt-4 flex justify-end gap-2">
        <button
          onClick={onClose}
          className="rounded border border-border px-3 py-1 text-xs text-text hover:bg-bg"
        >
          Cancel
        </button>
        <button
          onClick={handleSubmit}
          disabled={loading}
          className="rounded bg-accent px-3 py-1 text-xs text-white hover:bg-accent/80 disabled:opacity-50"
        >
          {loading ? 'Creating\u2026' : 'Create'}
        </button>
      </div>
    </ModalOverlay>
  )
}

// ── Edit User Modal ────────────────────────────────────────────────────

function EditUserModal({
  user,
  onClose,
  onSaved,
}: {
  user: AdminUser
  onClose: () => void
  onSaved: () => void
}) {
  const [role, setRole] = useState(user.role)
  const [newPassword, setNewPassword] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  const handleSubmit = async () => {
    setError(null)
    setLoading(true)
    try {
      const data: { role?: string; new_password?: string } = {}
      if (role !== user.role) data.role = role
      if (newPassword) data.new_password = newPassword
      if (Object.keys(data).length > 0) {
        await admin.updateUser(user.id, data)
      }
      onSaved()
    } catch (err: any) {
      setError(err.response?.data?.detail ?? 'Failed to update user.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <ModalOverlay onClose={onClose} title={`Edit: ${user.username}`}>
      {error && (
        <div className="rounded bg-red-900/30 px-3 py-2 text-xs text-red-300">
          {error}
        </div>
      )}
      <div className="space-y-3">
        <Field label="Role">
          <select
            value={role}
            onChange={(e) => setRole(e.target.value as 'user' | 'admin')}
            className="rounded border border-border bg-bg px-2 py-1 text-xs text-text outline-none focus:border-accent"
          >
            <option value="user">User</option>
            <option value="admin">Admin</option>
          </select>
        </Field>
        <Field label="New Password (leave blank to keep current)">
          <input
            type="password"
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
            className="w-full rounded border border-border bg-bg px-2 py-1 text-xs text-text outline-none focus:border-accent"
            placeholder="Unchanged"
          />
        </Field>
      </div>
      <div className="mt-4 flex justify-end gap-2">
        <button
          onClick={onClose}
          className="rounded border border-border px-3 py-1 text-xs text-text hover:bg-bg"
        >
          Cancel
        </button>
        <button
          onClick={handleSubmit}
          disabled={loading}
          className="rounded bg-accent px-3 py-1 text-xs text-white hover:bg-accent/80 disabled:opacity-50"
        >
          {loading ? 'Saving\u2026' : 'Save'}
        </button>
      </div>
    </ModalOverlay>
  )
}

// ── Shared helpers ─────────────────────────────────────────────────────

function ModalOverlay({
  onClose: _onClose,
  title,
  children,
}: {
  onClose: () => void
  title: string
  children: React.ReactNode
}) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={_onClose}>
      <div className="w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl" onClick={(e) => e.stopPropagation()}>
        <h4 className="mb-3 text-sm font-semibold text-text">{title}</h4>
        {children}
      </div>
    </div>
  )
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="space-y-1">
      <label className="block text-[11px] text-text-muted">{label}</label>
      {children}
    </div>
  )
}
